2

I am trying to create a helper function that validates forms. If the form is valid, then I will create an object in the database. The function takes in three arguments, the request, the form, and the model.

def form_validate(request, form, model):
  form = form(request.POST)
  print form
  if form.is_valid():
    print "the form is valid"
    # create object using valid form
  else:
    print "the form is not valid"
    # send back items
    print form.errors.items()

If the form is valid, I want to use the form data to create a new model. How would I do that? I have tried to look at the Django docs(https://docs.djangoproject.com/en/dev/topics/forms/) but I cannot find the answer.

1
  • You should come back to documentation. Commented Feb 8, 2012 at 8:12

2 Answers 2

4

As David Wolever said, using ModelForms is the obvious way.

You could also pass the cleaned_data dictionary to the model constructor (assuming the fields are the same):

def form_validate(request, form, model):
    form = form(request.POST)
    print form
    if form.is_valid():
        print "the form is valid"
        obj = model(**form.cleaned_data)
        obj.save()
    else:
        # etc

However, ModelForms are really the easiest way of doing this, but you might be interested in reading Django's source to see how they work.

Sign up to request clarification or add additional context in comments.

1 Comment

I know it's an old question, but I ran into this from google and still have questions: what do we do if there is no "form", but only form data because of a call from an external domain with a payload, so that we only have POST data to work with?
1

You'll likely want to look at ModelForms: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.