【问题标题】:How to customise unique = true in django如何在 django 中自定义 unique = true
【发布时间】:2021-05-02 06:10:20
【问题描述】:

基本上,我网站上的用户可以创建博客文章。但我不想使用 unique = True ,因为这意味着 user1 无法创建与 user2 具有相同标题的帖子。

我想让 user1 可以创建一个与 user2 具有相同标题的帖子,但 user1 不能创建另一个与 USER1 之前创建的任何现有帖子同名的帖子。

意味着用户 1 可以有一个博文标题“hello”,用户 2 也可以有一个博文“hello” 但用户 1 不能有 2 篇具有相同标题“你好”的博文

好的,我认为这已经很清楚了^....如果我使用 unique = true,那就太多了,那么我该如何自定义它以使其仅适用于用户的帖子?谢谢!

models.py

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

class Account(AbstractBaseUser):
 email                  = models.EmailField(verbose_name="email", max_length=60, unique=True)
 username               = models.CharField(max_length=30, unique=True)

forms.py

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

html

   <form class="create-form" method="post" enctype="multipart/form-data">{% csrf_token %}
   <div class="form-group">
    <label for="id_title">Title</label>
    <input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus>
   </div>
   <button class="submit-button btn btn-lg btn-primary btn-block" type="submit">Submit</button>

  </form>

  {% if form.errors %}
  {% for field in form %}
      {% for error in field.errors %}
          <div class="alert alert-danger">
              <strong>{{ error|escape }}</strong>
          </div>
      {% endfor %}
{% endif %}
    

views.py

def create_blog_view(request):
    context = {}
    user = request.user
    if request.method == 'POST':
        form = CreateBlogPostForm(request.POST or None, request.FILES or None)    
        if form.is_valid():
            obj.save()
            return redirect('HomeFeed:main')
        else:
            context['form'] = form
    return render(request, "HomeFeed/create_blog.html", context)

【问题讨论】:

    标签: django django-models django-views django-forms django-templates


    【解决方案1】:

    您可以使用 unique constraint,这允许 2 个字段进行交互并且是唯一的,因此您可以拥有每个用户只能使用一次的帖子名称

    【讨论】:

    • 嘿伙计,这在代码中会是什么样子?只是UniqueConstraint(fields=['chief_title', 'author'], name='unique_blogpost') 吗?在所有字段之后,我会将其包含在我的 models.py 中吗?我需要在 views.py 和 html 等中包含任何内容吗? @Sirwill98
    • 另外,我假设通过这样做,我的标题字段中不再需要 unique=True 了
    • 它们被添加到模型中的meta:类中,this page展示了一个例子
    • 是的,您可以删除唯一属性
    • 当然,完成后^,如果碰巧违反了唯一约束,我是否需要在我的views.py和html中添加任何内容来显示错误?还是我在 html 中已有的内容就足够了?
    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    相关资源
    最近更新 更多