基于类的视图:FormView,如何从success_url()中的form_valid()访问变量

时间:2017-09-13 17:34:11

标签: django django-forms django-views

我有一个简单的电子邮件表单工作正常,但我想访问recipient中的success_url(),因此我可以将一封简单的“电子邮件发送到recipient”消息模板。

class FullEmailView(FormView, MyCustomMixin):
    form_class = EmailForm
    template_name = 'my_app/email_form.html'

    def form_valid(self, form, **kwargs):
        x = MyModel.objects.get(pk=self.kwargs['pk'])
        recipient = form.cleaned_data.get('email_address')
        subject = "My Email Subject"
        sender = "me@myemail.com>"
        html_message = render_to_string('my_app/email.html', {
            'x': x,
            'recipient': recipient,
        })
        message = render_to_string('my_app/email.html')
        send_mail(
            subject,
            message,
            sender,
            [recipient],
            html_message = html_message
        ) 
        return super(FullEmailView, self).form_valid(form)

    def get_success_url(self, form, **kwargs):
        x = MyModel.objects.get(pk=self.kwargs['pk'])
        recipient =  #????  <<<--- what do I put here to access recipient from from_valid()?
        return super(FullEmailView, self).reverse_lazy('email_sent', self, kwargs={"pk": x.pk})

1 个答案:

答案 0 :(得分:1)

为此,您可以使用django

消息框架

使用以下代码添加消息:

  messages.add_message(self.request, messages.INFO, 'Email has been sent!')

所以你的form_valid()函数可以改为:

  from django.contrib import messages
   #... 
   def form_valid(self, form, **kwargs):
          x = MyModel.objects.get(pk=self.kwargs['pk'])
          recipient = form.cleaned_data.get('email_address')
          subject = "My Email Subject"
          sender = "me@myemail.com>"
          html_message = render_to_string('my_app/email.html', {
          'x': x,
        'recipient': recipient,
         })
    message = render_to_string('my_app/email.html')
    send_mail(
        subject,
        message,
        sender,
        [recipient],
        html_message = html_message
    ) 
     messages.add_message(self.request, messages.INFO, 'Email has been sent!')
    return super(FullEmailView, self).form_valid(form)
 #....

可以通过

在模板上访问该消息
 {% if messages %}
 <ul class="messages">
   {% for message in messages %}
    <li>{{ message }}</li>
   {% endfor %}
 </ul>
 {% endif %}

有关消息的更多信息:https://docs.djangoproject.com/en/1.11/ref/contrib/messages/