我如何使用UpdateView?

时间:2013-08-01 04:49:26

标签: django django-forms django-views django-class-based-views

我有两个(可能是相关的)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?提前致谢。

3 个答案:

答案 0 :(得分:6)

问题1。 由于您使用的是相同的表单,因此未更新用户 (RegistrationForm)进行更新并创建新用户。

问题2.表单属于自己的文件,名为forms.py。 我建议的重构:



    #forms.py
    #place(forms.py) this in the same directory as views.py

    class UpdateForm(forms.ModelForm):
    #form for updating users
    #the field you want to use should already be defined in the model
    #so no need to add them here again DRY
        class Meta:
            model = User
            fields = ('field1', 'field2', 'field3',)

    #views.py
    #import your forms
    from .forms import UpdateForm
    #also import your CBVs
    from django.views.generic import UpdateView

    class UserUpdate(UpdateView):  
        context_object_name = 'variable_used_in `update.html`'
        form_class = UpdateForm
        template_name = 'update.html'
        success_url = 'success_url'

        #get object
        def get_object(self, queryset=None): 
            return self.request.user

        #override form_valid method
        def form_valid(self, form):
            #save cleaned post data
            clean = form.cleaned_data 
            context = {}        
            self.object = context.save(clean) 
            return super(UserUpdate, self).form_valid(form)    

稍微优雅的urls.py



    #urls.py
    #i'm assuming login is required to perform edit function
    #in that case, we don't need to pass the 'id' in the url. 
    #we can just get the user instance
    url(
        regex=r'^profile/edit$',
        view= UserUpdate.as_view(),
        name='user-update'
    ),

你遗漏了很多信息,所以不确定你的设置是什么。我的解决方案是基于你有Django 1.5的假设。您可以learn more关于使用CBV处理表单

答案 1 :(得分:2)

首先user = form.save()在db中保存表单。由于表格中没有pk,因此会创建一个新的pk。 您要做的就是检查具有该用户名的用户是否存在,如果没有创建它(对于此部分检查谷歌)。

第二个:要限制字段,您必须在表单的Meta类中指定它们(您未在此处显示),请检查此https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelform

答案 2 :(得分:2)

如果要在数据库中获取新对象而不是更新现有对象,则可能是您复制并粘贴了新对象的模板,而忘记更改表单的action属性。这应该指向以硬编码路径或URL标记({% url '<name of URLconf>' object.id %)的形式进行更新的视图。