简体   繁体   English

如何在表单验证错误发生时指定它们?

[英]How can I specify form validation errors when they occur?

I'm quite new to Django Forms, and I'm facing a problem that I cannot solve. 我对Django Forms很新,而且我遇到了一个我无法解决的问题。 I've been googling and reading the docs, but I can't find the place where this is explained. 我一直在谷歌搜索和阅读文档,但我找不到这个解释的地方。 My problem is that I have an Animal Model and a ModelForm : 我的问题是我有一个动物 Model和一个ModelForm

class Animal(models.Model):
    name = models.CharField(max_length=300)
    age = models.PositiveSmallIntegerField()
    race = models.ForeignKey(Race)
    description = models.TextField()
    state = models.ForeignKey(State)
    pub_date = models.DateTimeField(auto_now_add=True)
    adoption_limit = models.DateTimeField(blank=True, null=True)
    location = models.ForeignKey(Location)
    publisher = models.ForeignKey(User)
    def __unicode__(self):
        return self.name

class AnimalForm(ModelForm):
    class Meta:
        model = Animal

I render this info via urls.py, calling this view: 我通过urls.py呈现此信息,调用此视图:

@login_required
def new_animal(request):
    if request.method == "POST":
        form = AnimalForm(request.POST)
        if form.is_valid():
            form.save()
            return render_to_response('/')
        else:
            variables = RequestContext(request, {'e': form.errors})
            return render_to_response('web/error.html', variables)
    else:
        form = AnimalForm()
    variables = RequestContext(request, {'form': form})
    return render_to_response('web/animal_form.html', variables)

It seems that I have an error introducing the adoption_limit field, so the data does not get saved in DB. 似乎我在引入adoption_limit字段时出错,因此数据不会保存在DB中。 This is because I just set a date and not a time into the text field displayed by the form. 这是因为我只是在表单显示的文本字段中设置了日期而不是时间。

I would like to know how can I do two things: 我想知道如何做两件事:

  1. How can I send the error message to the form again, so that I can add a text next to the field that I have not set correctly? 如何将错误消息再次发送到表单,以便我可以在我未正确设置的字段旁边添加文本? Ie, like the admin does. 就像管理员一样。
  2. How can I put the same input type for DateTimeField that I have in the admin interface? 如何为管理界面中的DateTimeField相同的输入类型? (with the Today and Now functions) (使用Today和Now功能)

The way you have written your view, to display form errors, in your web/error.html template, simply output the errors: 您在web/error.html模板中编写视图,显示表单错误的方式,只需输出错误:

{%if e %}
  You had some errors in your submission!<br />
  {{ e }}
{% endif %}

However, you don't have explicitly pass the errors list, it is part of the form itself. 但是,您没有显式传递错误列表,它是表单本身的一部分。 A bit of simplification: 一点简化:

variables = RequestContext(request, {'form': form})
return render_to_response('web/error.html', variables)

Then, in your template: 然后,在您的模板中:

{% if form.errors %}
   You have some errors!<br />
   {{ form.errors }}
{% endif %}

For the second part of your question - to display the django date time widget - things get a bit more involved: 对于问题的第二部分 - 显示django日期时间窗口小部件 - 事情变得更加复杂:

# First, you need to import the widget:
from django.contrib.admin.widgets import AdminSplitDateTime
from django.forms import TextField

# In your form class, you have to specify the widget
# for the field.

class AnimalForm(forms.ModelForm):
   pub_date = models.TextField(widget=AdminSplitDateTime)
   class Meta:
      model = Animal

In order for this to work though, you have to make sure your admin media directory is accessible from your project (since all the javascript and css is included there). 为了使其工作,您必须确保您的管理媒体目录可以从您的项目访问(因为所有的javascript和css都包含在那里)。 You'll also to have make sure that all the stylesheets are also added. 您还要确保还添加了所有样式表。 It is much easier (and simpler) to use your own javascript form widget from your preferred library. 从首选库中使用您自己的javascript表单小部件会更容易(也更简单)。

Finally, as stated in the documentation , if you override any fields, you need to add all the other validation logic yourself: 最后,如文档中所述,如果覆盖任何字段,则需要自己添加所有其他验证逻辑:

If you explicitly instantiate a form field like this, Django assumes that you want to completely define its behavior; 如果你明确地实例化这样的表单字段,Django假定你想要完全定义它的行为; therefore, default attributes (such as max_length or required) are not drawn from the corresponding model. 因此,不会从相应的模型中绘制默认属性(例如max_length或required)。 If you want to maintain the behavior specified in the model, you must set the relevant arguments explicitly when declaring the form field. 如果要维护模型中指定的行为,则必须在声明表单字段时明确设置相关参数。

burhan's answer is spot on. burhan的回答很明显。 Additionaly, You might probably want to hide the publisher on the form and deal with it in your view. 另外,您可能希望隐藏表单上的发布者并在您的视图中处理它。

To do this, add exclude = ('publisher',) to class Meta in your ModelForm. 为此,请将exclude =('publisher',)添加到ModelForm中的类Meta。

And then in your view: 然后在你看来:

if form.is_valid():
    animal = form.save(commit=false)
    animal.publisher = request.user
    animal.save()

Otherwise, as it stands I think your form will show all users in a dropdown, which might not be what you want. 否则,就目前而言,我认为您的表单会在下拉列表中显示所有用户,这可能不是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 WTForms与Jquery Form Plugin结合使用时如何显示验证错误? - How to display validation errors when WTForms is coupled with Jquery Form Plugin? 当我尝试在python中导入cv时,会发生一些错误。 如何修复 - When I try to import cv in python, some errors occur. How to fix it 如何覆盖 FastAPI 中 pydantic 验证错误的默认行为? - How can I overwrite the default behavior of pydantic validation errors in FastAPI? 当同一日期中出现多条消息时,如何将第一个消息标记为已诱导? - When multiple messages occur across same date how can I tag the first one as induced? 如何在Django中列出所有与表单相关的错误? - How can I list all form related errors in Django? 如何在每个字段下显示表格错误? - How can I display the form errors under each field? 如何对我的字段进行表单和字段验证? - How can i give form and field validation to my fields? Django表单验证:空白时必填字段不显示错误 - Django form validation: required fields not displaying errors when blank Django MultiValueDictKeyError什么时候发生?如何避免? - Django MultiValueDictKeyError what is it when do they occur and how can it be avoided? 如何删除文本中单词结尾处可能出现的数字 - How can I remove numbers that may occur at the end of words in a text
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM