我收到完整性错误。数据正在进入数据库。然后在给出错误之后。为什么会这样?有谁能告诉我怎么做
/ trustyrequest / update / 4 /
中的IntegrityError(1062,“键'email'的重复条目””)
class TrustyRequestUpdate(generic.UpdateView):
template_name = "trustyrequest/update.html"
model = TrustyRequest
form_class = TrustyRequestForm
success_url = reverse_lazy('trustyrequest_list')
def form_valid(self, form):
if form.cleaned_data['status'] == 'Accepted':
print('PK: ', form.instance.id)
random_password = User.objects.make_random_password() # generate password here
user = User(
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
email=form.cleaned_data['email'],
phone_number=form.cleaned_data['phone_number'],
)
user.set_password(random_password)
user.save()
elif form.cleaned_data['status'] == 'Pending':
print('Pending')
print('PK: ', form.instance.id)
elif form.cleaned_data['status'] == 'Rejected':
print('Rejected')
print('PK: ', form.instance.id)
return super().form_valid(form)
上面的代码是否有很好的方法。我正在将AbstractBaseUser用于用户模型
Models.py
from __future__ import unicode_literals
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from .managers import UserManager
from apps.roles.models import Role
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
is_active = models.BooleanField(_('active'), default=True)
avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
is_staff = models.BooleanField(_('staff'), default=True)
role = models.ForeignKey(Role, on_delete=models.CASCADE, blank=True, null=True)
phone_number = models.CharField(max_length=30, blank=True, null=True)
address = models.CharField(max_length=100, blank=True, null=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
'''
Returns the first_name plus the last_name, with a space in between.
'''
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
'''
Returns the short name for the user.
'''
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
'''
Sends an email to this User.
'''
send_mail(subject, message, from_email, [self.email], **kwargs)
class Meta:
db_table = "user"
这是我的Managers.py
from django.contrib.auth.base_user import BaseUserManager
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
Form.py
from django import forms
from .models import TrustyRequest
class TrustyRequestForm(forms.ModelForm):
class Meta:
model = TrustyRequest
fields = [
'name',
'address',
'first_name',
'last_name',
'email',
'phone_number',
'status',
]
答案 0 :(得分:0)
您正在使用更新视图来创建新用户。使用更新视图时,应该已经在数据库中拥有该用户(URL中的pk为4,不是吗?)。
您应该在更新视图中使用get()来检索用户,因为您使用的语法是在每次更新时创建一个新用户。该错误表明您正在尝试重复一个唯一字段-即新用户的电子邮件与现有用户的电子邮件相同
在form_valid()中,将用户创建更改为:
user = User.objects.get(pk=form.instance.id)
user.first_name=form.cleaned_data['first_name']
user.last_name = form.cleaned_data['last_name]
...
..
user.save()