I have used the default Django admin panel as my backend. I have a Blogpost model. What I am trying to do is whenever an admin user saves a blogpost object on Django admin, I need to send an email to the newsletter subscribers notifying them that there is a new blog on the website.
Since Django admin automatically saves the blog by calling the save function, I don't know where to write send email api logic. Hope I have explained it well.
My Blogpost:
class BlogPost(models.Model):
author = models.CharField(max_length=64, default='Admin')
CATEGORY_CHOICES = (
('travel_news', 'Travel News',),
('travel_tips', 'Travel Tips',),
('things_to_do', 'Things to Do',),
('places_to_go', 'Places to Go'),
)
image = models.ImageField(blank=True, null=True)
title = models.CharField(max_length=255)
categories = models.CharField(max_length=64, choices=CATEGORY_CHOICES, default='travel_news')
caption = models.CharField(max_length=500)
content = RichTextUploadingField()
# todo support for tags
# tags = models.CharField(max_length=255, default='travel') #todo
tag = models.ManyToManyField(Tag)
date_created = models.DateField()
I have overwritten the Django admin form by my model form like this.
class BlogForm(forms.ModelForm):
CATEGORY_CHOICES = (
('travel_news', 'Travel News',),
('travel_tips', 'Travel Tips',),
('things_to_do', 'Things to Do',),
('places_to_go', 'Places to Go'),
)
# categories = forms.MultipleChoiceField(choices = CATEGORY_CHOICES)
class Meta:
model = BlogPost
fields = ['author','image', 'title','categories',
'caption','content','tag','date_created']
@register(BlogPost)
class BlogPostAdmin(ModelAdmin):
# autocomplete_fields = ['author']
def edit(self, obj):
return format_html('<a class="btn-btn" href="/admin/blogs/blogpost/{}/change/">Change</a>', obj.id)
def delete(self, obj):
return format_html('<a class="btn-btn" href="/admin/blogs/blogpost/{}/delete/">Delete</a>', obj.id)
list_display = ('categories', 'title', 'date_created','edit', 'delete')
icon_name = 'chrome_reader_mode'
# inlines = [TagInline]
form = BlogForm
I have written a view, but it doesnt make sense since there is no any url calling it as we dont need any view and url when saving from the django admin itself.
from apps.blogs.admin import BlogForm
def blogform(request):
if request.method == 'POST':
form = BlogForm(request.POST)
if form.is_valid():
form.save()
Without this logic too, the form is working fine.
My subscribers model:
class Subscribers(models.Model):
email = models.EmailField(unique=True)
date_subscribed = models.DateField(auto_now_add=True)
def __str__(self):
return self.email
class Meta:
verbose_name_plural = "Newsletter Subscribers"