LeLouch
LeLouch

Reputation: 611

display and update DateField using a custom form in django

i'm trying to display and update a DateField using my custom form , i'm using DATE_INPUT_FORMATS like that

settings.py

DATE_INPUT_FORMATS = ['%d %m %Y']

forms.py

class UserForm(forms.ModelForm):
    birth_day = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS)
    class Meta:
        model = User
        fields = ('first_name', 'last_name','birth_day')

my custom inpute :

<input type="text" name="birth_day" value="{{ user.birth_day }}" size="10" class="form-control date-picker" id="id_birth_day" data-datepicker-color="">

default form inpute

<input type="text" name="birth_day" value="" required="" id="id_birth_day" class="form-control">

my problem starts everytime i'm trying to update the i have to re-enter the DateField since my DATE_INPUT_FORMATS is like that

06 02 2017

but django display it like that

Feb 6th, 2017

so h

so every time i update my form i get

Enter a valid date. error

so what it the best way to fix this problem and without changing the display and inpute format if possible

Upvotes: 1

Views: 1409

Answers (1)

Bikiran Das
Bikiran Das

Reputation: 313

I have a similar setup for your requirement which is working fine for me

HTML --- Edit.html

<p>You can edit your account using the following form:</p>
        <form action="." method="post" enctype="multipart/form-data" id="controlForm">
        {{ user_form.as_p }}
        {{ profile_form.as_p }}
        {% csrf_token %}
<p><input type="submit" value="Save changes"></p>

models.py ---->

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    date_of_birth = models.DateField(blank=False, null=True)
    img = models.ImageField(upload_to=upload_to, blank=True, db_index=True)
    slug = models.SlugField(max_length=200, blank=True)

Forms.py

class ProfileEditForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('date_of_birth', 'img')

The above code saves the date in YYYY-MM-DD Format to change the default format you can add the date format in settings.py

with DATE_INPUT_FORMT = ['YYYY-MM-DD'] or ANY format as u wish

Upvotes: 2

Related Questions