开发者

"Field is required message" before submitting form

I am trying to throw 'Field required' messages once the user has submitted a form and they have not filled the required fields.

What is happening is that the error is being showed even before the form has been submitted. Isn't the validation supposed to be done after the submission?

I have the following form:

class LookforPlace(forms.Form):
    name = forms.CharField(requ开发者_开发问答ired=True,max_length=100,label='Name',error_messages = {'required': "This field is required..."})
    city = forms.CharField(required=False,label='City')
    email = forms.EmailField()

I have the following view:

def newreview(request):
    if request.method == 'GET': # If the form has been submitted...
        form = LookforPlace(request.GET) # A form bound to the GET data
        if form.is_valid(): # All validation rules pass
            return HttpResponseRedirect('/newreview/valid') # Redirect after GET
    else:

        form = LookforPlace() # An unbound form
    return render_to_response('newreview.html', {
        'form': form,
    })

And I have the following HTML code:

 <form action="/newreview/" method="get">
{% for field in form %}
        <div class="fieldWrapper">
            {{ field.errors }}
            {{ field.label_tag }}: {{ field }}
        </div>
    {% endfor %}
<input type="submit" value="Submit" />
</form>


A GET is issued when you browse to a page normally, not just when you submit a form with that method - if you want to use the same view to display an initial form and handle submission via GET, you should check for a value from the form having been submitted.

One option is to give the submit button a name...

<input type="submit" name="submit" value="Submit">

...and check for that name having been submitted as a parameter (this is also a good way to handle forms with multiple submit buttons, as only the button which was clicked will count as a successful control and have its name submitted as a parameter in the request):

if 'submit' in request.GET:
    # ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜