2022-07-21 12:45:44 +00:00
|
|
|
from django import forms
|
|
|
|
from django.contrib.auth.forms import UserCreationForm
|
2023-01-11 21:04:54 +00:00
|
|
|
from django.core.exceptions import FieldDoesNotExist
|
2022-07-21 12:45:44 +00:00
|
|
|
|
|
|
|
from .models import User
|
|
|
|
|
2023-01-11 21:04:54 +00:00
|
|
|
# from django.forms import ModelForm
|
|
|
|
|
|
|
|
|
2022-07-21 12:45:44 +00:00
|
|
|
# Create your forms here.
|
2023-01-11 21:04:54 +00:00
|
|
|
class RestrictedFormMixin:
|
|
|
|
"""
|
|
|
|
This mixin is used to restrict the queryset of a form to the current user.
|
|
|
|
The request object is passed from the view.
|
|
|
|
Fieldargs is used to pass additional arguments to the queryset filter.
|
|
|
|
"""
|
|
|
|
|
|
|
|
fieldargs = {}
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
# self.fieldargs = {}
|
|
|
|
self.request = kwargs.pop("request")
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
for field in self.fields:
|
|
|
|
# Check it's not something like a CharField which has no queryset
|
|
|
|
if not hasattr(self.fields[field], "queryset"):
|
|
|
|
continue
|
|
|
|
|
|
|
|
model = self.fields[field].queryset.model
|
|
|
|
# Check if the model has a user field
|
|
|
|
try:
|
|
|
|
model._meta.get_field("user")
|
|
|
|
# Add the user to the queryset filters
|
|
|
|
self.fields[field].queryset = model.objects.filter(
|
|
|
|
user=self.request.user, **self.fieldargs.get(field, {})
|
|
|
|
)
|
|
|
|
except FieldDoesNotExist:
|
|
|
|
pass
|
2022-07-21 12:45:44 +00:00
|
|
|
|
|
|
|
|
|
|
|
class NewUserForm(UserCreationForm):
|
|
|
|
email = forms.EmailField(required=True)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = User
|
|
|
|
fields = (
|
|
|
|
"username",
|
|
|
|
"email",
|
|
|
|
"first_name",
|
|
|
|
"last_name",
|
|
|
|
"password1",
|
|
|
|
"password2",
|
|
|
|
)
|
|
|
|
|
|
|
|
def save(self, commit=True):
|
|
|
|
user = super(NewUserForm, self).save(commit=False)
|
|
|
|
user.email = self.cleaned_data["email"]
|
|
|
|
if commit:
|
|
|
|
user.save()
|
|
|
|
return user
|
|
|
|
|
|
|
|
|
|
|
|
class CustomUserCreationForm(UserCreationForm):
|
|
|
|
class Meta:
|
|
|
|
model = User
|
|
|
|
fields = "__all__"
|