我正在建立一个论坛,我有一个令人厌烦的小问题。 我需要生成一个包含表单的页面来填充一个 model,但该页面还应显示其他相关模型的条目。 我希望表单在模型响应中填充新响应(请参阅下面的代码)。 该模型将模型StartMsg作为外键。我希望页面视图(response_form)显示用户正在响应的StartMsg.msg。问题是我使用django的内置表单来生成表单,并使用render_to_response来调用页面。 render_to_response语句(标记为(A))将包含Responseses模型中的表单组件的字典发送到html模板。
如何将有关模型StartMsg的信息包含在render_to_response语句中(标记为 与(A),下面)?有没有更好的方法来实现我的目标?
以下是模型:
class StartMsg (models.Model):
msg_title = models.TextField(max_length=500)
msg = models.TextField(max_length=2000)
pub_date = models.DateTimeField('date published')
author = models.ForeignKey(User)
def __unicode__(self):
return self.msg
class Responses (models.Model):
startmsg = models.ForeignKey(StartMsg) #one startmsg can have many responses
response = models.TextField()
responder = models.ForeignKey(User)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.response
下面是表单处理函数,后跟表单模型。
def response_form (request, msg_id):
msg = get_object_or_404(StartMsg, pk=msg_id)
form = MsgRespForm(request.POST or None)
if form.is_valid():
new_rspns = form.save(commit =False)
#retrieve StartMsg entry to assign to the response entry foreign key
message = StartMsg.objects.get(pk=msg_id)
new_rspns.startmsg = message
response = form.cleaned_data['response']
new_rspns.response = response
new_rspns.responder= request.user.username()
new_rspns.pub_date = datetime.now()
new_rspns.save()
return HttpResponseRedirect(reverse('forum.views.forum', )) #if form is processed, view goes here
return render_to_response( #if form not processed, view goes here
'forumresponseform.html',
{'form': form}, (A)
context_instance = RequestContext(request)
)
class MsgRespForm(forms.ModelForm):
# Add Labels to form fields:
response = forms.CharField(label='Your Response',
widget=forms.Textarea(attrs={'cols': 60, 'rows': 10}))
class Meta: #Define what fields in the form
model = Responses
fields = ('response',)
答案 0 :(得分:0)
我找到了似乎有效的解决方案。 您可以创建一个函数,用于从可变数量的模型查询中构建字典,然后将该字典传递到第(A)行的表单模板。
def build_dict(request, ** kwargs):
d = dict(user=request.user, ** kwargs)
return d
msg = get_object_or_404(StartMsg, pk=msg_id)
form = MsgRespForm(request.POST or None)
dict = build_dict(request, msg=msg, form=form)
return render_to_response( #if form not processed, view goes here
'forumresponseform.html',
{'form': dict}, (A)
context_instance = RequestContext(request)
)