The python framework Django real mall project to create a user module

Create a user APP

The entire project will be multiple applications need to be stored in a separate package, so a new apps directory, all sub-management applications.

file

In the apps users wear a package directory application

 python ../../manage.py startapp users

This time for it, we need the newly created application to register django years, but here we have modified the management directory applications, the default of different ways, if it is registered APP in accordance with the previous way will certainly be an error, this time we can first view about the guide path django package, enter the dev file

print(sys.path()) # 输出包的所有搜索路径
['/Users/xxxx/workspace/xxxx/mall/immortal_mall', 
 '/Users/xxxx/workspace/xxxx/mall', 
 '/Users/xxxx/workspace/xxxx/mall/venv/lib/python38.zip', 
 '/Users/xxxx/workspace/xxxx/mall/venv/lib/python3.8', 
 '/Users/xxxx/workspace/xxxx/mall/venv/lib/python3.8/lib-dynload', 
 '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', 
 '/Users/xxxx/workspace/xxxx/mall/venv/lib/python3.8/site-packages', 
 '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend']

The first path is the home directory of our django project,

file

That all packages under his will search your home directory, then you can define a path for the APP

meiduo_mall.apps.users

This time run the program, you can run successfully. But then, this definition of registered APP way too much trouble, if the application is much, each must write it again, it may not be sick. So we have to be simplified. How to simplify, to the search path in the package insert absolute path to the directory apps directly, it can not be django search to begin.

sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))

So finished thing, and then register the APP

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'immortal_mall.apps.users',
    'users'
]

Return to the registration page

Ready to register the template used, placed in a good pre-New templates folder
file

Registration is defined users view class:

class RegisterView(View):
    """用户注册视图类"""

    def get(self, request):
        '''获取注册页面'''
        return render(request, 'register.html')

User-defined routing Registration

# 总路由
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(('users.urls', 'users'), namespace='users'))
]

Here we focus on the draw, the first parameter is a function include Ganso, the first argument did not have to say, is to specify the routing sub-applications, the second argument is app_name, there must be developed app_name, if you do not specify this parameter , written in include('users.urls', namespace='users')a will complain.

Of course, there is a way to specify the file specified in the urls sub-applications in app_name='users'.
Create a new file in the users urls.py application directory, and then writes the routing information

urlpatterns = [
    path('register/', views.RegisterView.as_view(), name='register')  # name添加命名空间
]

Start the application, the browser requests http://127.0.0.1:8989/register/, return to the registration page.

User model class

Django project using the built-in user authentication system, first to find out what are the features.

Django's default user authentication system

django comes with a user authentication system handles user accounts, groups, permissions and cookie-based user sessions, located django.contrib.auth

in the bag.

django auth package is a built-APP, and as admin, can handle authentication and authorization, certification is to verify that a user is not the system of people, decided to authorize an authenticated user can be allowed to do.

Django authentication system provides a user model class User to save user data, User authentication system is the core of the object :

class User(AbstractUser):
    """
    Users within the Django authentication system are represented by this
    model.

    Username and password are required. Other fields are optional.
    """
    class Meta(AbstractUser.Meta):
        swappable = 'AUTH_USER_MODEL'

Userl like nothing, look at parent AbstractUserof things in some fields which define the user, which includes a number of user classes required field username, password, there are other optional fields, is_active, is_staff, etc., on the user authentication the methods AbstractUserof the parent class AbstractBaseUserin

But AbstractUser类in holding the UserManagerinstance is called objects, this class provides a way to create a user, such as:

user = User.objects.create_user(username, email, password, **extra_fields)

Custom User model class

file

This is the user registration information form, there is a phone number field, but Django model is provided in a user does not have this field, we need to define ourselves.

class User(AbstractUser):
    """自定义用户模型类"""
    mobile = models.CharField(max_length=11, unique=True, verbose_name="手机号")

    class Meta:
        db_table = 'tb_user' # 自定义表名
        verbose_name = "用户"  # 站点显示
        verbose_name_plural = verbose_name # 复数显示

User-defined model classes need to inherit AbstractUserthe class, and then specify the newly added fields. After the addition run the project, it will report a error:
file

This is the default authentication django object configuration, we use a custom object, but the object is not assigned to the system,

file

So to re-specify their dev configuration file;

AUTH_USER_MODEL = 'users.User'

Then create a migration file, execute the migration command, creating a table.

✗ python manage.py makemigrations

 python manage.py migrate

Welcome everyone to my blog Chou Chou, there are more details about the test of combat Oh! !

Guess you like

Origin www.cnblogs.com/zyjimmortalp/p/12452635.html