views:

64

answers:

2

I have a form generated from various models and the various values filled go and sit in some other table. Hence, in this case I haven't used the inbuilt Django forms(i.e. I am not creating forms from models ).

Now the data which is posted from the self made form is handled by view1 which should clean the data accordingly. How do I go about it and use the various functions clean and define validation errors (and preferably not do validation logic in the view itself!)

EDIT:
I have 3 models defined ==> 3 db tables. Now a form is to be created which shows data from 2 of the models and then the data from this form is to be saved in the 3rd table! In this scenario, I have created the form myself and I want to use form functionalities to validate the inputs of this self-made form. How should I go about it? In case, I cannot use the inbuilt form functionalities, where and how do i validate this self-made form(not using form from models)

A: 

The only interaction the view should have with the form is to control when the data is validated, and what to do if it is or is not valid, as in,

if form.is_valid():
    do_something()

Otherwise everything should be done in the form class, using the clean_fieldname() and clean() methods. See http://docs.djangoproject.com/en/dev/ref/forms/validation/ for more info on how to define these within a form.

Casey Stark
A: 

I'm still not sure why you couldn't use built-in form validation methods.

Assume models:

class A(models.Model):
   a = models.CharField()

class B(models.Model):
   b = models.CharField()

class C(models.Model):
   c = models.CharField()
   d = models.CharField()

Assume that values from A.a and B.b need to end up in C.c and C.d model through form:

class MyForm(forms.Form):
   a = forms.CharField()
   b = forms.CharField()

When you populate and submit your form do a standard validation on it:

if request.method == "POST": 
   form = MyForm(request.POST)
   if form.is_valid():
      model3 = C() # create 3rd model objects
      model3.c = form.cleand_data['a'] # and assign values from form to it
      model3.d = form.cleand_data['b']
      model3.save() # save the data into the 3rd table

Or you could use model validation instead of form validation but it's more or less the same principle.

Or am i still not reading your question correctly? Example code is always welcomed.

rebus