使用模型扩展用户的 Django 登录
Django Login with Model Extending User
我创建了一个扩展用户模型的员工模型。当我创建员工时,我也可以在 User.objects 中找到相同的用户,所以我知道它已创建。当我尝试使用该用户的凭据登录时,凭据未通过身份验证(用户名或密码不正确)
class Employee(User):
start_date = models.DateField()
@property
def leave_days_remaining(self):
#to calculate
calculated_days=10
return calculated_days
def trial(request):
emp = Employee.objects.create(username='lll', password='pass',
email="myemail@emails.com", first_name='Mokgadi,
last_name='Rasekgala', start_date=datetime.date.today())
found=User.objects.get(username='lll')
print found.email
print found.username
print found.password #Found exists
return render(request, 'leave/trial.html')
{% if form.errors %}
<p>{{ form.errors }}Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<p>
<label>Username</label>
<input type="text" name="username">
</p>
<p>
<label>Password</label>
<input type="password" name="password">
</p>
<button type="submit">Login</button>
</form>
创建可以登录的用户,密码必须加密。您可以通过两种不同的方式实现这一目标。
首先你可以使用create_user
代替create
:
emp = Employee.objects.create_user(...)
或者您可以将密码设置为散列:
emp = Employee.objects.create(...)
emp.set_password("password")
我创建了一个扩展用户模型的员工模型。当我创建员工时,我也可以在 User.objects 中找到相同的用户,所以我知道它已创建。当我尝试使用该用户的凭据登录时,凭据未通过身份验证(用户名或密码不正确)
class Employee(User):
start_date = models.DateField()
@property
def leave_days_remaining(self):
#to calculate
calculated_days=10
return calculated_days
def trial(request):
emp = Employee.objects.create(username='lll', password='pass',
email="myemail@emails.com", first_name='Mokgadi,
last_name='Rasekgala', start_date=datetime.date.today())
found=User.objects.get(username='lll')
print found.email
print found.username
print found.password #Found exists
return render(request, 'leave/trial.html')
{% if form.errors %}
<p>{{ form.errors }}Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<p>
<label>Username</label>
<input type="text" name="username">
</p>
<p>
<label>Password</label>
<input type="password" name="password">
</p>
<button type="submit">Login</button>
</form>
创建可以登录的用户,密码必须加密。您可以通过两种不同的方式实现这一目标。
首先你可以使用create_user
代替create
:
emp = Employee.objects.create_user(...)
或者您可以将密码设置为散列:
emp = Employee.objects.create(...)
emp.set_password("password")