Receive our weekly advanced programming tips for FREE
Django processuing multiple objects in forms
| 0 votes
Autor: bookkeeper
Chapter: Django

How do i validate multiply object with one forms?

It's Django, it's simple!

We have a normal model like:
from django.db import models

class MyModel(models.Model):
    cool_field = models.CharField(max_length=32)

To validate data with the form
from django import forms

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

In views it will look like this:
from django.utils import simplejson
from django.shortcuts import render_to_response
from models import *
from forms import *

def index(request):
    if request.method == 'POST':
        forms = [MyModelForm(request.POST, prefix=str(x)) for x in xrange(0, 5)]
        if all([x.is_valid() for x in forms]):
            print "jup"
        forms = [MyModelForm(prefix=str(x)) for x in xrange(0,5)]
    return render_to_response('index.html', locals())
{% for form in forms %} {{ form.as_p }} {% endfor %} <input value="OK" type="submit"/>

The function "all" is new in python 2.5, it will return true if all emelent are true