Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django “关键点”;(用户id)=(51)“;已经存在_Django - Fatal编程技术网

Django “关键点”;(用户id)=(51)“;已经存在

Django “关键点”;(用户id)=(51)“;已经存在,django,Django,错误:重复记录违反了单一约束“user\u otherinfo\u user\u id\u key” 详细信息:键“(用户id)=(52)”已存在 models.py 类别OtherInfo(models.Model): user=models.OneToOneField(用户,on_delete=models.CASCADE) phone=models.CharField(最大长度=11,详细名称=“电话号码”) location=models.CharField(最大长度=50,详细名称=

错误:重复记录违反了单一约束“user\u otherinfo\u user\u id\u key” 详细信息:键“(用户id)=(52)”已存在

models.py


类别OtherInfo(models.Model):
user=models.OneToOneField(用户,on_delete=models.CASCADE)
phone=models.CharField(最大长度=11,详细名称=“电话号码”)
location=models.CharField(最大长度=50,详细名称=“location”)
profile\u image=models.FileField(blank=True,null=True,verbose\u name=“image”)
类元:
详细名称复数='其他信息'
@接收方(保存后,发送方=用户)
def create_user_配置文件(发送方、实例、已创建、**kwargs):
如果创建:
OtherInfo.objects.create(用户=实例)
@接收方(保存后,发送方=用户)
def save_user_配置文件(发送方、实例,**kwargs):
instance.otherinfo.save()
forms.py

class LoginForm(forms.Form):
    username = forms.CharField(label = "Username")
    password = forms.CharField(label = "Parola",widget = forms.PasswordInput)

class RegisterForm(forms.ModelForm):
    password1 = forms.CharField(max_length=100, label='Parola',widget=forms.PasswordInput())
    password2 = forms.CharField(max_length=100, label='Parola again', widget=forms.PasswordInput())
    phone_number = forms.CharField(required=False, max_length=11, label='Phone Number')
    location = forms.CharField(required=False, max_length=50, label='Location')
    profile_image = forms.FileField(required=False, label="Image") 

class Meta:
    model = User

    fields = [
        'first_name',
        'last_name',
        'email',
        'username',
        'password1',
        'password2',
        'phone_number',
        'location',
        'profile_image',
    ]

def clean_password2(self):

    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")

    if password1 and password2 and password1 != password2:
        raise forms.ValidationError("Passwords do not match!")
    return password2

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')

class ProfileForm(forms.ModelForm):
    class Meta:
        model = OtherInfo
        fields = ('phone', 'location', 'profile_image')
views.py

@login_required
@transaction.atomic
def updateprofile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.otherinfo)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, _('Your profile has been successfully updated!'))
            return redirect('/user/profile/')
        else:
            messages.error(request, _('Please correct the following error.'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.otherinfo)
    return render(request, 'user/update_user.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

def register(request):

    form = RegisterForm(request.POST or None,request.FILES or None )
    if form.is_valid():
        user = form.save(commit=False)
        first_name = form.cleaned_data.get('first_name')
        last_name = form.cleaned_data.get('last_name')
        username = form.cleaned_data.get("username")
        email = form.cleaned_data.get('email')
        password = form.cleaned_data.get('password1')
        phone = form.cleaned_data.get('phone_number')
        location = form.cleaned_data.get('location')
        profile_image = form.cleaned_data.get('profile_image')
        user.set_password(password)

        user.save()
        new_user = authenticate(username=user.username, first_name=first_name, last_name=last_name, email=email, password=password)

OtherInfo.objects.create(user=new_user,phone=phone,location=location,
profile_image=profile_image)

        login(request,new_user)
        messages.info(request,"Successfully Register ...")

        return redirect("/")
    context = {
            "form" : form
        }
    return render(request,"user/register.html",context)

在Django中,用户可以在更新配置文件之前注册。当我添加配置文件更新代码时,现在用户无法注册。如何解决此问题?

您需要删除id为51的数据条目

您得到的错误与数据库有关,您尝试创建的id为的条目已存在


删除您的数据库并创建一个新的数据库(如果您不在生产环境中)

只需不为同一
用户创建两次
OtherInfo

  • 在保存
    用户的
    post\u save
    处理程序中,为用户创建一个
    OtherInfo
    对象
  • 在您的视图中,您首先创建
    用户
    ,因此您已经创建了与该用户关联的
    其他信息
  • 然后你有了
    OtherInfo.objects.create(user=new\u user,phone=phone,location=location,
    profile\u image=profile\u image)
最后一条指令将失败,因为您正试图为同一
用户创建第二条
OtherInfo
。所以你可以做两件事:

  • 删除创建
    OtherInfo
    对象的
    post\u save
    信号处理程序
  • 通过设置各种值并保存而不是创建来更新
    new\u user.otherinfo

  • 我正在使用postgresql数据库。你必须从postgresql内部执行。事实上,我的数据库中没有记录。单击“保存”按钮会在数据库中创建一条记录,但浏览器会返回一个错误。当删除构成OtherInfo对象的post_保存信号处理程序时,用户会给出一个更新错误。我做错了什么?那是因为在保存用户时,您有第二次
    post\u save
    信号保存
    OtherInfo
    。我真的不认为有必要,你也可以把它去掉。或者在试图保存它之前,至少检查代码
    如果hasattr(实例,'otherinfo')
    你说的是my Models.py文件,对吗?我尝试了所有这些可能性,但我不能。是的,在你们的型号中删除两个信号接收器。它们是不需要的;用户不允许更新用户,控制台或浏览器中没有错误文本。这一切都表现良好,但没有更新。