Editing a Favorite
Do you want to edit a field of a particular Favorite object? It's easy. You just access the object you want, edit the fields you want, and save the object in the database:
favorite = Favorite.objects.get(id=1) favorite.title = "Washington Post" favorite.save( )
The next time you access the field from the database, it will contain the new data:
title = Favorite.objects.get(id=1).title
Let's look at this process in action.
- Using a text editor, edit chapter4\favorites\views.py, adding the code shown in Listing 4.17.
Listing 4.17. The edited views.py file.
from django.http import HttpResponse from django.contrib.auth.models import User from favorites.models import * def main_page(request): favorite = Favorite.objects.get(id=1) favorite.title = "Washington Post" favorite.save( ) . . . output = ''' <html> <head> <title> Connecting to the model </title> </head> <body> <h1> Connecting to the model </h1> The edited favorite title: %s </body> </html>''' % ( . . . ) return HttpResponse(output)
- Add the code to actually access the edited title and display it, shown in Listing 4.18.
Listing 4.18. The completed views.py file.
from django.http import HttpResponse from django.contrib.auth.models import User from favorites.models import * def main_page(request): favorite = Favorite.objects.get(id=1) favorite.title = "Washington Post" favorite.save( ) title = Favorite.objects.get(id=1).title output = ''' <html> <head> <title> Connecting to the model </title> </head> <body> <h1> Connecting to the model </h1> The edited favorite title: %s </body> </html>''' % ( title ) return HttpResponse(output)
- Save views.py.
- Open a command prompt and navigate to the chapter4 directory:
$ cd django-1.1\django\bin\chapter4
- Run the development server:
$ python manage.py runserver
- Navigate your browser to http://localhost:8000.
You should see the Web page that appears in Figure 4.7.
Figure 4.7 Displaying an edited Favorite object.