我将使用django中可用的用户表创建一个不同的作者表,我想将我创建的这个自定义表与post模型中的列结合起来。因此,我将拥有作者表和帖子表,其中分别包含这些作者共享的帖子。同时,我还会用ready user表创建用户模型。但我得到了我提到的错误。当我添加作者到管理面板,我得到这个错误。当我添加一个作者时,没有问题,但当我添加第二个作者时,我得到这个错误。我该如何解决这个问题,有什么替代方法?
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.urls import reverse
from .utils import get_read_time
from django.conf import settings
from django.utils import timezone
from markdown_deux import markdown
from django.utils.text import slugify
from django.contrib.auth.models import User
from django.db.models.signals import pre_save
from django.utils.safestring import mark_safe
class GENDER(models.TextChoices):
Erkek = "Erkek"
Kadın = "Kadın"
Diğer = "Diğer"
NONE = "Belirtmek İstemiyorum"
class Category_Choices(models.TextChoices):
BİLİNMEYENLER = '13İlinmeyenler'
KİŞİSEL_GELİŞİM = 'Kişisel Gelişim'
İLHAM_AL = 'İlham Al'
YATIRIM_HABERLERİ = 'Yatırım Haberleri'
GİRİŞİMCİLİK = 'Girişimcilik'
ENGLİSH_NEWS = 'English News'
BAŞARI_HİKAYELERİ = "Başarı Hikayeleri"
class Color_Choices(models.TextChoices):
INDIGO = 'indigo'
green = 'green'
yellow = 'yellow'
RED = 'red'
blue = 'blue'
gray = 'gray'
pink = "pink"
class Author(models.Model):
author = models.ForeignKey(User, on_delete = models.CASCADE)
firstName = models.CharField(max_length=80)
lastName = models.CharField(max_length=80)
email = models.EmailField(null=True,blank=True)
displayName = models.CharField(max_length=100)
gender = models.TextField(blank=False,choices=GENDER.choices)
avatar = models.ImageField(upload_to="avatar")
href = models.SlugField(unique=True,editable=False)
desc = models.TextField()
jobName = models.CharField(default="Yazar",max_length=30)
bgImage = models.ImageField(null=True, blank=True, upload_to="background")
def __str__(self):
return self.displayName
def get_slug(self):
href = slugify(self.displayName.replace("ı","i"))
unique = href
number = 1
while Author.objects.filter(slug=unique).exists():
unique = "{}-{}" .format(href,number)
number += 1
return unique
class Categories(models.Model):
name = models.CharField(max_length=50,choices=Category_Choices.choices,default=Category_Choices.BİLİNMEYENLER)
color = models.CharField(max_length=30,choices=Color_Choices.choices, default=Color_Choices.RED)
href = models.SlugField(unique=True,editable=False)
thumbnail = models.ImageField(upload_to="postpost",null=True,blank=True)
def __str__(self):
return self.name
def get_category_slug(self):
slug = slugify(self.name.replace("ı","i"))
unique = slug
number = 1
while Categories.objects.filter(slug=unique).exists():
unique = "{}-{}" .format(slug,number)
number += 1
return unique
def save(self, *args, **kwargs):
self.href = slugify(self.name)
super(Categories,self).save(*args, **kwargs)
def get_absolute_url(self):
return self.href
class Post(models.Model):
authorId = models.ManyToManyField(Author)
title = models.CharField(max_length=255)
desc = models.CharField(max_length=255)
categoryID = models.ForeignKey(Categories,on_delete=models.CASCADE,)
content = models.TextField(blank=False)
href = models.SlugField(unique=True,editable=False)
draft = models.BooleanField(default=True)
readingtime = models.IntegerField(default=0)
updated = models.DateTimeField()
date = models.DateTimeField(editable=False,null=True)
published = models.DateField(default=timezone.now)
featuredimage = models.ImageField(null=True, blank=True, upload_to='post')
class Meta:
ordering = ['-date', '-updated']
def __str__(self):
return self.title
def get_slug(self):
slug = slugify(self.title.replace("ı","i"))
unique = slug
number = 1
while Post.objects.filter(slug=unique).exists():
unique = "{}-{}" .format(slug,number)
number += 1
return unique
#@property
#def comments(self):
# instance = self
# qs = Comment.objects.filter_by_instance(instance)
# return qs
def get_markdown(self):
content = self.content
markdown_text = markdown(content)
return mark_safe(markdown_text)
def pre_save_receiver(sender, instance, *args, **kwargs):
if not instance.href and instance.title:
instance.href = slugify(instance.title)
if instance.content:
html_string = instance.get_markdown()
read_time_var = get_read_time(html_string)
instance.read_time = read_time_var
pre_save.connect(pre_save_receiver, sender=Post)
和此错误
IntegrityError at /adminpost/author/add/
UNIQUE constraint failed: post_author.href
Request Method: POST
Request URL: http://127.0.0.1:8000/adminpost/author/add/
Django Version: 3.2.8
Exception Type: IntegrityError
Exception Value:
UNIQUE constraint failed: post_author.href
似乎您试图创建一个已经存在的标题。因此,您的href字段不再是唯一的。
也可以使title
字段唯一,或者您可以添加一些随机数标识符到您的段塞。
import uuid
def pre_save_receiver(sender, instance, *args, **kwargs):
if not instance.href and instance.title:
if not Post.objects.filter(href=slugify(instance.title)).exists():
instance.href = slugify(instance.title)
else:
instance.href = slugify(instance.title) + str(uuid.uuid4())[:8]