我正在试图绕过CBV。在这里,我使用CreateView为我的模板提供一个表单来创建新模型(通过POST)。当我向表单提供有效数据时,它会提交并返回到同一页面,就像表单有错误一样,但它不会。 HTTP POST后页面刷新时不会显示错误。我知道验证是有效的,因为我测试了我在相应表单字段中没有提供某些数据的情况,并且有与之关联的错误消息。我检查数据库,没有插入记录。我的数据库配置正确。我有应用程序的其他部分从中读取。该数据库还具有通过South应用于它的所有当前迁移。
我希望有人可以了解一下CBV的简单基本设置。
提前致谢。
models.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)
forms.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',)
views.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)
urls.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>
...
答案 0 :(得分:0)
我认为您应该将title
字段称为form.cleaned_data['title']
而不是form.title
。提交的有效字段值位于form.cleaned_data
dict。
所以将代码更改为
def form_valid(self, form):
try:
Guide.objects.get(title=form.cleaned_data['title'])
except ObjectDoesNotExist:
return super(NewGuideView, self).form_valid(form)
return super(NewGuideView, self).form_invalid(form)
评估form.title
会导致AttributeError
未在您的方法中处理。