我有用户表单,其中有一个用户名字段。表单中的字段是从数据库中的数据初始化的。
class PersonEditForm(forms.ModelForm):
username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
class Meta:
model = User
view.py
@login_required
def edit(request, template_name):
if request.user.is_authenticated():
if request.method == 'POST':
form = PersonEditForm(request.POST)
if form.is_valid():
form.save(instance = request.POST, user = request.user)
return HttpResponseRedirect(reverse('/success/'))
else:
user = User.objects.get(username = request.user)
form = PersonEditForm(instance = user, initial = {'username': request.user.username})
return render_to_response(template_name, {"form": form },
context_instance = RequestContext(request))
登录用户可以编辑用户名。问题是在编写 clean_username 方法时,我需要request.user来检查:
elif username!= request.user.username
a)User.objects.get(用户名=用户名)#if返回一些东西,然后引发forms.ValidationError(_("用户名已经采取。"))
b)否则user.username = username
我怎样才能做到这一点?
答案 0 :(得分:4)
您可以在self.instance
class PersonEditForm(forms.ModelForm):
def clean_username(self):
# self.instance is your current user
...
视图应如下所示
if request.user.is_authenticated():
if request.method == 'POST':
form = PersonEditForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('/success/'))
else:
form = PersonEditForm(instance=request.user, initial={'username': request.user.username})
return render_to_response(template_name, {"form": form },
context_instance = RequestContext(request))