Search code examples
pythondjangodjango-formsdjango-validation

Django form validation: required fields not displaying errors when blank


im trying to build a simple form with some simple validation rules.

the problem i am having is that fields that are supposed to be required are not causing any validation prompts to appear in the form page when i try to submit the form. As in, when i submit a completely blank form, i get redirected to my specified page instead of having any valifation error promts appear.

The form does not actually any data to the database though, so it looks like the is_valid function is working fine, and if i enter a string where an integer should be, i get my error messages ok. So im wondering if you normally have to do some extra coding to have some 'field required' messages appear. currently i am letting django take care of all the validation, and i am not creating any custom rules. heres some code:

the model

class Advert(models.Model):
    user = models.ForeignKey(User)
    category = models.ForeignKey('Category')
    title = models.CharField(max_length=100, null=False, blank=False)
    description = models.TextField()
    price = models.IntegerField(null=False, blank=False)
    image = models.FileField(upload_to=get_upload_file_name, null=True)
    location = models.CharField(max_length=50, null=False, blank=False)
    pub_date = models.DateField(auto_now_add=True)

something i want to note is that after adding these to the model, makemigrations did not detect the changes, but i think its assumed that null=False when not explicity specified? and in the ModelForm, required=True is assumed also no?

the form

class AdvertForm(forms.ModelForm):
    class Meta:
        model = Advert
        exclude = ['user']

the view file

def create_advert(request):
    if request.POST:
        form = AdvertForm(request.POST, request.FILES)
        if form.is_valid():
            ad = form.save(False)
            ad.user = request.user
            ad.save()

        return HttpResponseRedirect('/adverts/list_adverts/0/')

    else:
        c = {}
        c.update(csrf(request))
        c['form'] = AdvertForm()
        return render(request, 'create_advert.html', c)

so is_valid is working, the record is not saved, but im getting no error prompts for leave required fields blank.

is there something im missing?


Solution

  • Because you're redirecting even if the form is not valid. Instead, you should stay on the same view and re-render the form. The view should look like this:

    def create_advert(request):
        if request.POST:
            form = AdvertForm(request.POST, request.FILES)
            if form.is_valid():
                ad = form.save(commit=False)
                ad.user = request.user
                ad.save()
                return HttpResponseRedirect('/adverts/list_adverts/0/')
    
        else:
            form = AdvertForm()
    
        return render(request, 'create_advert.html', {'form': form})
    

    (Note there's no point in manually adding the CSRF token, the context processors will do so since you are using the render shortcut.)