在formview django中使用表单呈现其他信息

时间:2017-03-06 15:08:24

标签: python django

我正在为django编写联系人应用程序,用户可以联系另一个响应特定帖子的应用程序。这是我的消息模型:

class Message(models.Model):
    person_src = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    person_dst = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    replyTo = models.ForeignKey("self", on_delete=models.CASCADE) # reply to another message
    post = models.ForeignKey(Post, on_delete=models.CASCADE)    # posts concerned by the message

    date = models.DateTimeField()
    content = models.CharField(max_length=1000)

这是我的django消息表格

class NewMessageForm(forms.ModelForm):
    content = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = Message
        fields = ['content']

相关观点:

class NewMessageFormView(View):
    form_class = NewMessageForm
    template_name = 'messaging/new_message.html'

    #get just displays an empty form
    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():
            message = form.save(commit=False)
            message.content = request.content
            message.date = datetime.date.today()

            message.save()

            if message is not None:
                return redirect('messages:detail', message.id)

        return render(request, self.template_name, {'form': form})

我希望能够发送除表单,用户正在响应的相关帖子以及与当前消息相关联的所有先前消息(如果用户正在回答)。是否可以在视图中呈现其他信息?

1 个答案:

答案 0 :(得分:1)

将其添加到上下文(表单所在的字典)中:

    return render(request, self.template_name, {'form': form, 'additional_item_1': additional_item_1_value}) 

使用您使用的密钥在模板中访问它:

{{ additional_item_1 }}