form.is_valid() is always returning false without showing any errors

不打扰是莪最后的温柔 提交于 2019-12-11 13:38:00

问题


I am pretty new to python and Django and I am using the built-in user system of Django to create a registration from. Here's my view `

def register_user(request):
    if request.method == 'POST':
        form = UserCreationForm(data=request.POST)
        if form.is_valid():
            form.save()
            #print 'success'
            return HttpResponseRedirect('/accounts/register_success')
        #print 'fail'

    args = {}
    args.update(csrf(request))

    args['form'] = UserCreationForm()
    #print args
    return render_to_response('register.html',args)

` and here's the register.html template.

{% extends "base.html" %}

{% block content %}

    <h2>Register</h2>
    <form action="/accounts/register/" method="post">{% csrf_token %}
      {{ form.errors }}

      {{ form.non_field_errors }}

      {{form}}

    <input type="submit" value="Register" />
    </form>
{% endblock %}

No matter what, form.is_valid() is always returning false without giving out any errors. I have been trying it since forever.

EDIT: I changed the view to the below one, it is working now, but I am not getting the exact reason, also there are no indentation errors in both the views.

def register_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success')

    else:
        form = UserCreationForm()
    args = {}
    args.update(csrf(request))

    args['form'] = form

    return render_to_response('register.html', args)

Any help is greatly appreciated. Thanks in advance :D and also Happy new year :P.


回答1:


It doesn't show any errors because you always re-instantiate a new, unbound, form. Don't do that; the pattern in the docs is perfectly clear and you should follow it.

if request.method == 'POST':
    form = UserCreationForm(data=request.POST)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/accounts/register_success')
else:
    form = UserCreationForm()

args = {}
args.update(csrf(request))

args['form'] = form
return render_to_response('register.html',args)



回答2:


You don't have any else condition in your views; you have tor write args['form'] = UserCreationForm() starting of the function; ex;

def register_user(request):
   args = {}
   args['form'] = UserCreationForm()
   if request.method == 'POST':
       form = UserCreationForm(data=request.POST)
       if form.is_valid():
           form.save()

           return HttpResponseRedirect('/accounts/register_success')
   args.update(csrf(request))
   return render_to_response('register.html',args)


来源:https://stackoverflow.com/questions/34550027/form-is-valid-is-always-returning-false-without-showing-any-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!