i want to allow users of a website create blog post from a form that i made, but the slug field does not get populated automatically from the frontend but from the backend (admin page) it does get populated, and that is not what i want. I want the slug field to get populated with the title when the users want to create a post e.g this-is-an-example please how do i go about it
models.py
class Blog(models.Model):
title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title")
slug = models.SlugField(unique=True)
content = RichTextField()
image = models.ImageField(upload_to="blog-images/%Y/%m/%d/", verbose_name="Post Thumbnail")
def get_absolute_url(self):
return reverse("blog:blog-details", args=[self.slug])
def __str__(self):
return self.title
views.py
@login_required
def new_post(request):
info = Announcements.objects.filter(active=True)
categories = Category.objects.all()
if request.method == "POST":
form = BlogPostForm(request.POST, request.FILES)
if form.is_valid():
form.instance.creator = request.user
form.save() # ← no commit=False
messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!')
return redirect('blog:home')
else:
form = BlogPostForm()
context = {
'form': form,
'info': info,
'categories': categories
}
return render(request, 'blog/newpost.html', context)
forms.py NOTE if i remove the 'slug' from the field it throws an error saying that slug is needed
class BlogPostForm(forms.ModelForm):
class Meta:
model = Blog
fields = ('title', 'slug', 'content', 'image', 'category')
newpost.html
<form action="" method="POST" enctype="multipart/form-data">
<p><span style="color: black;"><b>NOTE</b></span>: For slug field, input the title as slug field but with hypens in between text <br> e.g <span style="color: black;"><b> "this-is-a-new-post"</b></span></p>
{% csrf_token %}
{{form|crispy}}
{{form.media}}
<div >
<button type="submit">Post Content</button>
</div>
</form>
CodePudding user response:
Django already has a method for slugs. You can override your save model method and add the slugify field.
from django.utils.text import slugify
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)