所以我正在建立一个基本的问答网站——每个主题都有一系列与之相关的问题,每个问题都有与之相关的多个答案。
我正在为问题创建用户输入,它们必须与一个主题相关联。这是问题模型
#models.py
class Question(models.Model):
movie = models.ForeignKey(Movie, blank=True, null=True)
question_text = models.CharField(max_length = 1000)
question_detail = models.CharField(max_length = 5000, blank = True, null = True)
q_pub_date = models.DateTimeField(auto_now_add = True)
q_author = models.ForeignKey(User)
class QuestionForm(ModelForm):
def save(self, user = None, force_insert = False, force_update = False, commit = True):
q = super(QuestionForm, self).save(commit = False)
q.q_author = user
if commit:
q.save()
return q
class Meta:
model = Question
exclude = ('movie', 'q_author', 'q_pub_date')
这是网址配置
#urls.py
url(r'^(?P<movie_id>\d+)/add_question/$', 'add_question'),
现在这里是视图
#views.py
def add_question(request, movie_id):
if request.method == "POST":
form = QuestionForm(request.POST, request.FILES)
#QuestionForm.movie = Movie.objects.get(pk = movie_id)
if form.is_valid():
form.save(user = request.user)
return HttpResponseRedirect("/home/")
else:
form = QuestionForm()
return render_to_response("qanda/add_question.html", {'form': form}, context_instance = RequestContext(request))
这是 HTML 代码
#add_question.html
<h1> Add Question: {{ user.username }}</h1>
<form action = "" method = "post">{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value = "Ask" />
<input type = "hidden" name = "next" value = "{{ next|escape }}" />
</form>
在视图中,注释掉的行是我添加到视图中以尝试自动保存模型的内容。添加问题时,URL 具有与其关联的电影的 ID,我的想法是获取该 ID,然后将其插入 ForeignKey 以识别与问题关联的电影。但是,当我使用我的代码时,它会将所有问题的电影关联更改为当前电影,而不仅仅是更改该特定问题的电影关联。没有代码,它根本不会将电影与问题相关联。我该如何解决?