我的models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,null=True)
#first_name = models.CharField(max_length=30)
#last_name = models.CharField(max_length=40)
#username = models.CharField(max_length=30)
buisness_name= models.CharField(max_length=30,blank=True)
我的forms.py
from django import forms
from first_app.models import Person
from django.contrib.auth.models import User
class LoginForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ('username','password')
class PersonForm(forms.ModelForm):
class Meta():
model = Person
fields = ('buisness_name',)
我想创建一个包含字段password
和username
的自定义模型,因此在登录时应该检查此字段中的用户名和密码,在字段中手动输入数据。那我应该如何进行登录验证呢。
答案 0 :(得分:0)
您可以使用django中已存在的模型User
。使用该模型,您可以为其创建表单。
答案 1 :(得分:0)
我希望这会有所帮助。
models.py
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.utils import timezone
class UserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
if not email:
raise ValueError('Users must have an email address')
now = timezone.now()
email = self.normalize_email(email)
user = self.model(
email=email,
is_staff=is_staff,
is_active=True,
is_superuser=is_superuser,
last_login=now,
date_joined=now,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password, **extra_fields):
return self._create_user(email, password, False, False, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
user = self._create_user(email, password, True, True, **extra_fields)
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
name = models.CharField(max_length=254, null=True, blank=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def get_absolute_url(self):
return "/users/%i/" % (self.pk)
views.py
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from django.views.generic.detail import DetailView
from django.http import HttpResponseRedirect, HttpResponse
from .forms import SignUpForm, LoginForm
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
class UserView(DetailView):
template_name = 'users/profile.html'
def get_object(self):
return self.request.user
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(request, email=user.email, password=raw_password)
if user is not None:
login(request, user)
else:
print("user is not authenticated")
return render(request, 'users/login.html')
else:
form = SignUpForm()
return render(request, 'users/signup.html', {'form': form})
@csrf_protect
def user_login(request):
if request.method == 'POST':
# Gather the username and password provided by the user.
# This information is obtained from the login form.
email = request.POST['email']
password = request.POST['password']
user = authenticate(username=email, password=password)
print("auth", str(authenticate(username=email, password=password)))
if user:
# Is the account active? It could have been disabled.
if user.is_active:
login(request, user)
return render(request, 'users/index.html')
else:
return HttpResponse("User is logged in")
else:
# Bad login details were provided. So we can't log the user in.
msg = "Invalid login credentials. Try Again"
contextt = LoginForm(request)
return render(request, 'users/login.html', {'msg': msg})
else:
logout(request)
contextt = LoginForm(request)
return render(request, 'users/login.html', {'form': contextt})
def home(request):
return HttpResponse("Home Page ")
def user_logout(request):
print('Loggin out {}'.format(request.user))
logout(request)
print(request.user)
return user_login(request)
#@login_required(login_url=user_login)
def index(request):
return render(request, 'users/index.html')
forms.py
from django.contrib.auth.forms import UserCreationForm
from django import forms
from .models import User
#class SignUpForm(UserCreationForm):
# class Meta:
# model = User
# fields = ('name', 'email', )
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ('email',)
class LoginForm(forms.Form):
class Meta:
model = User
fields = ('email',)
signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Sign up</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign up</button>
</form>
</body>
</html>
login.html
<form action="" method="post">
{% csrf_token %}
{% if msg %}
<div class="alert alert-danger">
<strong>{{ msg|escape }}</strong>
</div>
{% endif %}
First name: <input type="text" name="email"><br>
Last name: <input type="text" name="password"><br>
<input type="submit" value="Submit">
</form>