我有两个模型一个是问题一个是答案当我提交答案时form它抛出一个错误,像这样:IntegrityError at/answer/NOT NULL constraint failed: answer_answer.post_id我试图通过添加blank=False来修复它零= False和并删除了我的迁移,但错误仍然存在。请问我怎样才能解决这个问题?
我想要一个用户能够发布一个问题的答案,错误来自我的My_Answer视图并突出显示这行代码:
return super (My_Answer,self).form_valid(form)
我的模型class Question(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100, blank=False, null=False)
body = RichTextField(blank=False, null=False)
category = models.CharField(max_length=50, blank=False, null=False)
def __str__(self):
return str(self.user)
class Answer(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
answer = RichTextField(blank=False, null=False)
post = models.ForeignKey(Question, on_delete=models.CASCADE)
def __str__(self):
return str(self.user)
视图
def viewQuestion(request, pk):
question = Question.objects.get(id=pk)
answers = Answer.objects.filter(post_id=question)
context = {'question':question, 'answers':answers}
return render(request, 'viewQuestion.html', context)
class My_Question(LoginRequiredMixin, CreateView):
model = Question
fields = ['title', 'body', 'category']
template_name = 'question.html'
success_url = reverse_lazy('index')
def form_valid(self, form):
form.instance.user = self.request.user
return super (My_Question, self).form_valid(form)
class My_Answer(LoginRequiredMixin, CreateView):
model = Answer
fields = ['answer']
template_name = 'answer.html'
success_url = reverse_lazy('index')
def form_valid(self, form):
form.instance.user = self.request.user
return super (My_Answer, self).form_valid(form)
viewQuestion模板:
<div class="container">
<div class="row justify-content-center">
<h1>{{question.title}}</h1>
<hr>
</div>
<br>
<h3 style="font-family: arial;">{{question.body|safe}}</h3>
<hr>
<br>
<h5>{{question.user.username.upper}}</h5>
</div>
<!--question-->
<div class="container">
<div class="row justify-content-center">
<a href="{% url 'answer' %}" class="btn btn-primary">Post Your Answer</a>
</div>
</div>
<br>
<br>
<!--answer-->
<div class="container">
{% for answer in answers reversed %}
<div class="row justify-content-center">
<p>{{answer.user}}</p>
<p>{{answer.answer|safe}}</p>
</div>
{% endfor %}
</div>
谢谢你的帮助。
您正在保存一个答案实例,其中只有来自表单的答案和来自请求用户的用户,但其中有一个post id,该id不能为none,并且是必需的。
你的url模式应该是这样的
urlpatterns = [
path('question/<int:pk>/', viewQuestion, name='view-question'),
path('question/<int:pk>/answer/', My_Answer.as_view(), name='answer'),
]
你只需要将viewQuestion.html中的url更改为
<div class="row justify-content-center">
<a href="{% url 'answer' pk=question.pk %}" class="btn btn-primary">Post Your Answer</a>
</div>
在回答视图中为
def form_valid(self, form):
form.instance.user = self.request.user
form.instance.post_id = self.kwargs['pk']
return super (My_Answer, self).form_valid(form)
基本上你是在保存没有postpk的答案实例,我在url参数中传递了postpk并在答案post视图中保存到form实例中。现在应该可以工作了!