Changing request.POST values (QueryDict instance is immutable)

Posted: February 12th, 2010 | Author: Davo | Filed under: Django | Tags: | No Comments »

When trying to change the request.POST values an exception is raised with: QueryDict instance is immutable.
The request.POST is immutable which means you cannot change/alter it.
To cope this you will need to copy() it.

def something(request):
    ...
    if request.method == 'POST':
        post_values = request.POST.copy()
        # post_values can now be changed. For instance if you have a
        post_values['some_input'] = 'I am changing it!'
        # this can be used for forms etc...
        # Ex:
        form = SomeForm(post_values)
    ...

Show form errors (non field errors)

Posted: February 5th, 2010 | Author: Davo | Filed under: Django | Tags: , , , | 1 Comment »

In the current Django version it is possible to implement form validation by overriding the clean() function.
For instance a ContactForm:

class ContactForm(forms.Form):
    # ... fields...
   field1 = forms.IntegerField()

   def clean(self)
       cleaned_data = self.cleaned_data
       f = cleaned_data.get('field1')
       if f > 10:
          raise forms.ValidationError("Did you just enter more than 10?")
       return cleaned_data # Never forget this otherwise you will end up with empty request.POST in the views.py.

In order to show that “Did you just enter more than 10″ error in the template:

<!-- assuming that you have form as ContactForm. -->
{{ form.non_field_errors }}

Session array/list append does not work

Posted: February 1st, 2010 | Author: Davo | Filed under: Django | Tags: , , , | 5 Comments »

I was trying to save and update some arrays inside the Django session object but it was not working at all…

The following snippet DOES NOT WORK

request.session['array'] = [] # let's create an empty array
# try to append some integers...
request.session['array'].append(1)
request.session['array'].append(2)
request.session['array'].append(3)
...

In order to solve this we need to store the array in a temporary object first.
Quick fix:

request.session['array'] = []
tmp = request.session['array']
tmp.append(1)
tmp.append(2)
tmp.append(3)
request.session['array'] = tmp # this works now.
...