[英]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: 我想知道如何做两件事:
DateTimeField
that I have in the admin interface? DateTimeField
相同的输入类型? (with the Today and Now functions) 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.