Adam Starrh
Adam Starrh

Reputation: 6958

Django Forms - Custom Date Input

I am having an issue clearing a date through the following form:

class CreateArtistProfile(forms.ModelForm):
    focus_str = forms.CharField()
    birthdate = forms.DateField(input_formats="%d %B, %Y")
    occupation = forms.CharField(required=False)
    tagline = forms.CharField(required=False)

    class Meta:
        model=ArtistAccount
        fields = ['artist_name', 'location', 'occupation', "type_label", "map_input", "tagline", "birthdate"]

I am using Materialize's datepicker, and trying to submit the date string it gives me. If I select a date, the field value looks like this

30 September, 2004

But Django continues to reject it:

('birthdate', 'Enter a valid date.')

I think I've set the correct date formats. Am I doing something else wrong? Is there a different way to adjust Django's format expectations before the cleaning process?

Upvotes: 0

Views: 1547

Answers (2)

Satendra
Satendra

Reputation: 6865

Add widgets for birthdate field.

birthdate should be models.DateField of model ArtistAccount

class CreateArtistProfile(forms.ModelForm):
    focus_str = forms.CharField()
    occupation = forms.CharField(required=False)
    tagline = forms.CharField(required=False)

    class Meta:
        model=ArtistAccount
        fields = ['artist_name', 'location', 'occupation', "type_label", "map_input", "tagline", "birthdate"]
        widgets = {
           'birthdate': forms.DateInput(format=('%d %B, %Y'), attrs={'class': 'datepicker'}),
        }

Upvotes: 1

Adam Starrh
Adam Starrh

Reputation: 6958

I can't figure out how to get the custom date through Django's forms. Hopefully someone can post with an answer, but for now, here is my workaround:

First, I removed 'birthdate' from the required model fields and converted it to a CharField:

class CreateArtistProfile(forms.ModelForm):
    focus_str = forms.CharField()
    birthdate = forms.CharField()
    occupation = forms.CharField(required=False)
    tagline = forms.CharField(required=False)

    class Meta:
        model=ArtistAccount
        fields = ['artist_name', 'location', 'occupation', "type_label", "map_input", "tagline"]

Then in my view I added some extra processing:

@require_POST
def create_artist_profile(request):
    if request.method == 'POST':
        form = forms.CreateArtistProfile(request.POST)
        if form.is_valid():
            string = request.POST["birthdate"]
            birthdate = datetime.strptime(string, "%d %B, %Y")
            form.instance.birthdate = birthdate
            form.save()
            json_obj = {"success": True}
            return JsonResponse(json_obj)
        else:
            return JsonResponse({'success': False, 'errors': [(k, v[0]) for k, v in form.errors.items()]})

Upvotes: 0

Related Questions