Receive our weekly advanced programming tips for FREE
29.June
Django processuing multiple objects in forms
0
| 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:

models.py
from django.db import models

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

To validate data with the form

forms.py
from django import forms

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

In views it will look like this:

views.py
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"
    else:
        forms = [MyModelForm(prefix=str(x)) for x in xrange(0,5)]
       
    return render_to_response('index.html', locals())
index.html
{% 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