我对django很新,我无法理解为什么会出现这个错误:
project_question_text.question_id may not be NULL
我有相互连接的模型和视图:
class Question_Text(models.Model):
text_en = models.CharField(max_length=60, blank=True)
class Question(models.Model):
user = models.ForeignKey(User)
question_text = models.ForeignKey(Question_Text)
viewed = models.BooleanField(default=False)
def __unicode__(self):
return self.question_text
并查看:
def add_question(request, project_id):
a = Project.objects.get(id=project_id)
if request.method == "POST":
f = QuestionForm(request.POST)
if f.is_valid():
c = f.save(commit=False)
c.project = a
c.save()
messages.success(request, "Your question was added")
return HttpResponseRedirect('/projects/get/%s' % project_id)
else:
f = QuestionForm()
args = {}
args.update(csrf(request))
args['project'] = a
args['form'] = f
return render_to_response('project/add_question.html', args)
请问有人建议吗?
答案 0 :(得分:0)
您确定是否使用请求参数在else条件下初始化新对象?
def add_question(request, project_id):
a = Project.objects.get(id=project_id)
if request.method == "POST":
f = QuestionForm(request.POST)
if f.is_valid():
c = f.save(commit=False)
c.project = a
c.save()
messages.success(request, "Your question was added")
return HttpResponseRedirect('/projects/get/%s' % project_id)
else:
f = QuestionForm(request.POST) #Add request params to initialization
args = {}
args.update(csrf(request))
args['project'] = a
args['form'] = f
return render_to_response('project/add_question.html', args)
答案 1 :(得分:0)
错误消息似乎表明question_id
表中有project_question_text
列,但Question_Text
模型不包含Question
的任何ForeignKey。我的猜测是,您曾经在question = models.ForeignKey(Question)
模型中使用Question_Text
这样的字段,并且在某些时候您更改了模型定义。您的数据库表仍会反映旧模式,而模型则不会。
最简单的解决方案是删除您已更改的所有表并再次运行syncdb。另一种解决方案是使用迁移(即South)。
一个稍微偏离主题的旁注,标准Python代码样式建议使用CamelCase而不使用下划线来表示类名,这意味着Question_Text
模型的名称会更好,更标准{{1} }。