我试图让用户能够更新他们的个人资料,但似乎无法弄清楚如果修改了2个字段username, email
,或者如果用户不是该用户,则只会引发错误。截至目前,我无法保存更新,因为错误不断弹出,因为用户明显具有这些值。我也尝试了excludes
,但也无法让它正常工作。这是我的代码:
forms.py
class UpdateUserProfile(forms.ModelForm):
first_name = forms.CharField(
required=True,
label='First Name',
max_length=32,
)
last_name = forms.CharField(
required=True,
label='Last Name',
max_length=32,
)
email = forms.EmailField(
required=True,
label='Email (You will login with this)',
max_length=32,
)
username = forms.CharField(
required = True,
label = 'Display Name',
max_length = 32,
)
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name')
def clean_email(self):
email = self.cleaned_data.get('email')
username = self.cleaned_data.get('username')
if (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()):
raise forms.ValidationError('This email address is already in use.'
'Please supply a different email address.')
return email
def save(self, commit=True):
user = super().save(commit=False)
user.email = self.cleaned_data['email']
user.username = self.cleaned_data['username']
if commit:
user.save()
return user, user.username
views.py
def update_user_profile(request, username):
args = {}
if request.method == 'POST':
form = UpdateUserProfile(request.POST, instance=request.user)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('user-profile', kwargs={'username': form.save()[1]}))
else:
form = UpdateUserProfile(instance=request.user)
args['form'] = form
return render(request, 'storytime/update_user_profile.html', args)
答案 0 :(得分:1)
通过排除当前的用户来检查是否存在用户:
from django.db.models import Q
class UpdateUserProfile(forms.ModelForm):
# ...
def clean_email(self):
# ...
if User.objects.filter(
Q(username=username)|Q(email=email)
).exclude(pk=self.instance.pk).exists():
raise ...
# for checking if both were modified
if self.instance.email != email and self.instance.username != username:
raise ...
有人可能会进一步争辩说这段代码属于clean
形式,因为它验证了字段的相互依赖性。