【发布时间】: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)
【问题讨论】: