【发布时间】:2019-05-29 01:33:36
【问题描述】:
我正在尝试在我的简单论坛应用程序中测试用于创建帖子模型的表单。我遇到的问题是,在我尝试在测试中保存表单后,我收到错误NOT NULL constraint failed: forum_web_post.user_id,因为我在视图中的form_valid() 方法中分配了用户。用户不会通过表单传递,因为创建帖子的用户是发送请求的登录用户。
models.py
class Post(models.Model):
category = models.ForeignKey(Category, on_delete=models.PROTECT)
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
text = models.TextField()
created_at = models.DateTimeField(auto_now=True)
用户是从django.contrib.auth.models 导入的,类别模型如下所示。
class Category(models.Model):
name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now=True)
在views.py 中,用户提交表单后,他被重定向到他的个人资料页面
views.py
class PostCreate(generic.CreateView):
model = Post
form_class = PostForm
template_name = 'forum_web/post_edit.html'
def form_valid(self, form):
post = form.save(commit=False)
post.user = models.User.objects.get(id=self.request.user.id)
post.save()
return HttpResponseRedirect(reverse_lazy('forum:user_detail', kwargs={'pk': self.request.user.id}))
forms.py
class PostForm(ModelForm):
class Meta:
model = Post
fields = ['category', 'title', 'text']
tests.py
def test_post_form_create_should_pass(self):
# this dict is in setUp() as well as the test_category but for simplicity I will include it in this method
post_data = {
'category': self.test_category.pk,
'title': 'test_post',
'text': 'test_post_text'
}
post_count = Post.objects.count()
form = PostForm(data=self.post_data)
self.assertTrue(form.is_valid())
form.save()
self.assertEqual(post_count + 1, Post.objects.count())
任何帮助将不胜感激!
【问题讨论】:
标签: python django django-forms django-testing