如何在django表单中自动填充slug字段

bvjxkvbb  于 2023-01-10  发布在  Go
关注(0)|答案(1)|浏览(157)

我想让一个网站的用户创建博客文章从一个形式,我做了,但slug字段不得到填充自动从前端,但从后端(管理页面)它确实得到填充,这不是我想要的。我想slug字段得到填充的标题时,用户想要创建一个帖子,例如这是一个例子请我怎么去
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注意*如果我从字段中删除“slug”,则会抛出一个错误,指出需要slug *

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 class="form-group">
  <button class="btn theme-bg rounded" type="submit">Post Content</button>
 </div>
</form>
t40tm48m

t40tm48m1#

Django已经有了slugs的方法,你可以覆盖你的保存model方法并添加slugify字段。

from django.utils.text import slugify

def save(self, *args, **kwargs):
    self.slug = slugify(self.title)
    super(Post, self).save(*args, **kwargs)

相关问题