Creating a New User
Editing fields in a database as we did in the previous topic is fine if the object you want to work with already exists. But what if it doesn't? What if you want to create a new object in the database yourself, from code?
For example, how would you create a new User object? For that, you can use the create_user method and then save the new User object, like this:
user = User.objects.create_user( username = 'nancy', password = 'opensesame', email = 'nancy@nancy.com' ) user.save( )
Here, we'll create a new user and then get the user's email address to confirm that the new user exists.
To create a new user:
- Using a text editor, edit chapter4\favorites\views.py, adding the code shown in Listing 4.19.
Listing 4.19. 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): user = User.objects.create_user( username = 'nancy', password = 'opensesame', email = 'nancy@nancy.com' ) user.save( ) . . . output = ''' <html> <head> <title> Connecting to the model </title> </head> <body> <h1> Connecting to the model </h1> The new user's email: %s </body> </html>''' % ( ) return HttpResponse(output)
- Add the code to actually access the new user's email address and display it, shown in Listing 4.20.
Listing 4.20. 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): user = User.objects.create_user( username = 'nancy', password = 'opensesame', email = 'nancy@nancy.com' ) user.save( ) email = User.objects. get(username='nancy').email output = ''' <html> <head> <title> Connecting to the model </title> </head> <body> <h1> Connecting to the model </h1> The new user's email: %s </body> </html>''' % ( email ) return HttpResponse(output)
g - 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.8.
Figure 4.8 Displaying the new user's email address.