有三个模型:用户,问答。
我的方式可以工作 - 跨越答案Modelform的save
方法,传递两个对象(问题和用户。
我不确定这是官方方式还是最好的方法。还是在这种情况下有一些很好的教程,谢谢。
这是代码:
#settings.py
#ROOT urls.py
urlpatterns = patterns('',
url(r'^$', 'myauth.views.home', name='home'),
url(r'^questions/', include('questions.urls',namespace='questions')),
)
#urls.py
urlpatterns = patterns('questions.views',
url(r'^(?P<question_pk>d+)/detail/$',
'detail',
{'template_name': 'questions/detail.html'},
name='detail'),
)
#models.py
class User(AbstractBaseUser):
username = models.CharField()
class Question(models.Model):
user = models.ForeignKey(User)
title = models.CharField()
content = models.TextField()
class Answer(models.Model):
#user create an anwer to a question
user = models.ForeignKey(User)
question = models.ForeignKey(Question)
content = models.TextField()
#forms.py
class AnswerForm(ModelForm):
class Meta:
model = Answer
fields = ['content']
#this is my way
#pass two objects:user and question to it
def save(self,user,question,commit=True,):
answer = super(AnswerForm,self).save(commit=False)
answer.user = user
answer.question = question
if commit:
answer.save()
return answer
#views.py
def detail(request,
question_pk,
template_name,
answer_create_form=AnswerForm):
"""detail to show a question,contains:
1.question's title and content.
2.all answers(represented by field 'content')to this question
3.a form for create an answer to this question
"""
#question object is identified by question_pk from the url string.
#along with request.user, both will be passed to the form to
#create answer objects.
question = Question.objects.get(pk=question_pk)
user = request.user
#all answers to this question
answers = question.answer_set.all()
form=None
if user.is_authenticated():
if request.method == 'POST':
form = answer_create_form(data=request.POST)
if form.is_valid():
form.save(user=user,question=question)
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
else:
form = answer_create_form()
return TemplateResponse(request, template_name, locals(),)
#questions/detail.html
#rest ommitted...
{% if form %}
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="回答" />
</form>
{% endif %}
我认为您需要阅读此内容。因此,您应该做些类似的东西:
question = Question.objects.get(pk=question_pk)
user = request.user
(....)
if user.is_authenticated():
if request.method == 'POST':
answer = Answer(question=question, user=user)
form = AnswerForm(data=request.POST, instance=answer)
if form.is_valid():
form.save()
(....)