gpt4 book ai didi

python - 当表单验证错误发生时,我如何指定它们?

转载 作者:太空宇宙 更新时间:2023-11-04 10:57:42 25 4
gpt4 key购买 nike

我是 Django Forms 的新手,我遇到了一个我无法解决的问题。我一直在谷歌搜索和阅读文档,但我找不到解释这个的地方。我的问题是我有一个 Animal 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

我通过 urls.py 呈现此信息,调用此 View :

@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)

似乎我在引入adoption_limit 字段时出错,所以数据没有保存在DB 中。这是因为我只是在表单显示的文本字段中设置了日期而不是时间。

我想知道如何做两件事:

  1. 如何再次将错误消息发送到表单,以便我可以在未正确设置的字段旁边添加文本?即,就像管理员一样。
  2. 如何为管理界面中的 DateTimeField 输入相同的输入类型? (具有今天和现在功能)

最佳答案

您在 web/error.html 模板中编写 View 以显示表单错误的方式,只需输出错误:

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

但是,您没有明确传递错误列表,它是表单本身的一部分。稍微简化一下:

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

然后,在您的模板中:

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

对于问题的第二部分 - 显示 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

不过,为了使其正常工作,您必须确保您的管理媒体目录可以从您的项目访问(因为所有的 javascript 和 css 都包含在那里)。您还需要确保所有样式表也已添加。从您的首选库中使用您自己的 javascript 表单小部件要容易得多(也更简单)。

最后,如 documentation 中所述,如果您覆盖任何字段,您需要自己添加所有其他验证逻辑:

If you explicitly instantiate a form field like this, Django assumes that you want to completely define its behavior; therefore, default attributes (such as max_length or required) are not drawn from the corresponding model. If you want to maintain the behavior specified in the model, you must set the relevant arguments explicitly when declaring the form field.

关于python - 当表单验证错误发生时,我如何指定它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8465475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com