Using the profile extension user module in Django (based on the Django 1.10 version)

Source: Internet
Author: User
Tags openid

version: Django 1.10.1 (Other versions may have different implementations for a good workaround)

Reference Official document:https://docs.djangoproject.com/en/1.10/topics/auth/customizing/

In the development process, the Django User Management module can bring us a lot of convenience, but the Django Users module provides too few fields, so the extension of the user module is necessary, the following combination of my own development process, The problems encountered when using profile to extend the user module and the methods to be resolved are documented.

Let's take a look at the first code I developed based on the official documentation:

admin.py

From Django.contrib import adminfrom django.contrib.auth.models import userfrom django.contrib.auth.admin Import Useradmin as Baseuseradminfrom models import *class accountinline (admin. Stackedinline):    model = account    Can_delete = False    verbose_name_plural = ' account '    class Useradmin ( Baseuseradmin):    inlines = (accountinline,) admin.site.unregister (user) Admin.site.register (user, useradmin)

model.py:

From __future__ import unicode_literalsfrom mysite import settingsfrom django.db import Modelsfrom Django.contrib.auth.models Import userfrom django.db.models.signals import Post_saveclass account (models. Model): "" "Registered Users" "" Sex_choices = {1: ' Boy ', 2: ' Girl ',} user = models. Onetoonefield (User, On_delete=models. CASCADE) Sex = models. Smallintegerfield (Default=1, Choices=sex_choices.items ()) birth = models. Datefield (Blank=true, null=true) Age = models. Smallintegerfield (blank=true,null=true) Contact_number = models. Charfield (max_length=128, Blank=true, null=true) Personalized_signature = models. Charfield (max_length=128, Blank=true, null=true) picture = models. ImageField (upload_to= "image/", blank=true,null=true) OpenID = models.        Charfield (max_length=128, Blank=true, null=true) def __unicode__ (self): return self.user.username Class meta:db_table = ' account ' def create_user_profile (sender, INstance, created, **kwargs): If Created:profile = account () Profile.user = Instance Profile.save ( ) Post_save.connect (Create_user_profile, Sender=user)

settings.py:

Installed_apps = [    ' django.contrib.admin ',    ' Django.contrib.auth ',    ' django.contrib.contenttypes ',    ' django.contrib.sessions ',    ' django.contrib.messages ',    ' django.contrib.staticfiles ',    ' rest_ Framework ',    ' Blog ')
Auth_profile_module = ' Blog.account '

This is a reference to the official documentation: It is good to have your own model with the user module for one-to-two foreign key mapping.

We can create the user through the Admin page, we can see that our account model is well embedded in the user module, then we can expand the field of the user module.

But at this point, when you save, there is a problem, see:

This question tells me (just my understanding, if there is a mistake to ask for a message), when Django creates a user in the Users table, when the second instance (account) is created by UserProfile, it executes two times when the save operation is executed, This causes the above user_id to already be unable to complete the operation, this is because: the above model calls Post_save two times (Django own save once, and then through the signal post_save once, Causes the second call to save to find that the same primary key ID already exists)

So what we need to do is rewrite the save in the model.py file, and rewrite the model.py file as:

Class account (models. Model): "" "Registered Users" "" Sex_choices = {1: ' Boy ', 2: ' Girl ',} user = models. Onetoonefield (User, On_delete=models. CASCADE) Sex = models. Smallintegerfield (Default=1, Choices=sex_choices.items ()) birth = models. Datefield (Blank=true, null=true) Age = models. Smallintegerfield (blank=true,null=true) Contact_number = models. Charfield (max_length=128, Blank=true, null=true) Personalized_signature = models. Charfield (max_length=128, Blank=true, null=true) picture = models. ImageField (upload_to= "image/", blank=true,null=true) OpenID = models.        Charfield (max_length=128, Blank=true, null=true) def __unicode__ (self): return self.user.username                Class meta:db_table = ' account ' Def-save (self, *args, **kwargs): If not self.pk:try:                p = Account.objects.get (user=self.user) self.pk = p.pk except account.doesnotexist:Pass Super (account, self). Save (*args, **kwargs) def create_user_profile (sender, instance, created, **kwargs): if Created:profile = account () Profile.user = Instance Profile.save () Post_save.connect (Create_u Ser_profile, Sender=user)

This will detect and then save the primary key PK when the save is created.

Because I used the django-rest-framework when I was developing it, I have a serializer serialized file, which is given here:

serializers.py:

Class Userserializer (serializers. Modelserializer):    class Meta:        model = User Fields        = ("id", "username", "password", "email", "Last_login", " Date_joined ") class Accountserializer (serializers. Modelserializer):    class Meta:        model = Account fields        = ("user_id", "User", "Sex", "age", "Birth", "picture", "Contact_number", "Personalized_signature", "OpenID")

  

Using the profile extension user module in Django (based on the Django 1.10 version)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.