Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

87 rader
2.5 KiB

  1. from api import models
  2. from api.models import LessPassUser
  3. from django import forms
  4. from django.contrib import admin
  5. from django.contrib.auth.models import Group
  6. from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
  7. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  8. from django.db.models import Count
  9. class UserCreationForm(forms.ModelForm):
  10. password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
  11. password2 = forms.CharField(
  12. label="Password confirmation", widget=forms.PasswordInput
  13. )
  14. class Meta:
  15. model = LessPassUser
  16. fields = ("email",)
  17. def clean_password2(self):
  18. password1 = self.cleaned_data.get("password1")
  19. password2 = self.cleaned_data.get("password2")
  20. if password1 and password2 and password1 != password2:
  21. raise forms.ValidationError("Passwords don't match")
  22. return password2
  23. def save(self, commit=True):
  24. user = super(UserCreationForm, self).save(commit=False)
  25. user.set_password(self.cleaned_data["password1"])
  26. if commit:
  27. user.save()
  28. return user
  29. class UserChangeForm(forms.ModelForm):
  30. password = ReadOnlyPasswordHashField()
  31. class Meta:
  32. model = LessPassUser
  33. fields = ("email", "password", "is_active", "is_admin")
  34. def clean_password(self):
  35. return self.initial["password"]
  36. class LessPassUserAdmin(BaseUserAdmin):
  37. form = UserChangeForm
  38. add_form = UserCreationForm
  39. list_display = ("email", "is_admin", "column_passwords_count")
  40. list_filter = ("is_admin", "is_active")
  41. fieldsets = (
  42. (None, {"fields": ("email", "password")}),
  43. ("Permissions", {"fields": ("is_admin",)}),
  44. )
  45. add_fieldsets = (
  46. (None, {"classes": ("wide",), "fields": ("email", "password1", "password2")}),
  47. )
  48. search_fields = ("email",)
  49. ordering = ("email",)
  50. filter_horizontal = ()
  51. def get_queryset(self, request):
  52. return models.LessPassUser.objects.annotate(passwords_count=Count("passwords"))
  53. def column_passwords_count(self, instance):
  54. return instance.passwords_count
  55. column_passwords_count.short_description = "Password count"
  56. column_passwords_count.admin_order_field = "passwords_count"
  57. class PasswordAdmin(admin.ModelAdmin):
  58. list_display = (
  59. "id",
  60. "user",
  61. )
  62. search_fields = ("user__email",)
  63. ordering = ("user",)
  64. admin.site.register(models.Password, PasswordAdmin)
  65. admin.site.register(LessPassUser, LessPassUserAdmin)
  66. admin.site.unregister(Group)