Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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.

  1. 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)
    
  2. 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)
    
  3. Save views.py.
  4. Open a command prompt and navigate to the chapter4 directory:
    $ cd django-1.1\django\bin\chapter4
  5. Run the development server:
    $ python manage.py runserver
  6. Navigate your browser to http://localhost:8000.

    You should see the Web page that appears in Figure 4.7.

    Figure 4.7

    Figure 4.7 Displaying an edited Favorite object.

  • + Share This
  • 🔖 Save To Your Account