首页 > 解决方案 > 修改基于类的视图对象保存

问题描述

我目前有这样的模型

class Newsletter(models.Model):
    email = models.EmailField(null=False, blank=True, max_length=200, unique=True)
    conf_num = models.CharField(max_length=15)
    confirmed = models.BooleanField(default=False)

    def __str__(self):
        return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)"

我有基于类的视图

class NewsletterView(SuccessMessageMixin, CreateView):
    template_name = 'newsletter.html'
    success_url = reverse_lazy('newsletter')
    form_class = NewsletterRegisterForm
    success_message = "Check your inbox for the verification email"

    def form_valid(self, form):
        self.conf_num = random_digits()
        subject = 'Newsletter Confirmation',
        html_content = 'Thank you for signing up for my email newsletter! \
        Please complete the process by \
        <a href="{}/confirm/?email={}&conf_num={}"> clicking here to \
        confirm your registration</a>.'.format(self.request.build_absolute_uri('/confirm/'),
                                               self.email,
                                               self.conf_num)

        sender = "noreply@example.com"
        recipient = form.cleaned_data['email']
        msg = EmailMultiAlternatives(subject, html_content, sender, [recipient])
        msg.send()
        return super().form_valid(form)

我对如何通过基于类的视图进行设置感到有些困惑,conf_num?我必须在我的form_valid函数中正确调用self.conf_num = number吗?

当我尝试其中任何一种方法时,我要么得到电子邮件不是唯一的,要么得到时事通讯对象没有电子邮件。任何帮助将不胜感激。

标签: django

解决方案


我会选择这种方法,

class NewsletterView(SuccessMessageMixin, CreateView):
    template_name = 'newsletter.html'
    success_url = reverse_lazy('newsletter')
    form_class = NewsletterRegisterForm
    success_message = "Check your inbox for the verification email"

    def send_email(self, conf_num):
        # gather relevant data for email compose
        # you can use function args or instance attributes
        # and then, send mail from here
        email.send()

    def form_valid(self, form):
        response = super().form_valid(form) # calling the `super()` method on the top will be the best, in this case

        conf_num = random_digits()
        self.send_email(conf_num)

        # after sending the mail, access the `self.object` attribute
        # which hold the instance which just created
        self.object.conf_num = conf_num  # assign the value
        self.object.save()  # call the save() method to save the value into the database

        return response

我希望这里的评论是不言自明的:)


推荐阅读