Django - 处理大量表单

时间:2014-03-14 23:53:58

标签: python django django-forms django-views

我开始在网站上工作,显然会有很多按钮,我仍然只有2个按钮可以处理,我的一个视图已经有了这段代码来处理这两个表格提交

if request.method == "POST":
    if "see" in request.POST:
        seetagform = SeeTagForm(request.POST)
        createform = CreateForm()
        if seetagform.is_valid():
            cd = seetagform.cleaned_data
            tagstring = "_".join(cd["name"].split(' '))
            return HttpResponseRedirect(reverse("base:see",args=(tagstring,)))
    elif "create" in request.POST:
        createform = CreateForm(request.POST)
        seetagform = SeeTagForm()
        if createform.is_valid():
            cd = createform.cleaned_data
            p = Event.objects.create(start=cd["datetime"])
            tags = cd["tags"]
            tags = tags.split(' ')
            for tag in tags:
                t = Tag.objects.get(name=tag)
                t.events.add(p)
            return HttpResponseRedirect(reverse("base:see",args=(tagstring,)))

    else:
        createform = CreateForm()
        seetagform = SeeTagForm()

else:
    createform = CreateForm()
    seetagform = SeeTagForm()

嗯,据我所知,这些很多,如果只有2个按钮(但这里只需要一切),所以我想知道我喜欢的时候可能会有什么困惑。我的页面上有12个按钮。这看起来并不过于pythonic! 是否有更简单/更聪明的方法来处理许多表单提交?

提前致谢

1 个答案:

答案 0 :(得分:0)

我也是这样做的,只需在按钮名称上添加前缀就可以更清晰了

@login_required def profile_view(request): message = None user = MyUser.objects.get(pk=request.user.pk) addresses = user.profile_address.all() AddressFormSet = modelformset_factory(Address, fields=['city','zip_code','address','phone','default_address', 'first_name','last_name']) address_formset = AddressFormSet(queryset=addresses) profile_form = ProfileForm(instance=user) pass_form = PasswordChangeForm() if request.method == "POST": if 'btn_profile' in request.POST: profile_form = ProfileForm(request.POST, instance=user) if profile_form.is_valid(): profile_form.save() messages.add_message(request, messages.INFO, 'Successfully changed your profile') return HttpResponseRedirect(reverse('profile')) if 'btn_pass' in request.POST: pass_form = PasswordChangeForm(request.POST) if pass_form.is_valid(): user.set_password(pass_form.cleaned_data['password1']) user.save() messages.add_message(request, messages.INFO, 'Successfully changed your password') return HttpResponseRedirect(reverse('profile')) if 'btn_address' in request.POST: address_formset = AddressFormSet(request.POST) if address_formset.is_valid(): for address_form in address_formset: if address_form.is_valid() and address_form.has_changed(): address = address_form.save(commit=False) address.user_profile = user address.save() return HttpResponseRedirect(reverse('profile')) orders = Order.objects.filter(user = user).order_by('-created') context = { 'address_formset': address_formset, 'pass_form': pass_form, 'profile_form':profile_form, 'message':message, 'orders':orders, } return render(request,'custom_auth/profile.html', context)