为什么我的Django表单不会产生任何错误? [英] Why my Django form is not raising any error?

查看:104
本文介绍了为什么我的Django表单不会产生任何错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表单,每当用户在表单上做错误的事情时,我想在Django上提出一个验证错误。问题是我设置了它,但是当表单被错误的值赋值时,它会通过。我想知道为什么会发生这种情况,以及如何避免这种情况?

以下是html表单:

 < form id =ask-projectmethod =postaction ={%url'ask-project'%}> 
{%csrf_token%}

< input required =requiredclass =form-control form-text requiredid =prenomname =prenomtype =text >

< button class =btn btn-default submit>提交< / button>
< / form>

views.py:

  def askProject(request):
if request.method =='POST':
form = AskProjectForm(request.POST)
如果form.is_valid():
save_it = form.save(commit = False)
save_it.save()
return redirect('/ merci /')#success

forms.py:

 class AskProjectForm(forms.ModelForm):$ b $ class Meta:
model = AskProject
fields = ['prenom']

def clean_prenom(self):
prenom = self.cleaned_data ['prenom']
if len(prenom)< 3:
raise ValidationError('Votreprénomdoit etre plus long que 1caractère。')
return prenom

我做错了什么?

解决方案

有了你使用的模式,这类问题是不可避免的和一天的秩序。首先不要像你所做的那样手动渲染表单。这意味着当用户输入无效数据时,您不会显示任何反馈。考虑使用 {{form}} {{form.as_table}} 等,或者将所有信息渲染为这里描述: https://docs.djangoproject.com/ zh / 1.11 / topics / forms /#rendering-fields-manually

第二个问题是您在提交表单时重定向,不管它是有效与否。建议的模式仅在表单有效时才重定向。所以即使你在第一段中应用了这个建议,你仍然没有得到所需的反馈。考虑按照手册中的建议实施表格。如果request.method =='POST':
#创建一个表单实例并填充它来自请求的数据:
form = NameForm(request.POST)
#检查它是否有效:
如果form.is_valid():
#处理表单中的数据.cleaned_data根据需要
#...
#重定向到一个新的URL:
return HttpResponseRedirect('/ thanks /')

#如果GET(或任何其他方法),我们将创建一个空白表单
else:
form = NameForm()

return render(request,'name.html',{'form':表单}}

最后介绍为什么表单验证无效的具体情况,在你的clean方法中打印语句来打印出字符串和它的长度,看它是否符合(或者你的方法甚至被调用)。

I have a simple form and whenever the user do something wrong on the form i'd like to raise a validation error on Django. The problem is that I set it up but when the form is submited with wrong values, it goes through. I was wondering why it's happening and how I can avoid that ?

Here is the html form :

<form id="ask-project" method="post" action="{% url 'ask-project' %}">
  {% csrf_token %}

  <input required="required" class="form-control form-text required" id="prenom" name="prenom" type="text">

  <button class="btn btn-default submit">Submit</button>
</form>

views.py :

def askProject(request):
    if request.method == 'POST':
        form = AskProjectForm(request.POST)
        if form.is_valid():
            save_it = form.save(commit=False)
            save_it.save()
            return redirect('/merci/') #success

forms.py :

class AskProjectForm(forms.ModelForm):
    class Meta:
        model = AskProject
        fields = ['prenom']

    def clean_prenom(self):
        prenom = self.cleaned_data['prenom']
        if len(prenom) < 3:
            raise ValidationError('Votre prénom doit etre plus long que 1 caractère.')
        return prenom

Am I doing something wrong ?

解决方案

With the pattern that you are using, this sort of problem is inevitable and order of the day. The first thing is not to render the form manually as you appear to be doing. That means you are not showing any feedback when the user enters invalid data. Consider using {{ form }}, {{ form.as_table }} etc or rendering the fields with all information as described here: https://docs.djangoproject.com/en/1.11/topics/forms/#rendering-fields-manually

Second problem is that you are redirecting when the form is submitted, regardless of whether it's valid or not. The recommended pattern is to redirect only when the form is valid. So even if you apply the suggestion in the first para, you are still not getting the required feedback. Consider implementing the form as suggested in the manual. A straight copy past follows

if request.method == 'POST':
    # create a form instance and populate it with data from the request:
    form = NameForm(request.POST)
    # check whether it's valid:
    if form.is_valid():
        # process the data in form.cleaned_data as required
        # ...
        # redirect to a new URL:
        return HttpResponseRedirect('/thanks/')

# if a GET (or any other method) we'll create a blank form
else:
    form = NameForm()

return render(request, 'name.html', {'form': form})

Finally getting onto the specific case of why your form validation doesn't work, add a print statement in your clean method to print out both the string and it's length see if it tallies (or if your method even gets called)

这篇关于为什么我的Django表单不会产生任何错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆