如何将我的 def clean_slug 函数包含到我的视图或模板中,以便它可以工作并显示“title alr existing"? [英] How do I include my def clean_slug function into my views or template so that it will work and show "title alr exist"

查看:14
本文介绍了如何将我的 def clean_slug 函数包含到我的视图或模板中,以便它可以工作并显示“title alr existing"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单中编写了一个 def clean(self) 函数,以确保如果之前已经有一个具有相同标题的帖子,他们将返回一条消息说该标题已经存在因此无法提交表单.

现在的问题:

当我输入一个已经存在的标题并尝试创建帖子时,之前输入的所有数据都将被删除,我将被重定向到一个新的表单.没有出现错误.我想要的是当我尝试单击创建按钮时引发错误并显示给用户,以便所有数据都保留在那里,用户知道并且可以在再次尝试创建博客文章之前更改标题.

return Cleaned_data 在 forms.py 中也没有定义...给出一个名称错误

指南:

注意!我的表单中没有 slug 字段.slug 仅适用于每个单独的博客文章的 url.但基本上 slug 由标题组成.例如,如果我的用户名是 hello 而我的 Chief_title 是 bye,我的 slug 将是 hello-bye.正如您在模型中看到的那样,slug 和标题都必须是唯一的,但表单中没有 slug.

models.py

class BlogPost(models.Model):Chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True)Brief_description = models.TextField(max_length=300, null=False, blank=False)author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)slug = models.SlugField(空白=真,唯一=真)

views.py

def create_blog_view(request):上下文 = {}用户 = request.user如果不是 user.is_authenticated:返回重定向('must_authenticate')如果 request.method == 'POST':form = CreateBlogPostForm(request.POST or None, request.FILES or None)如果 form.is_valid():obj= form.save(commit = False)author = Account.objects.filter(email=user.email).first()obj.author = 作者obj.save()obj.members.add(request.user)context['success_message'] = 已更新";返回重定向('HomeFeed:main')别的:表单 = CreateBlogPostForm()上下文['形式'] = 形式返回渲染(请求,HomeFeed/create_blog.html",{})

forms.py

class CreateBlogPostForm(forms.ModelForm):元类:模型 = 博客帖子字段 = ['chief_title']def清洁(自我):Chief_title = self.cleaned_data['chief_title']qs = BlogPost.objects.filter(chief_title=chief_title)如果 qs.exists():raise forms.ValidationError('帖子已经存在')返回cleaned_data

html

 
{% csrf_token %}{% if form.non_field_errors %}{{form.non_field_errors}}{% 万一 %}<!-- Chief_title --><div class="form-group"><label for="id_title">头衔!</label><输入类=表单控件"类型=文本"name="chief_title";id="id_title";占位符=标题"所需的自动对焦>

{{form.chief_title.errors}}<button class="submit-button btn btn-lg btn-primary btn-block";type=提交">CREATE</button></表单>

解决方案

好吧,您可以创建一个自定义验证器来检查 slug 是否存在:

 from django.core.exceptions import ValidationErrordef validate_slug_exists(value):blog_post = BlogPost.objects.filter(slug=value)如果 blog_post.exists():raise ValidationError('具有给定标题的帖子已经存在')

然后在您的表单中将此验证器添加到字段验证器列表中:

class CreateBlogPostForm(forms.ModelForm):Chief_title = forms.CharField(validators = [validate_slug_exists])

更新

您也可以尝试在您的表单类中使用validate_unique():

def validate_unique(self, exclude=None):qs = BlogPost.objects.all()如果 qs.filter(chief_title=self.chief_title).exists():raise ValidationError(具有此标题的博文已经存在")

Hi I have written a def clean(self) function in forms to make sure that if there was previously already a post with the same title, they will return a message saying that the title already exists and hence the form cannot be submitted.

Problem now:

When I enter a title that already exists and I try to create the post, all data previously input will be removed and I will be redirected to a fresh form. No errors were raised. What I want is for the error to be raised and shown to the user when I try to click on the create button so all data remains there and the user knows and can change the title before attempting the create the blog post again.

return cleaned_data in forms.py is not defined too...giving a nameerror

Guideline:

Note! There is NO slug field in my form. The slug is only for the url for each individual blogpost. But basically the slug consists of the title. Eg if my username is hello and my chief_title is bye, my slug will be hello-bye. Both the slug and the title has to be unique as you can see in the model, but there is no slug in the form.

models.py

class BlogPost(models.Model):
 chief_title                    = models.CharField(max_length=50, null=False, blank=False, unique=True)
 brief_description = models.TextField(max_length=300, null=False, blank=False)
 author                     = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
 slug                   = models.SlugField(blank=True, unique=True)

views.py

def create_blog_view(request):
    context = {}
    user = request.user
    if not user.is_authenticated:
        return redirect('must_authenticate')
    if request.method == 'POST':
        form = CreateBlogPostForm(request.POST or None, request.FILES or None)
    
        if form.is_valid():
            obj= form.save(commit = False)
            author = Account.objects.filter(email=user.email).first()
            obj.author = author
            obj.save()
            obj.members.add(request.user)
            context['success_message'] = "Updated"
            return redirect('HomeFeed:main')
        else:
            form = CreateBlogPostForm()
            context['form'] = form
    return render(request, "HomeFeed/create_blog.html", {})

forms.py

class CreateBlogPostForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['chief_title']

    def clean(self):
        chief_title = self.cleaned_data['chief_title']
        qs = BlogPost.objects.filter(chief_title=chief_title)
        if qs.exists():
            raise forms.ValidationError('Post already exists')
        return cleaned_data

html

  <form class="create-form" method="post" enctype="multipart/form-data">{% csrf_token %}

    {% if form.non_field_errors %}
   {{form.non_field_errors}}  
    {% endif %}

   <!-- chief_title -->
   <div class="form-group">
    <label for="id_title">Chief Title!</label>
    <input class="form-control" type="text" name="chief_title" id="id_title" placeholder="Title" required autofocus>
   </div>   {{form.chief_title.errors}}



   <button class="submit-button btn btn-lg btn-primary btn-block" type="submit">CREATE</button>

  </form>   

解决方案

Well you can create a custom validator to check if the slug exists:

from django.core.exceptions import ValidationError

def validate_slug_exists(value):
    blog_post = BlogPost.objects.filter(slug=value)
    if blog_post.exists():
        raise ValidationError('The post with a given title already exists')

Then in your form add this validator to the fields validators list:

class CreateBlogPostForm(forms.ModelForm):
    chief_title = forms.CharField(validators = [validate_slug_exists])

UPDATE

You can also try using validate_unique() in your form class:

def validate_unique(self, exclude=None):
    qs = BlogPost.objects.all()

    if qs.filter(chief_title=self.chief_title).exists():
        raise ValidationError("Blog post with this title already exists")

这篇关于如何将我的 def clean_slug 函数包含到我的视图或模板中,以便它可以工作并显示“title alr existing"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆