Accessing a Specific User
You can also access User objects in code. For example, you might want to access a user's email address, which is recorded in the User field email.
Using the get method, you can access a specific user by username. At this point, the database contains only one user: the superuser we created in the previous chapter. In the database shown in this book, that superuser is 'steve' (substitute your own superuser name to make this example work):
User.objects.get(username='steve')
Also, you can access the user's email address using the User object's email field:
email = User.objects. get(username='steve').email
Let's put this process to work in views.py.
To access a specific user:
- Using a text editor, edit chapter4\favorites\views.py, adding the code shown in Listing 4.11.
Listing 4.11. 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): output = ''' <html> <head> <title> Connecting to the model </title> </head> <body> <h1> Connecting to the model </h1> User steve's email: %s </body> </html>''' % ( . . . ) return HttpResponse(output)
- Add the code to actually access the user's email and display it, shown in Listing 4.12.
Listing 4.12. 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): email = User.objects. get(username='steve').email output = ''' <html> <head> <title> Connecting to the model </title> </head> <body> <h1> Connecting to the model </h1> User steve's email: %s </body> </html>''' % ( email ) 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 shown in Figure 4.4.
Figure 4.4 Displaying a user's email address.