django - 修改基于类的视图对象保存
问题描述
我目前有这样的模型
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
吗?
当我尝试其中任何一种方法时,我要么得到电子邮件不是唯一的,要么得到时事通讯对象没有电子邮件。任何帮助将不胜感激。
解决方案
我会选择这种方法,
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
我希望这里的评论是不言自明的:)
推荐阅读
- javascript - 仅当组件文件存在时如何动态导入 Vuejs 组件
- c++ - 全局变量的未解析外部符号
- xamarin.android - 如何使用 Uno Platform 在多个平台上录制音频
- javascript - 无法让 useParams 挂钩正常工作
- powershell - Powershell:管道生产者和消费者通信
- playframework - 在 GitLab CI 中使用“driverTarget”运行空手道 UI 测试
- protege - 如何重命名和发布现有的本地本体?
- javascript - 赛普拉斯 - 迭代具有不同值的相同元素?
- javascript - 提交后将下拉菜单恢复为默认选项
- python - @property 装饰器和@[property name].getter 有什么区别?