在Django表单中进行验证之前更改表单值 [英] change a form value before validation in Django form

查看:87
本文介绍了在Django表单中进行验证之前更改表单值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django表单,并在我的view函数上执行此操作:

  search_packages_form = SearchPackagesForm(data = request.POST )

我想覆盖一个称为price的表单字段,该字段已这样清除:

 价格=表格.ChoiceField(选择= PRICE_CHOICES,必填= False,小部件=表格.RadioSelect)

我想在调用 search_packages_form.is_valid()

我想这样做:

  search_packages_form.data ['price'] = NEW_PRICE 

但这不起作用。有什么想法吗?

解决方案

可能不是Django方式,而是基于https://stackoverflow.com/a/17304350/2730032 我想在验证之前更改表单值的最简单方法是执行以下操作:

  def search_packages_view(request):
if request.method =='POST'
Updated_request = request.POST.copy( )
Updated_request.update({'price':NEW_PRICE})
search_packages_form = SearchPackagesForm(updated_request)
if search_packages_form.is_valid():
#你们都很好

这是可行的,但是如果有人有其他更符合Django的方式,或者是否没有:然后解释原因。


I have a django form and on my view function I do this :

search_packages_form = SearchPackagesForm( data = request.POST )

I would like to overwrite a form field called price which is decleared as such :

price = forms.ChoiceField( choices = PRICE_CHOICES, required = False,widget = forms.RadioSelect )

I would like to overwrite the form field before calling search_packages_form.is_valid()

I thought of doing :

search_packages_form.data['price'] = NEW_PRICE

But it does not work. Any ideas ?

解决方案

Probably not the Django way but based on https://stackoverflow.com/a/17304350/2730032 I'm guessing the easiest way to change your form value before validation is to do something like the following:

def search_packages_view(request):
    if request.method == 'POST'
        updated_request = request.POST.copy()
        updated_request.update({'price': NEW_PRICE})
        search_packages_form = SearchPackagesForm(updated_request)
        if search_packages_form.is_valid():
             # You're all good

This works but I'd be interested if anyone has another way that seems more in line with Django, or if there isn't: then an explanation about why.

这篇关于在Django表单中进行验证之前更改表单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆