我正在使用django v.1.11.3。这是我的模型字段声明。
class Post(models.Model):
slug = models.SlugField(max_length=80, unique_for_month='pub_date')
pub_date = models.DateField('date published', auto_now_add=True)
...
def get_absolute_url(self):
return reverse('blog_post_detail', kwargs={'year': self.pub_date.year,
'month': self.pub_date.month,
'slug': self.slug,})
我使用ModelForms如下创建用户表单。
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = '__all__'
def clean_slug(self):
return self.cleaned_data['slug'].lower()
但是,当我尝试输入重复的段并重定向到新创建的帖子时,它是在db中创建的,由于多个对象返回,get方法调用失败。
这是详细信息页面的URL配置和FBV。
url(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<slug>[\w\-]+)/$',
post_detail, name='blog_post_detail'),
def post_detail(request, year, month, slug):
post = get_object_or_404(Post, pub_date__year=year, pub_date__month=month,
slug=slug)
return render(request, 'blog/post_detail.html', {'post': post})
最后,这是调试数据中显示的错误。
MultipleObjectsReturned at /blog/2018/8/python-3-programming/
get() returned more than one Post -- it returned 2!
~/workspace/src/blog/views.py in post_detail
post = get_object_or_404(Post, pub_date__year=year, pub_date__month=month,
slug=slug)
我检查了数据库,并在同一个月看到两个条目。怎么了?
更新CBV代码:
class PostCreate(View):
form_class = PostForm
template_name = 'blog/post_form.html'
def get(self, request):
return render(request, self.template_name, {'form': self.form_class()})
def post(self, request):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_post = bound_form.save()
return redirect(new_post)
else:
return render(request, self.template_name, {'form': bound_form})