我正在为公司网站实施新闻通讯应用程序。我的目标是允许“未来”网站管理员直接从管理员处发布新闻稿。
为此,我编写了以下代码:
models.py
from django.db import models
from ckeditor.fields import RichTextField
class NewsletterSubscription(models.Model):
datetime = models.DateTimeField(auto_now_add = True)
email = models.EmailField(max_length=128)
class Meta:
verbose_name = 'Iscritto Newsletter'
verbose_name_plural = 'Iscritti Newsletter'
def __unicode__(self):
return self.email
class Newsletter(models.Model):
EMAIL_STATUS_CHOICES = (
('Draft', 'Draft'),
('Pubblicata', 'Pubblicata')
)
subject = models.CharField(max_length=250)
body = RichTextField()
email = models.ManyToManyField(NewsletterSubscription)
status = models.CharField(max_length=10, choices=EMAIL_STATUS_CHOICES)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.subject
我想知道是否可以在 NewsletterAdminForm 中添加一种按钮,该按钮可以触发电子邮件。
admin.py
from django import forms
from django.contrib import admin
from .models import NewsletterSubscription, Newsletter
from ckeditor.widgets import CKEditorWidget
class NewsletterSubscriptionAdmin(admin.ModelAdmin):
list_display = ('email', 'datetime', )
class NewsletterAdminForm(forms.ModelForm):
body = forms.CharField(widget=CKEditorWidget())
class Meta:
model = Newsletter
fields = '__all__'
class NewsletterAdmin(admin.ModelAdmin):
form = NewsletterAdminForm
admin.site.register(NewsletterSubscription, NewsletterSubscriptionAdmin)
admin.site.register(Newsletter, NewsletterAdmin)
在此先感谢您提供的帮助。
答案 0 :(得分:0)
要在管理面板中获取按钮,您只需创建一个方法即可返回html:
class NewsletterAdmin(admin.ModelAdmin):
...
readonly_fields = ['send_mails']
def send_mails(self, obj):
url_red = 'url_of_your_view_to_send_mails'
return format_html(
'<a class="button" href="{}">Send</a> ',
url_red,
)
然后将其渲染为管理页面中的按钮,该页面会将GET请求发送到视图提供的url,您可以在其中定义所有逻辑并发送邮件。请将此自定义字段包含在 fields 属性中。
希望有帮助。