Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change a form value before validation in Django form

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 ?

like image 741
Nuno_147 Avatar asked Aug 30 '13 13:08

Nuno_147


People also ask

How do I override a form in django?

You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form.

What is form Is_valid () in django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What is form cleaned_data in django?

cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).


2 Answers

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.

like image 100
Ixio Avatar answered Oct 15 '22 19:10

Ixio


one trick for what you want is to do it like this:

changed_data = dict(request.POST)
changed_data['price'] = NEW_PRICE
search_packages_form = SearchPackagesForm(data = changed_data)
like image 31
Milad Khodabandehloo Avatar answered Oct 15 '22 21:10

Milad Khodabandehloo