我正试图围绕 CBV。在这里,我使用 CreateView 为我的模板提供一个用于创建新模型的表单(通过 POST)。当我为表单提供有效数据时,它会提交并返回到同一页面,就好像表单有错误一样,但事实并非如此。HTTP POST 后页面刷新时不会显示错误。我知道验证有效,因为我已经测试了未在适当的表单字段中提供某些数据的场景,并且有与之关联的错误消息。我检查了数据库,没有插入任何记录。我的数据库配置正确。我有应用程序的其他部分从中读取。该数据库还通过 South 应用了所有当前迁移。
我希望有人能对 CBV 的简单基本设置有所了解。
提前致谢。
模型.py
class Guide(models.Model):
DIFFICULTY_OPTIONS = (
(u'1', u'Easy'),
(u'2', u'So so'),
(u'3', u'Moderate'),
(u'4', u'Challenging'),
(u'5', u'Very challenging'),
)
title = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100)
description = models.CharField(max_length=500)
user = models.ForeignKey(User)
difficulty = models.CharField(max_length=1, choices=DIFFICULTY_OPTIONS, default=u'1', null=True, blank=True)
created = models.DateTimeField(default=datetime.datetime.now(), editable=False)
modified = models.DateTimeField(default=datetime.datetime.now())
publish = models.BooleanField(default=False)
delete = models.BooleanField(default=False)
表格.py
class NewGuideForm(forms.ModelForm):
title = forms.CharField(widget=forms.widgets.TextInput(attrs={'placeholder': 'Title',
'class': 'input-block-level'}))
description = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Description',
'rows': 8,
'class': 'input-block-level'}))
class Meta:
model = Guide
exclude = ('user', 'slug', 'created', 'modified', 'publish', 'delete', 'modified',)
视图.py
class NewGuideView(CreateView):
model = Guide
form_class = NewGuideForm
template_name = "guides/guide_new.html"
success_url = "/" # Just to keep things simple, redirect to root.
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(NewGuideView, self).dispatch(*args, **kwargs)
def form_valid(self, form):
try:
Guide.objects.get(title=form.title)
except ObjectDoesNotExist:
return super(NewGuideView, self).form_valid(form)
return super(NewGuideView, self).form_invalid(form)
网址.py
url(r'^guides/new/$', guide.NewGuideView.as_view(), name='guide-new'),
指南/guide_new.html
...
<form method="post">{% csrf_token %}
{{ form.non_field_errors }}
<p>First, let's start by entering a title.</p>
<p>{{ form.title.errors }}</p>
<p>{{ form.title }}</p>
<p>Now, provide a short summary of the problem you will be solving.</p>
<p>{{ form.description.errors }}</p>
<p>{{ form.description }}</p>
<p>On a scale of 1 to 5, 5 being the most difficult, how hard is this?</p>
<p>{{ form.difficulty.errors }}</p>
<p>{{ form.difficulty }}</p>
<button type="submit" class="btn-password btn btn-send">Submit</button>
</form>
...