Mohan
Mohan

Reputation: 949

How to validate form if empty values passed to form fields in Django?

Below is the form:

struggling to validate form with sending empty values for some form fields.

enter image description here

Name and phone were mandatory field. When user type and click submit, All the values should be concatenated and save it in file.

forms.py

from django import forms

class ReviewForm1(forms.Form):
    PRECAUTIONS_CHOICES = (
        ('no', 'No'),
        ('yes', 'Yes')
    )
    UNIT1_CHOICES = (
        ('Very Satisfied', 'Very Satisfied'),
        ('Satisfied', 'Satisfied'),
        ('neutral', 'neutral'),
        ('Unsatisfied', 'Unsatisfied'),
        ('Very Unsatisfied', 'Very Unsatisfied'),
    )
    name = forms.CharField(required=True, widget=forms.TextInput(attrs={'required': 'true'}))
    phone = forms.CharField(required=False)
    email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'required': 'true'}))
    precautions = forms.ChoiceField(required=True, choices= PRECAUTIONS_CHOICES, widget=forms.Select())
    unit1_ambience = forms.ChoiceField(required=True, choices= UNIT1_CHOICES, widget=forms.Select())
    review = forms.CharField(required=False, widget=forms.Textarea())

    def clean(self):
        name = self.cleaned_data.get('name')
        phone = self.cleaned_data.get('phone')
        review = self.cleaned_data.get('review')
        email = self.cleaned_data.get('email')
        precautions = self.cleaned_data.get('precautions')
        unit1_ambience = self.cleaned_data.get('unit1_ambience')
        expected_string = ''
        options = [name,phone,review,email,precautions,unit1_ambience]
        for option in options:
            if not option:
                continue
            else:
                expected_string = expected_string + option + '\n'

        # concat all with review and then return string
        return expected_string

views.py snippet

@require_POST
@csrf_protect
def revfile_save(request):
   """
   This page processes and saves review file.
   """
   form = ReviewForm1(request.POST)
    if form.is_valid():
        review = form.cleaned_data
   reviewfile_name = "/root/sjfacweb/" + remote.sjfacweb()
   #content writes to timestamped filename
   remote.write_reviewfile(reviewfile_name,False,review)

Below is the error I am getting when clicked save:

local variable 'review' referenced before assignment

I think form.is_valid() returns false, how to fix this issue?

Thanks

Upvotes: 0

Views: 2259

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599470

This doesn't have anything to do with "empty fields". The rest of that view should be within the is_valid block, and you should do something else - ie re-render the template with the invalid form - when the form is not valid.

form = ReviewForm1(request.POST)
if form.is_valid():
    review = form.cleaned_data
    reviewfile_name = "/root/sjfacweb/" + remote.sjfacweb()
    #content writes to timestamped filename
    remote.write_reviewfile(reviewfile_name,False,review)
    return redirect('somewhere')
else:
    return render(request, 'template.html', {'form': form})

Note though that clean() should return the cleaned data as a dict, not a concatenated string; the concatenation should be done somewhere else.

Upvotes: 1

Related Questions