Previous Page Next Page

Adding Data to the Database

The process of adding data to the database is basically the same as updating existing data. You start with an empty form, add data to it, and then use save() to update the database. The difference is that the primary key of the Form object either doesn't already exist in the database or is not present in the object.

Django adds the primary key ID to objects if one is not specified in the model. However, you can assign your own primary key in the model and then set the value in the view function to tell Django to add the data as a new object.

Watch Out!

If you do decide to assign a primary key to the object, you need to make certain that the key is unique. Otherwise, existing data might be overwritten.


Try It Yourself: Add New Objects to the Database Using Form Data

In this section, you will add a new view to the People views that will render a form to create Blog objects and assign them to a Person object. You will add a POST handler just as you did in the person_form() view that will collect data from the POST request. However, this time you will start with a blank Blog Form so that a new Blog object is added to the database. You will also be required to add code to add the Blog object to a specific Person object.

Follow these steps to add the add_blog() view to the iFriends project:

1.
Open the iFriends/Person/views.py file in an editor.

2.
Create a new view function called add_blog(), as shown in Listing 11.5.

3.
Add the following lines of code, shown in Listing 11.5, to initialize a BlogForm instance and message and to get the Person object that the new Blog will be added to:

BlogForm = forms.form_for_model(Blog, fields=('title', 'text'))
bf = BlogForm()
message = 'Unknown Request'
p = get_object_or_404(Person, pk=pID)

4.
Add the following lines of code, shown in Listing 11.5, to add a simple GET handler:

if request.method == 'GET':
    message = 'Add Blog for %s ' % p.name

5.
Add the following lines of code, shown in Listing 11.5, to begin adding the POST handler to the view:

if request.method == 'POST':
    if request.POST['submit'] == 'Add':

6.
Add the following line of code to the POST handler, shown in Listing 11.5, to create an instance of the BlogForm with only the title and text Fields from the POST data that will be rendered in the template:

bf = BlogForm(request.POST.copy())

7.
Add the following lines of code to the POST handler, shown in Listing 11.5, to create a Form class for the full Blog. Add the title and text Fields from the POST data and a date Field set to the current time to a dictionary. Use that dictionary to create an instance of the SaveForm for the Blog object:

SaveForm = forms.form_for_model(Blog)
postDict = request.POST.copy()
postDict['date'] = datetime.now()
save_bf = SaveForm(postDict)

8.
Add the following line of code to the POST handler to validate the instance of the Blog SaveForm and either save the object or set the error message:

if save_bf.is_valid():
    try:
        bObj = save_bf.save()
. . .
        message = 'Blog added to %s.' % p.name
    except:
        message = 'Database Error.'
else:
    message = 'Invalid data in Form.'

9.
Add the following lines of code to the try block in the POST handler, shown in Listing 11.5, to add the new Blog object to the Person object, and save the Person object:

p.blogs.add(bObj)
p.save()

10.
Add the following lines of code to the end of the add_blog() function, shown in Listing 11.5, to render the data to an add_blog_form.html template file.

return render_to_response(
    'People/add_blog_form.html',
    {'bForm':bf, 'message': message})

11.
Save the iFriends/Person/views.py file.

12.
Create and open a file called iFriends/templates/Person/add_blog_form.html in an editor.

13.
Add the code shown in Listing 11.6 to the file to render a Blog Form object, bForm, as a table, and add an Add button to submit the form.

14.
Save the iFriends/templates/Person/add_blog_form.html file.

15.
Open the iFriends/templates/Person/person_details.html file in an editor.

16.
Add the following lines of code to the <h3> header "Blog Entries," shown in Listing 11.7, to add a link to the add_blog() view function:

<a href="
 {% url iFriends.People.views.add_blog pID=p.id %}
 ">[+]</a>

17.
Open the iFriends/People/urls.py file in an editor.

18.
Add the following line to the URL patterns to enable the add_blog() view function:

(r'^AddBlogForm/(?P<pID>\d+)/$', 'add_blog'),

19.
Save the iFriends/People/urls.py file.

20.
Access the following URL in a web browser to bring up the Person details() view, shown in Figure 11.6, and verify that the new link has been added to the Blog object:

http://127.0.0.1:8000/Person/Info/1/

Figure 11.6. Person details() view with a link to the add_blog() view.


21.
Click the + link to bring up the blog_add() view, shown in Figure 11.7.

Figure 11.7. add_blog() view rendering a Blog Form.


22.
Add data to the form, and click the Add button. The message should indicate that the new blog entry was added.

23.
Access the following URL again in a web browser to bring up the Person details() view, shown in Figure 11.8. This time the new entry you created in step 22 should show up in the blog list.

http://127.0.0.1:8000/Person/Info/1/

Figure 11.8. Person details() view with an updated blog entry from the add_blog() view.


Watch Out!

You may need to refresh the browser to retrieve a fresh copy of the details() view to see the new blog entry.


Listing 11.5. Full Contents of the add_blog() view in iFriends/People/views.py

def add_blog_form(request, pID='0'):
    BlogForm = forms.form_for_model(Blog, fields=('title', 'text'))
    bf = BlogForm()
    message = 'Unknown Request'
    p = get_object_or_404(Person, pk=pID)

    if request.method == 'GET':
        message = 'Add Blog for %s ' % p.name

    if request.method == 'POST':
        if request.POST['submit'] == 'Add':
            bf = BlogForm(request.POST.copy())
            SaveForm = forms.form_for_model(Blog)
            postDict = request.POST.copy()
            postDict['date'] = datetime.now()
            save_bf = SaveForm(postDict)
            if save_bf.is_valid():
                try:
                    bObj = save_bf.save()
                    p.blogs.add(bObj)
                    p.save()
                    message = 'Blog added to %s.' % p.name
                except:
                    message = 'Database Error.'
            else:
                message = 'Invalid data in Form.'

    return render_to_response(
        'People/add_blog_form.html',
         {'bForm':bf, 'message': message})


					  

Listing 11.6. Full Contents of the person_form() view in iFriends/People/views.py

{% extends "iFriends_base.html" %}

{% block title %}Blog Form{% endblock %}
{% block content %}
<h3>{{ message }}</h3>

<form method="post" action=".">
<table>
{{ bForm }}
</table>

<input type="submit" name="submit" value="Add" />
</form>
{% endblock %}

Listing 11.7. Full Contents of iFriends/templates/People/person_details.html

% extends "iFriends_base.html" %}

{% block title %}Details{% endblock %}
{% block content %}
<table width=100%>
<tr bgcolor="aabbcc"><td colspan="3">
<font size="5" color="white">Personal Information</font>
<a href="{% url iFriends.People.views.person_form pID=p.id %}">[Edit]</a>
</font>
</td></tr>
<tr valign="top"><td width=30% bgcolor="aaaaaa"><font color="white" size="5">
    <li>Name: {{p.name}}</li>
    <li>Birthday: {{ p.birthday|date:"m/d/Y" }}</li>
    <li>Gender:
        {% ifequal p.gender "M" %}
            Guy
        {% else %}
            Gal
        {% endifequal %}
    </li>
    <li>Desc: {{ p.desc }} </li>
</font></td>
<td width=40% bgcolor="aa99aa"><font color="white" size="4">
    {% include "quote.html" %}
</font></td>
<td width=30%>
    <h3>Contact Info</h3>
    <li>Email: {{ p.email }}</li>
    <li>Website: {{ p.favoriteURL }}</li>
</td></tr>
<tr>
<td width="30%" bgcolor="556677" valign="top">
    <font color="white" size="4">
    {% with p.friends.all as fl %}
    <h3>
        {{ fl|length|yesno:"iFriend,No Friend"}}{{fl|length|pluralize}}
    </h3>
    {% for f in fl %}
    <li>{{ f.name }}</li>
    {% endfor %}
    {% endwith %}
    </font>
</td>
<td width="70%" bgcolor="eeeeee" colspan="2" valign="top">
    <font size="4">
    {% with p.blogs.all as bl %}
    <h3>
        {{ bl|length|yesno:"Blog,No Blog"}}
        Entr{{ bl|length|pluralize:"y,ies"}}
        <a href="
        {% url iFriends.People.views.add_blog pID=p.id %}
        ">[+]</a>
    </h3>
    {% for b in bl %}
    <li>{{ b.title }} -
        <font size="2"> {{ b.date|date:"M d, Y g:ma" }}</font>
    </li>
    {% endfor %}
    {% endwith %}
    </font>
</td>
</tr>
</table>
{% endblock %}


					  


Previous Page Next Page