【问题标题】:duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=() already exists重复键值违反唯一约束“core_user_username_key”详细信息:键(用户名)=()已存在
【发布时间】:2019-12-07 21:19:11
【问题描述】:

美好的一天!创建了一个单独的页面来更改密码,当您输入密码并重复并单击“更改密码”按钮时,出现重复键值违反唯一约束“core_user_username_key”错误 详细信息:键(用户名)= 已存在 如何解决这个错误?

forms.py

class CallcenterPasswordChange(forms.ModelForm):
    password1 = forms.CharField(widget=forms.PasswordInput(),  label='Новый пароль')
    password2 = forms.CharField(widget=forms.PasswordInput(), label='Повтор нового пароля')

    def clean(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")

        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='Повтор нового пароля не совпадает',
            )
        return self.cleaned_data

  class Meta:
     model = User
     fields = ('username', 'first_name', 'last_name', 'password1',   'password2')

views.py

class CallcenterPasswordChangeView(AbsCallcenterView):
    template_name = 'callcenter/password_change.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        patient_pk = kwargs.get('patient_pk')
        patient = get_object_or_404(Patient, pk=patient_pk)
        initial_data = model_to_dict(patient.user)
        context['form'] =CallcenterPasswordChange(initial=initial_data)
        context['patient_pk'] = patient_pk
        context['patient'] = patient
        return context

    def post(self, request, **kwargs):
        context = super().get_context_data(**kwargs)
        patient_pk = kwargs.get('patient_pk')
        patient = get_object_or_404(Patient, pk=patient_pk)
        form = CallcenterPasswordChange(request.POST)
        context['form_user'] = form
        context['patient'] = patient
        if form.is_valid():
            form.save()
        else:
            return render(request, template_name=self.template_name, context=context)

【问题讨论】:

    标签: python django


    【解决方案1】:

    问题解决了!

     class CallcenterPasswordChangeView(AbsCallcenterView):
        template_name = 'callcenter/password_change.html'
    
       def get_context_data(self, **kwargs):
         context = super().get_context_data(**kwargs)
         patient_pk = kwargs.get('patient_pk')
         patient = get_object_or_404(Patient, pk=patient_pk)
         initial_data = model_to_dict(patient.user)
         context['form'] = CallcenterPasswordChange(initial=initial_data)
         context['patient'] = patient
         return context
    
     def post(self, request, **kwargs):
         context = super().get_context_data(**kwargs)
         patient = Patient.objects.get(pk=context['patient_pk'])
         form = CallcenterPasswordChange(request.POST)
         context['form'] = form
         if form.is_valid():
             patient.user.set_password(form.cleaned_data['password1'])
             patient.user.save()
             success_url = reverse_lazy('callcenter:patients')
             return HttpResponseRedirect(success_url)
    

    【讨论】:

      【解决方案2】:

      这根本不是你想做的。这试图做的是创建一个全新的用户。

      更重要的是,password1password2 字段与模型中的实际密码字段无关;另外,没有什么可以处理密码的散列。

      你真正想要的是一个只有这两个字段的标准(非模型)表单,然后设置当前用户的密码。

      所以形式就是:

      class CallcenterPasswordChange(forms.Form):
          password1 = forms.CharField(widget=forms.PasswordInput(),  label='Новый пароль')
          password2 = forms.CharField(widget=forms.PasswordInput(), label='Повтор нового пароля')
      
          def clean(self):
              password1 = self.cleaned_data.get("password1")
              password2 = self.cleaned_data.get("password2")
      
              if password1 and password2 and password1 != password2:
                  raise forms.ValidationError(
                      self.error_messages['password_mismatch'],
                      code='Повтор нового пароля не совпадает',
                  )
              return self.cleaned_data
      

      在视图中,你这样做:

      form = CallcenterPasswordChange(request.POST)
      if form.is_valid():
          request.user.set_password(form.cleaned_data['password1'])
          request.user.save()
          return redirect('somewhere')
      

      但是,您还应该注意,Django 已经包含一个密码更改表单和视图。

      【讨论】:

      • 根据你提出的方法,一切正常,但不是你想要的方式,应该由(患者_pk)而不是用户为患者更改密码
      • 嗯,你本来应该这么说的。但是患者和用户之间的关系是什么?展示模型。
      • 用户创建一个病人,输入他的所有数据,名字,姓氏,出生日期等,可以编辑他的登录名,姓氏,名字等,以及更改现在他的密码,所以我无法让用户更改患者密码,用户可以完全控制患者
      • 什么是code关系?再次,请展示您的模型。
      猜你喜欢
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多