我已经在模型中创建了一个Customer模型,并在admin.py上注册了它。然后我创建了一个登录表单并使用get方法获取字段值。现在我想遍历创建的所有客户对象并找到具有这两个匹配字段的对象。我在views.py中创建了一个登录功能。这是我的模型:Class Customer(models.Model):
FirstName = models.CharField(max_length=100, default="")
LastName = models.CharField(max_length=100, default="")
address = models.CharField(max_length=500, default="")
EmailId = models.CharField(max_length=120, default="")
PhoneNo = models.CharField(max_length=12, default="")
Password = models.CharField(max_length=120, default="")
这是我的功能:def登录(请求):
if request.method=="POST":
FirstName= request.POST.get('FirstName', '')
Password = request.POST.get('Password', '')
for customer in Customer.objects.all():
if FirstName==customer.FirstName and Password==customer.Password:
return redirect ( 'customer-home')
return render(request, 'customer/login.html')
我没有得到想要的结果。
我建议不要使用for循环来检查每个对象,而可以使用Django提供的Queryset检查(https://docs.djangoproject.com/en/3.0/ref/models/querysets/),如下所示
customer = Customer.objects.get(firstname=firstname, password=password)
if customer is not None:
redirect ( 'customer-home')
制作一个具有导入了Django表单的form.py文件,如下所示:>>
forms.py from django.forms import ModelForm from .models import * from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import User from django import forms class CreateUserForm(UserCreationForm): class Meta: model=User fields=['Firstname','Lastname','EmailId','Address',Password','PhoneNo']
然后在视图中添加
from .forms import *
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password =request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/')
else:
messages.info(request, 'Username OR password is incorrect')
return render(request, 'customer/login.html')