Hello,
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.