我试图通过降低所有用户的昵称来清理数据。这是代码:
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
website = models.URLField(blank=True)
def __unicode__(self):
return self.user.username
def clean(self):
self.user.username = self.user.username.lower()
但是我得到`UserProfile没有用户。
我是Django的菜鸟,但是我是否理解,每当我们保存我们的模型时 - 使用我写过的clean()?那是对的吗?那我的错误在哪里?
编辑:
def register(request):
# Like before, get the request's context.
context = RequestContext(request)
# A boolean value for telling the template whether the registration was successful.
# Set to False initially. Code changes value to True when registration succeeds.
registered = False
# If it's a HTTP POST, we're interested in processing form data.
if request.method == 'POST':
# Attempt to grab information from the raw form information.
# Note that we make use of both UserForm and UserProfileForm.
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
# If the two forms are valid...
if user_form.is_valid() and profile_form.is_valid():
# Save the user's form data to the database.
user = user_form.save()
# Now we hash the password with the set_password method.
# Once hashed, we can update the user object.
user.set_password(user.password)
user.save()
# Now sort out the UserProfile instance.
# Since we need to set the user attribute ourselves, we set commit=False.
# This delays saving the model until we're ready to avoid integrity problems.
profile = profile_form.save(commit=False)
profile.user = user
# Now we save the UserProfile model instance.
profile.save()
# Update our variable to tell the template registration was successful.
registered = True
# Invalid form or forms - mistakes or something else?
# Print problems to the terminal.
# They'll also be shown to the user.
else:
print user_form.errors, profile_form.errors
# Not a HTTP POST, so we render our form using two ModelForm instances.
# These forms will be blank, ready for user input.
else:
user_form = UserForm()
profile_form = UserProfileForm()
# Render the template depending on the context.
return render_to_response(
'registration.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
context)
答案 0 :(得分:0)
模型清理方法不是由保存过程调用的,而是在调用is_valid()时通过表单调用。你可以通过查看追溯来看到它 - 它总是有用的信息。
当时调用is_valid,当然,配置文件没有用户,因此出错。
我必须说,无论如何,这一点都没有任何意义。为什么要将该代码放在Profile模型中,而不是用户模型?更好的是,它应该在用户表单中,在clean_username
方法中,它应返回较低的值。