$ django-admin.py startproject myproject $ cd myproject $ python manage.py startapp contacts $ mkdir html
Edit your project's settings.py file and make the following changes:
- Configure your database (sqlite3 is convenient)
- Add 'myproject.contacts' to your INSTALLED_APPS list
- Add 'html' to your TEMPLATE_DIRS list
from django.db import models # Create your models here. class Contact(models.Model): name = models.CharField(maxlength=200) phone = models.CharField(maxlength=200)
The View
Edit the contacts/views.py file to contain the following code:
from myproject.contacts.models import Contact
from django import newforms as forms
from django.shortcuts import render_to_response
def main(request):
# initialize variables to sent to template
message = ''
submit_action = 'Add'
edit_id = ''
# generate default form
ContactForm = forms.form_for_model(Contact)
f = ContactForm()
# handle edit and delete events
if request.method == 'GET':
if request.has_key('edit_id'):
# replace default form with form based on row to edit
contact = Contact.objects.get(pk=request.GET['edit_id'])
ContactForm = forms.form_for_instance(contact)
f = ContactForm()
submit_action = 'Update'
edit_id = request.GET['edit_id']
message = 'Editing contact ID ' + request.GET['edit_id']
if request.has_key('delete_id'):
Contact.objects.get(pk=request.GET['delete_id']).delete()
message = 'Contact deleted.'
# handle add and update events
if request.method == 'POST':
if request.POST['submit_action'] == 'Add':
# attempt to do add
add_f = ContactForm(request.POST)
if add_f.is_valid():
add_f.save()
message = 'Contact added.'
else:
# validation failed: show submitted values in form
f = add_f
if request.POST['submit_action'] == 'Update':
# attempt to do update
contact = Contact.objects.get(pk=request.POST['edit_id'])
ContactForm = forms.form_for_instance(contact)
update_f = ContactForm(request.POST.copy())
if update_f.is_valid():
update_f.save()
message = 'Contact updated.'
else:
# validation failed: prepare form for new update attempt
submit_action = 'Update'
edit_id = request.POST['edit_id']
f = update_f
# get existing contacts
contact_list = Contact.objects.all()
# return rendered HTML page
return render_to_response(
'contacts.html',
{ 'request': request,
'message': message,
'contact_list': contact_list,
'form': f.as_table(),
'submit_action': submit_action,
'edit_id': edit_id
}
)The Template
Last, we have to define our Django template.
Create a file at html/contacts.html that contains the following code:
<html>
<head>
<title>Contacts</title>
</head>
<body>
{% if message %}
<b>{{ message }}</ b>
<p />
{% endif %}
{% if contact_list %}
<table>
{% for contact in contact_list %}
<tr bgcolor='{% cycle FFFFFF,EEEEEE as rowcolor %}'>
<td>{{ contact.name }}</td>
<td><a href='{{ request.path }}?edit_id={{ contact.id }}'>Edit</a></td>
<td><a href='{{ request.path }}?delete_id={{ contact.id }}'>Delete</a></td>
</tr>
{% endfor %}
</table>
<p />
{% endif %}
<form action='{{ request.path }}' method='POST'>
<input type='hidden' name='edit_id' value='{{ edit_id }}'>
<table>
{{ form }}
<tr>
<td colspan=2 align=right>
<input type=submit name='submit_action' value='{{ submit_action }}'>
</td>
</tr>
</table>
</form>
{% ifnotequal submit_action 'Add' %}
<p />
<a href='{{ request.path }}'>Add New Contact</a>
{% endifnotequal %}
</html>The End Result
Now that we've set up the project and defined a model, view, and template we synchronize the database and run the test server with the commands below:
$ python manage.py syncdb $ python manage.py runserver

Fri, 2007-09-14 00:27
I tried displaying the the form using MYSQL. The page didn't render properly.
Any ideas on getting your example to work with MYSQL?
Mon, 2007-10-08 19:50
Hi John,
I did use MySQL so it should work.
Sun, 2008-03-09 08:43
Yup, works on my end.
my site:
free razr
Thu, 2007-04-26 13:21
Unfortunately the example can not be developed further - it needs to be unraveled and reconstructed before it is a useful prototype. This example has "Delete" instructions coming in on a GET. GETs should be side-effect free.
David
Sat, 2007-04-28 04:12
Hi David,
Good point... I should retool that part of the tutorial. Thanks for the feedback!
Thu, 2007-04-26 13:15
This tutorial rocks.
Try adding a new field to the database
email varchar 75And the following line to model.py
email = models.EmailField()Then load the page at http://127.0.0.1:8000/contacts/ again!
It just works.
Try entering an email of "abc" and watch the automatic validation!
Thanks Mike!
Sat, 2007-03-03 12:48
I solved my problem - the urls.py file is not able to generate a decent error on a url that is not written in parenthesis.
I did
r'^contacts/', 'myproject.contacts.views.main'.
instead of:
(r'^contacts/', 'myproject.contacts.views.main').
Code 18
works fine now.
This is going to be helpful.
Do you have any idea how you would retrieve fields from a database and map it into a CSS form?
Kind of for: (string1,string2,string_n); ask string.color
and it would retrieve the strings from a table.
f.
Sat, 2007-03-10 07:26
Hi Francois,
For the CSS thing do you mean passing an entire row into a template then using a field from the row to specify CSS properties?
I'm not sure how to offhand, but my guess is it wouldn't be too tricky. When I get some time hopefully I can take a gander at that problem.
Cheers and thanks for stopping by!
Mike
Sat, 2007-03-03 12:30
I do not understand what is happening, but it seems to complain on the notion of a URL bound to request.path
-=Francois=-
Request Method: GET
Request URL: http://www.server.net:8000/
Exception Type: TypeError
Exception Value: __init__() takes at most 4 arguments (11 given)
Exception Location: /usr/lib/python2.4/site-packages/django/conf/urls/defaults.py in patterns, line 18
Traceback (innermost last)
Switch to copy-and-paste view
/usr/lib/python2.4/site-packages/django/core/handlers/base.py in get_response
return response # Get urlconf from request object, if available.
Sat, 2008-07-12 13:10
thanks for information
Wed, 2007-02-28 16:45
Thanks for the complete example - looks good! I will check it out and see if this works. Do you need any additional patches?
Sat, 2007-03-10 07:21
You shouldn't need any additional patches, but you need the latest version of Django from Subversion (not the latest release version).
Mon, 2007-02-26 02:10
Thanks, Mike! I found that very helpful. I came across your link in the comments to the Newforms documentation, so it's a good thing you put it there :-)
Do you only have anonymous comments? I can't see where to put my name in. I'm evariste.
Sat, 2007-03-10 07:18
Hi Evariste,
Yeah, I've got to refine my comments a bit. Would be nice to get people's names, websites, etc. I'll get that happening soon.
Glad the post was helpful and thanks for dropping by! :)
Mike
Fri, 2007-03-30 22:16
If you ever try rebuild this example to work with FileInput field for file uploads, don't forget to put enctype="multipart/form-data", so you get all needed properties to access your files properties ['filename'] and ['content'].
Example:
.