models.py
How to write models.py when I want to use both the mediation model and auth to be added
-----------------------------------------------------------------------------------
The role of auth: use
user=auth.authenticate(username=user,password=pwd)
auth.login(request, user)
is added to the session for users who have been successfully authenticated
-------------------------------------------------------------------------------------
ORM mediation model
Django allows you to specify a mediation model to define many-to -many relationships .
You can put other fields inside the mediation model. The source model's ManyToManyField field will use the through parameter to point to the intermediary model. For the music group example above, the code is as follows:
注意:ManyToMany("Student",through="Course_students")
ForeignKey("xxx")
class student courst id name id name id name 1 s1 1 lcg 1 Go 2 ming 2 Python s_c id student_id course_id 1 1 1 2 2 1 3 2 2 When dealing with similar many-to-many relationships, use the standard ManyToManyField to describe the relationship. However, sometimes you may need to correlate data (score) to the relationship between two models. s_c id student_id course_id score 1 1 1 80 2 2 1 90 3 2 2 100
class Student(models.Model): name=... class Course(models.Model): name=... students =models.ManyToMany( " Student " ,through= " Course_students " ) # through tells ORM to create the third table by myself, I don't have to create it automatically, I also use the students field. class Course_students(models.Model): student_id=mdoels.ForeignKey("Student") course_id=mdoels.ForeignKey("Course") score=models.IntegerFiled()
auth module
Using the auth module needs to be configured in settings.py AUTH_USER_MODEL="app name. table name"
Command to create superuser: python manage.py createsuperuser
models.py
from django.contrib.auth.models import AbstractUser from django.db import models class UserInfo(AbstractUser): """ User Info """ nid = models.AutoField(primary_key=True) telephone = models.CharField(max_length=11, null=True, unique=True) avatar = models.FileField(upload_to='avatars/', default="/avatars/default.png") create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True) blog = models.OneToOneField(to='Blog', to_field='nid', null=True) def __str__(self): return self.username
views.py
from django.contrib import authfrom
django.contrib.auth
import
authenticate, login
1、authenticate()
Provides user authentication, that is, to verify whether the user name and password are correct, generally requires two keyword parameters of username and password
If the authentication information is valid, a User object is returned. authenticate() will set an attribute on the User object to identify which authentication backend authenticated the user, and this information is required in the subsequent login process. When we try to log in to a User object that is directly retrieved from the database without authenticate(), an error will be reported! !
user = authenticate(username='someone',password='somepassword')
2、login(HttpResponse,user)
This function accepts an HttpRequest object, and an authenticated User object
In this case request.user.username request.user.email can be used
This function uses Django's session framework to attach information such as session id to an authenticated user.
from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid login' error message. ...
3. logout() to log out the user
from django.contrib.auth import logout def logout_view(request): logout(request) # Redirect to a success page.
4、
Require:
1 Users can only access certain pages after logging in,
2 If the user visits the page without logging in, jump directly to the login page
3 After the user completes the login in the jumped login interface, the user will automatically access and jump to the previously visited address
method 1:
def my_view(request): if not request.user.is_authenticated(): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
Method 2:
Django has designed a decorator for us in this case: login_requierd()
from django.contrib.auth.decorators import login_required @login_required def my_view(request): ...
If the user is not logged in, it will jump to the django default login URL '/accounts/login/ ' (this value can be modified in the settings file through LOGIN_URL). And pass the absolute path of the current access url (after successful login, it will be redirected to this path).