In this section, we are going to start learning how to design a user system, and Django provides an application called "Django.contrib.auth" that we can use to make user registration, login, logout, and so on.
17. User Model
In the Django-brought user system, the user model already contains the following data:
- User name
- Password
- E-Mail
- Name
We want to add some extra fields to the user model, such as:
- Link fields: Allow users to show their own personal sites
- Picture field: Lets the user set an avatar for himself
We just need to update the model to achieve the above requirements, edit the rango/models.py file, first add a line to the head:
rango/models.py:
from Import User
Then add the following at the end of the file:
rango/models.py:
class UserProfile (models. Model): # This sentence is necessary, Link UserProfile to the Django User model user = models. Onetoonefield (User) # We want to add extra fields Website = models. Urlfield (Blank=true) picture = models. ImageField (Upload_to= " profile_images " Span style= "COLOR: #800000" > ", Blank=true) # Override the __str__ method so that it displays the user name when it is invoked def __str__ return self.user.username
In both fields, we set the "Blank=true", just as the literal meaning shows, this is the rhythm that allows the field to be empty.
Note in the "ImageField" field, there is a "upload_to" attribute that specifies the folder where the user picture is stored, and the folder called "Profile_images" will be placed in the Media_ specified in settings.py. root folder, in other words, its path will be:
rangoproject/media/profile_images/
After the model is done, we need to update the database and then run the following command at the DOS command prompt:
$ python manage.py makemigrations Rango
To continue running the command at a DOS command prompt:
$ python manage.py Migrate
18. Installing PIL
Django's ImageField uses Python's image library PiL, and if you don't have PIL installed, you'll need to install it first.
In the Python 3.2 environment of the Windows platform, it is recommended to install this version:
https://pypi.python.org/pypi/Pillow/2.6.0
Find the Pillow-2.6.0.win32-py3.2.exe (MD5) and download it and install it directly. Note that this is the version for Python 32-bit.
19. Register UserProfile in the Admin interface
Edit the rango/admin.py file to make it look like this:
Rango/admin.py:
fromDjango.contribImportAdmin fromRango.modelsImportCategory, Page fromRango.modelsImportUserProfileclasspageadmin (admin. Modeladmin): List_display= ('title','category','URL')classcategoryadmin (admin. Modeladmin): Prepopulated_fields= {'Slug':('name',)} Admin.site.register (Category, Categoryadmin) admin.site.register (Page, Pageadmin) admin.site.register (userprofile)
20. Create user registration views and templates
The "User Registration" feature will allow users to create accounts on our site, and we need to add views and templates for this feature. Here are the work to be done:
- Create two forms of UserForm and Userprofileform;
- Add view, handle new user;
- Create a template to display UserForm and Userprofileform both forms;
- Map the URL to the view created above;
- Add a link to the registration page in the homepage;
Let's take this one step at a pace! Edit the rango/forms.py file to make it look like this:
Rango/forms.py:
classUserForm (forms. Modelform): Password= Forms. Charfield (widget=forms. Passwordinput ())classMeta:model=User Fields= ('username','Email','Password')classUserprofileform (forms. Modelform):classMeta:model=userprofile Fields= ('website',' Picture')
You will find that we have added two meta classes to both the UserForm and Userprofileform forms, each with a model field that tells the program which table the form will be associated to in the database. For example, UserForm is associated with the user table.
Finally, don't forget to change the forms.py head to the following:
Rango/forms.py:
from Import Forms from Import User from Import Category, Page, userprofile
To get this done, let's create a user registration view.
Edit Rango/views.pyand add the following:
Rango/views.py (note put the first line of code in the file header):
fromRango.formsImportUserForm, UserprofileformdefRegister (Request):#registered: The sign of success or not. #The default is False, and the program changes to true after the registration is successful.Registered =False#if it is an HTTP POST request, it means that the form data will be processed. ifRequest.method = ='POST': #try to get the data from the submitted information. #Note that this data is used by both UserForm and Userprofileform.User_form = UserForm (data=request. POST) Profile_form= Userprofileform (data=request. POST)#If the form is valid ... ifUser_form.is_valid () andprofile_form.is_valid ():#Store user form data in a database.user =User_form.save ()#use the Set_password method to process the password. #The user data is then stored.User.set_password (User.password) user.save ()#now take care of the UserProfile form. #set the commit to false first. #This signal is used to delay the data storage action until we have the data ready. Profile.user =User#does the user provide a picture (avatar)? #if so, store it in the database. if ' Picture' inchrequest. FILES:profile.picture= Request. files[' Picture'] #store userprofile data.Profile.save ()#update the registered signal and change it to true, this signal informs the template system that the user has completed the registration.Registered =True#invalid or error form #The fault code is displayed to the terminal and the user. Else: Print(User_form.errors, profile_form.errors)#non-HTTP POST request, let's just render two blank forms for user input. Else: User_form=UserForm () profile_form=Userprofileform ()#renders a template based on content. returnrender (Request,'rango/register.html', {'User_form': User_form,'Profile_form': Profile_form,'Registered': Registered})
Next, create a registration template, create a templates/rango/register.html, and add the following:
Templates/rango/register.html:
<!DOCTYPE HTML><HTML> <Head> <title>Rango</title> </Head> <Body> <H1>Register Rango</H1>{% if registered%} Rango says:<Strong>Thank you very much for registering!</Strong> <ahref= "/rango/">Return to the first page.</a><BR/>{% Else%} Rango says:<Strong>Register please click here!</Strong><BR/> <formID= "User_form"Method= "POST"Action= "/rango/register/"enctype= "Multipart/form-data">{% Csrf_token%}<!--each form is displayed, and the As_p method processes each element as a paragraph. This ensures that each element appears as a new line and looks neat] -{{user_form.as_p}} {{profile_form.as_p}}<!--provides a clickable button to submit the form. - <inputtype= "Submit"name= "Submit"value= "Register" /> </form>{% endif%}</Body></HTML>
Both the view and the template are good, so let's deal with the URL mappings and connect them all together. Edit the Rango/views.pyand change it to the following:
Rango/views.py:
Urlpatterns = Patterns ("', the URL (r'^$', Views.index, Name='Index'), url (r'^about/$', Views.about, Name=' About'), url (r'^category/(? p<category_name_url>\w+) $', Views.category, Name='category'), url (r'^add_category/$', Views.add_category, Name='add_category'), url (r'^category/(? p<category_name_url>\w+)/add_page/$', Views.add_page, Name='Add_page'), url (r'^register/$', Views.register, Name='Register'),#What's new here!)
Finally, we want to modify the homepage template (templates/rango/index.html), the "registration" link to the first page. Please add the following before the </body> label:
Templates/rango/index.html:
<href= "/rango/register/"> register </a>< />
Let's take a look at the work, and in the browser type: Http://127.0.0.1:8000/rango/register, you'll see a page like this:
650) this.width=650; "title=" 1 "style=" border-left-0px; border-right-width:0px; Background-image:none; border-bottom-width:0px; padding-top:0px; padding-left:0px; padding-right:0px; border-top-width:0px "border=" 0 "alt=" 1 "src=" http://s3.51cto.com/wyfs02/M00/6C/3B/wKioL1VB5oCB_ A4gaaeuz7wnjbq869.jpg "width=" 692 "height=" 385 "/>
"Not to be Continued"
This article copyright to willing to learn all, welcome reprint, reproduced please indicate the author and source. Thank you!
Willing
Starter: Willing to learn Yuan @ Blog Park
Actual combat Django:rango Part4