/
forms.py
66 lines (52 loc) · 2.39 KB
/
forms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.core.exceptions import ValidationError
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _
# Translators : %(username)s will be replaced by the username_field name
# (default : username, but could be email, or something else)
ERROR_MESSAGE = _(
"Please enter the correct %(username)s and password "
"for a staff account. Note that both fields may be case-sensitive."
)
class AdminAuthenticationForm(AuthenticationForm):
"""
A custom authentication form used in the admin app.
Liberally copied from django.contrib.admin.forms.AdminAuthenticationForm
"""
error_messages = {
'required': _("Please log in again, because your session has expired."),
}
this_is_the_login_form = forms.BooleanField(
widget=forms.HiddenInput,
initial=1,
error_messages=error_messages
)
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
message = ERROR_MESSAGE
if username and password:
self.user_cache = authenticate(username=username, password=password)
if self.user_cache is None:
raise ValidationError(message % {
'username': self.username_field.verbose_name
})
elif not self.user_cache.is_active or not self.user_cache.is_staff:
raise ValidationError(message % {
'username': self.username_field.verbose_name
})
return self.cleaned_data
class Admin2UserCreationForm(UserCreationForm):
pass
class Admin2UserChangeForm(UserChangeForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print(self.fields['password'].help_text)
self.fields['password'].help_text = _("Raw passwords are not stored, so there is no way to see this user's password, but you can change the password using <a href=\"%s\">this form</a>." % self.get_update_password_url())
def get_update_password_url(self):
if self.instance and self.instance.pk:
return reverse_lazy('admin2:password_change', args=[self.instance.pk])
return 'password/'