python-3.x IntegrityError at /admin/auth/user/11/delete/ FOREIGN KEY约束失败

bvjveswy  于 2023-04-13  发布在  Python
关注(0)|答案(2)|浏览(133)

当我从我的管理面板删除用户显示我给出的错误我不明白是什么原因这个错误或我犯了错误.我可以更新和创建新的用户和删除那些用户谁没有配置文件,但有配置文件的用户,他们无法删除,因为以下在这里,我在下面给出. x1c 0d1x
帐户/models.py

from django.urls import reverse
from django.db import models
from django.contrib import auth
from PIL import Image
from django.db.models.signals import post_save
from django.dispatch import receiver

# Create your models here.

class User(auth.models.User,auth.models.PermissionsMixin):
    
    def __str__(self):
        return "@{}".format(self.username)

class Profile(models.Model):

        user = models.OneToOneField(auth.models.User, on_delete=models.CASCADE)
        avatar = models.ImageField(default='1.jpg', upload_to='displays', height_field=None, width_field=None, max_length=None)
    
    
        def __str__(self):
            return f'{self.user.username} Profile'
    
    def save(self,*args, **kwargs):
        super(Profile,self).save(*args, **kwargs) #it will take data and save it

        dp = Image.open(self.avatar.path) #storing avatar in variable
        if dp.height >300 or dp.width >300:
            output_size =(300,300) #set any size you want
            dp.thumbnail(output_size) 
            dp.save(self.avatar.path) #after resizing it save it in data base in place of uploaded once by user
 

    def get_absolute_url(self):
        return reverse("Profile_detail", kwargs={"pk": self.pk})

@receiver(post_save, sender=User)
def create_profile(sender, created,instance,**kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_profile(sender, instance,**kwargs):
    instance.profile.save()

帐户/forms.py

from django import forms
    from django.contrib.auth.forms import UserCreationForm
    from django.core.exceptions import ValidationError
    from django.core import validators
    
    User = get_user_model()
    
    class UserCreateForm(UserCreationForm):
    
        class Meta:
            fields = ["username","email","password1","password2"]
            model = get_user_model()
            widgets ={
                'username' : forms.TextInput(attrs={'class':'textinputclass','placeholder':'username'}),
            }
        
        def clean_email(self):
            email = self.cleaned_data["email"]
            if User.objects.filter(email__iexact=email).exists():
                raise forms.ValidationError("Email is invalid")
            return email
        
    
        def __init__(self,*args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['username'].label = 'Display Name'
            # self.fields['email'].label = 'Email Address'

帐户/views.py

user = User
class SignUp(CreateView):
    form_class = forms.UserCreateForm
    
    def form_valid(self, form):
        if form.is_valid:
            email = form.cleaned_data.get('email')
            user = form.save(commit=False)
            user.is_active = False
            send_mail(
            'i gotch you',
            'how are uou',
            'coolahmed21@hgmail.com',
            [email],
            fail_silently=False,
            )
        return super(SignUp, self).form_valid(form)
    success_url = reverse_lazy('login')
    template_name = "accounts/signup.html"
dhxwm5r4

dhxwm5r41#

这是由于on_delete=CASCADE。这意味着如果ForeignKey引用的对象被删除,那么它也应该删除引用的对象。这样的CASCADE可能会导致大量的对象被删除,因为删除对象实际上会触发其他删除,等等。
试试这个:

class Profile(models.Model):
    user = models.OneToOneField(auth.models.User, null=True on_delete=models.SET_NULL)
gtlvzcf8

gtlvzcf82#

看,你需要改变后保存,后删除预保存和预删除,它将工作得很好

相关问题