django modelformset_factory(User)提供了两个formset

时间:2014-05-31 12:41:29

标签: django django-authentication user-profile django-forms

我尝试使用modelformset_factory(User)创建一个表单来添加(并在下一步编辑)用户。

我很困惑,为什么它会为我的当前用户创建一个表单而另一个用新表单创建一个表单?

任何想法我怎么能用当前删除那个?

这是我的view.py代码:

@login_required
def update_or_edit_user_profile(request, UserID = None, template_name='userprofile_form.html'):


    #check when a userid is provided if its the personal or if the user is allowed to edit the profile
    if UserID != None:
        if (request.user.has_perm('change_user_profile') or request.user.pk == UserID):
            pass
        else:
             raise PermissionDenied

    # when user is allowed to continue:
    UserFormSet = modelformset_factory(User)


    if request.method == 'POST':
        userformset = UserFormSet(request.POST, request.FILES)
        if userformset.is_valid():
            newUser=userformset.save()
    else:
        userformset = UserFormSet()

    return render_to_response(template_name, {
        "userformset": userformset,
    })

和我的模板:

<form action="" method="post">{% csrf_token %}
    {{ userformset.as_p }}
    <input type="submit" value="Send message" />
</form>

1 个答案:

答案 0 :(得分:0)

您将表单与表单集混淆。 formset是表单的集合,因此Django正在为您提供您所要求的内容。如果您只想要一个表单,那么您应该使用的是:

class UserForm(forms.ModelForm):
    class Meta:
        model = User


def update_or_edit_user_profile...

    user = User.objects.get(pk=UserID)
    if request.method == 'POST':
        form = UserForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = UserForm(instance=User)

    return render(request, template_name, {'form': form})