Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction to Django CMDB system (3) login and logout

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

Introduction to Django CMDB system (3) preface to login and logout

Author: he Quan, github address: https://github.com/hequan2017 QQ Exchange Group: 620176501

Through this tutorial to complete from scratch, you can write a simple CMDB system independently.

At present, the mainstream methods of development are divided into two types: mvc and mvvc. This tutorial is based on mvc, where django is responsible for rendering html. An introductory tutorial on mvvc (front and rear separation) will be introduced later.

Tutorial project address: https://github.com/hequan2017/husky/

Tutorial documentation address: https://github.com/hequan2017/husky/tree/master/doc

Home page

Pycharm: menu bar tools-- > Select run manage.py task

Manage.py@husky > startapp system # create an APP to manage the system

For details, please take a look at the actual page, and the following is just to show the key code.

Husky/urls.pyfrom django.contrib import adminfrom django.urls import pathfrom system.views import indexfrom django.conf.urls import include urlpatterns = [path ('admin/', admin.site.urls), path (', index), path ('index', index, name= "index"), path (' system/', include ('system.urls', namespace='system')), # # urls files introduced into system]

System/__init.py create a new blank file

System/views.py is responsible for logically processing @ login_required (login_url= "/ system/login") def index (request): "Home: param request:: return:"return render (request, 'system/index.html', {}) # render combines a given template and a given context dictionary, and returns a rendered HttpResponse object. Log in to system/modesl.py table structure

Inherit the user table structure and rebuild the user table

Use a Python class to describe the data table, which we call a model. Using this class, you can use a simple

Python code to create, retrieve, update and delete records in the database without writing "one SQL statement after another", which

It is the legendary ORM (Object Relation Mapping).

From django.db import modelsfrom django.contrib.auth.models import AbstractUser class Users (AbstractUser): # AbstractUser rewriting user requires the integration table "" to add fields based on the django table. If you need to call user, please use this table "position = models.CharField (max_length=64, verbose_name=' position information', blank=True, null=True) avatar = models.CharField (max_length=256, verbose_name=' avatar', blank=True) Null=True) mobile = models.CharField (max_length=11, verbose_name=' mobile', blank=True, null=True) class Meta: db_table = 'users' verbose_name=' user information' verbose_name_plural = verbose_name def _ str__ (self): return self.username

Because you have changed the default user table, you need to delete the library first. And then rebuild.

Drop database husky;create database husky

Pycharm: menu bar tools-- > Select run manage.py task

Makemigrations generates data files

Migrate generates the table structure according to the file

Createsuperuser

Settings.py adds system configuration import sysINSTALLED_APPS = [# enter the app created here, with the structure as follows A project can have multiple APP "system", 'bootstrap3'] AUTH_USER_MODEL =' system.users'AUTHENTICATION_BACKENDS = ('system.views.CustomBackend',) # # re-login authentication Adding the mailbox name can also be used to login SESSION_ENGINE = 'django.contrib.sessions.backends.db'SESSION_COOKIE_SAMESITE =' Lax'CSRF_COOKIE_SAMESITE = 'Lax'SESSION_COOKIE_AGE = 432000LOGIN_URL =' / auth/login'LANGUAGE_CODE = 'zh-Hans'TIME_ZONE =' Asia/Shanghai'USE_I18N = TrueUSE_L10N = FalseUSE_TZ = TrueDATETIME_FORMAT = 'Y-m-d H:i:s'DATE_FORMAT =' Y-m-d'# loggingLOGGING = {'version': 1 'disable_existing_loggers': False,' formatters': {'verbose': {' format':'[argus]% (levelname) s% (asctime) s% (module) s% (message) s'}, 'handlers': {' console': {'level':' DEBUG', 'class':' logging.StreamHandler' 'stream': sys.stdout,' formatter': 'verbose'},},' loggers': {'tasks': {' handlers': ['console'],' level': 'DEBUG',' propagate': True,} 'asset': {' handlers': ['console'],' level': 'DEBUG',' propagate': True,} # form tablePAGINATION_SETTINGS = {'PAGE_RANGE_DISPLAYED': 3,' MARGIN_PAGES_DISPLAYED': 2, 'SHOW_FIRST_PAGE_WHEN_INVALID': True } # form table shows data on one page DISPLAY_PER_PAGE = 15system/views.py

View contains the business logic of the item, which we call the view, and it is also the main content that we write in the development process.

Def login_view (request): "" login: param request: username,password: return: "" error_msg = "username or password is incorrect, or is disabled, please try again" if request.method = "GET": return render (request, 'system/login.html', {' error_msg': error_msg) }) if request.method = = "POST": U = request.POST.get ("username") p = request.POST.get ("password") user = authenticate (request, username=u, password=p) if user is not None: if user.is_active: login (request User) request.session ['is_login'] = True login_ip = request.META [' REMOTE_ADDR'] return redirect ('/ index') # # redirect to a specific URL else: return render (request, 'system/login.html', {' error_msg': error_msg) }) else: return render (request, 'system/login.html', {' error_msg': error_msg,}) class CustomBackend (ModelBackend): "user name / email login: param request:: return:" def authenticate (self, request, username=None, password=None * * kwargs): try: user = Users.objects.get (Q (username=username) | Q (email=username)) if user.check_password (password): return user except Exception as e: logger.error (e) return Nonesystem/urls.py route

It points out the view of what kind of URL call and what to use. In this example, / latest/ URL will call the latest_books () this

A function. In other words, if your domain name is example.com, any "person browsing" URL http://example.com/latest/ will

Will call the latest_books () function to return the result to the customer.

From django.urls import pathfrom system.views import login_viewapp_name = "system" urlpatterns = [path ('login', login_view, name= "login")] templates/system/login.html

To put it simply, it is the html template, which describes the boundary structure of the item. The template engine also comes with some built-in tag.

Login does not inherit base.html, which is a separate page

Welcome to login system {% csrf_token%} login {{error_msg}}

Browsing in IE/360 browser (compatibility mode) is not recommended! Log out system/views.pydef logout_view (request): "" logout:: return: "" logout (request) return redirect ('system:login') system/urls.pypath (' logout', logout_view, name= "logout"), templates/base/_navbar-static-top.html log out to change password system/form.py

User form is a basic function on the web side, and there is a ready-made basic form object in the large and complete Django framework. This paper explains in detail how to use the forms form class in the Django framework of Python.

The function of the Form form automatically generates HTML form elements to check the validity of the form data if the validation is incorrect Redisplay form (data will not be reset) data type conversion (data of character type converted to corresponding Python type) from django import formsclass UserPasswordForm (forms.Form): old_password = forms.CharField (max_length=128, widget=forms.PasswordInput, label=' old password') new_password = forms.CharField (min_length=8, max_length=128, widget=forms.PasswordInput, label=' new password') Help_text= "* your password must contain at least 8 characters, can't be common passwords that everyone likes, can't be all numbers") confirm_password = forms.CharField (min_length=8, max_length=128, widget=forms.PasswordInput, label=' confirm password' Help_text= "* same password") def _ _ init__ (self, * args, * * kwargs): self.instance = kwargs.pop ('instance') super (). _ _ init__ (* args) * * kwargs) def clean_old_password (self): old_password = self.cleaned_data ['old_password'] if not self.instance.check_password (old_password): raise forms.ValidationError (' old password error') return old_password def clean_confirm_password (self): new_password = self.cleaned_data ['new_password'] confirm_ Password = self.cleaned_data ['confirm_password'] if new_password! = confirm_password: raise forms.ValidationError (' new password is inconsistent with confirmation password') return confirm_password def save (self): password = self.cleaned_data ['new_password'] self.instance.set_password (password) self.instance.save () return self.instance

System/views.py

Class UserPasswordUpdateView (LoginRequiredMixin, UpdateView): "" change password: param request::return: "" template_name = 'system/password.html'model = Usersform_class = UserPasswordFormsuccess_url = reverse_lazy (' system:logout') def get_object (self, queryset=None): return self.request.userdef get_context_data (self) * * kwargs): return super () .get_context_data (* * kwargs) def get_success_url (self): return super () .get_success_url () system/urls.pypath ('password_update', UserPasswordUpdateView.as_view (), name= "password_update")

Templates/system/password.html

{% csrf_token%} {% if form.non_field_errors%} {{form.non_field_errors}} {% endif%} {{msg} {% bootstrap_field form.old_password layout= "horizontal"%} {% bootstrap_field form.new_password layout= "horizontal"%} {% bootstrap _ field form.confirm_password layout= "horizontal"%} submit reset background system/admin.py

Background interface configuration file, each APP can create one

From django.contrib import adminfrom system.models import Usersfrom django.contrib.auth.admin import UserAdminclass UsersAdmin (UserAdmin): fieldsets = (None, {'fields': (' username', 'password')}), (' basic information', {'fields': (' first_name', 'last_name',' email')}), ('permission', {'fields': (' is_active', 'is_staff')) 'is_superuser',' groups', 'user_permissions')}), (' login time', {'fields': (' last_login', 'date_joined')}), (' other information', {'fields': (' position', 'avatar',' mobile',)}),) @ classmethod def show_group (self Obj): return [i.name for i in obj.groups.all ()] @ classmethod def show_user_permissions (self, obj): return [i.name for i in obj.user_permissions.all ()] list_display = ('username',' show_group', 'show_user_permissions') list_display_links = (' username',) search_fields = ('username',) filter_horizontal = (' groups') 'user_permissions') admin.site.register (Users, UsersAdmin) admin.site.site_header =' manage backend 'admin.site.site_title = admin.site.site_header other migrations directories store the table structure files automatically generated by django The system will create database tables based on the generated files. If you want to regenerate the database, you need to delete the generated files.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report