Question

I am a primarily a PHP guy. How would I handle forms in django? I managed to create a form, model and a view. Now I want to save my data into the database.

#forms.py
from django import forms
import datetime

class CommentForm(forms.Form):
    name = forms.CharField(initial='Your name')
    comment = forms.CharField(initial='You comment')
    commend_date = forms.DateField(initial=datetime.date.today);
    posted_by = forms.CharField(max_length=200)

And my view is like this:

#views.py
from django.shortcuts import render_to_response
from django.http import Http404
from django.template import Template, Context
from mysite.blog.models import Blog         #load a model
from mysite.blog.forms import CommentForm   #load a form


def index(request):
    try:
        blog_posts = Blog.objects.all().order_by('-post_date')[:10]

        if request.method == 'POST':
            form = CommentForm(request.POST)
        else:
            form = CommentForm()

    except Blog.DoesNotExist:
        raise Http404

    return render_to_response('blog/posts.html', locals())

Then my template (blog/posts.html) is like this:

{% extends "base.html" %}
{% block title %}Dummy Django Site{% endblock %}
{% block heading %}A sample header{% endblock %}
{% block content %}

    {% if blog_posts %}
        {% for post in blog_posts %}
        <b>{{post.title}}</b><br/>
        <b>{{post.post_date}}</b><br/>
        <b>{{post.posted_by}}</b><br/>
        {{post.content}}
        {% endfor %}
    {% endif %}

    <h2>A Sample Form</h2>
    <form action="" method="POST">
        {% for field in form %}
            <div class="fieldWrapper">
                {{ field.errors }}
                {{ field.label_tag }}: {{ field }}
            </div>
        {% endfor %}
        <p><input type="submit" value="Send message" /></p>
    </form>

{% endblock %}

{% block footer %}
<hr/>
Great footer!
{% endblock %}

In PHP, I would put in something in my controller like:

//from <form action="http://mysite.com/saveComment" method="POST" >
function saveComment() {
    $data['name'] = $_POST['name'];
    $data['comment'] = $_POST['comment'];
    $model->save($name);
}

How would I do that in Django? What where would I put the code?

Any reply would be greatly appreciated.

Was it helpful?

Solution

If you really need a lot of custom stuff, check out ModelForms, but Generic Views are sufficient for an awful lot of use cases.

P.S. If you're really doing Comment-related stuff, check out the provided Comments app in django.contrib.comments.

UPDATE: Instead of defining your views and forms as you have above, use a ModelForm instead. This will allow to use code like the following to do the save:

# Save a new Comment object from the form's data.
>>> new_comment = my_comment_form.save()

The change to your forms.py would change the definition of CommentForm to something like:

from django.forms import ModelForm

class CommentForm(ModelForm):
    class Meta:
        model = Comment  # Assumes you've imported your model somewhere

UPDATE 2: In general:

  • to save a model instance, just invoke .save()
  • to access POST data from a form, use the cleaned_data attribute of the Form you constructed from the POST
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top