【发布时间】:2013-08-01 20:50:13
【问题描述】:
我有两个可能相关的 UpdateView 问题。首先,它不是更新用户,而是创建一个新的用户对象。其次,我不能限制表单中显示的字段。
这是我的views.py:
class RegistrationView(FormView):
form_class = RegistrationForm
template_name = "register.html"
success_url = "/accounts/profile/"
def form_valid(self, form):
if form.is_valid:
user = form.save()
user = authenticate(username=user.username, password=form.cleaned_data['password1'])
login(self.request, user)
return super(RegistrationView, self).form_valid(form) #I still have no idea what this is
class UserUpdate(UpdateView):
model = User
form_class = RegistrationForm
fields = ['username', 'first_name']
template_name = "update.html"
success_url = "/accounts/profile/"
和 urls.py
url(r'^create/$', RegistrationView.as_view(), name="create-user"),
url(r'^profile/(?P<pk>\d+)/edit/$', UserUpdate.as_view(), name="user-update"),
如何正确使用 UpdateView?
【问题讨论】:
-
这不是严格相关的,但请检查:lightbird.net/dbe2/index.html 和 github.com/pennersr/django-allauth
-
几点:一旦调用
form_valid()方法,就不需要检查表单是否有效。这是在post()方法中执行的(参见:ccbv.co.uk/projects/Django/1.8/django.views.generic.edit/…)。form_valid()方法的最后一行确保我们在 RegistrationView 的父级 (UpdateView) 中正确调用form_valid()。
标签: django django-forms django-views django-class-based-views