63 lines
No EOL
2.4 KiB
Python
63 lines
No EOL
2.4 KiB
Python
from django import forms
|
|
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
|
|
from .models import CustomUser, FriendCode
|
|
from allauth.account.forms import SignupForm
|
|
|
|
class CustomUserCreationForm(UserCreationForm):
|
|
|
|
class Meta(UserCreationForm.Meta):
|
|
model = CustomUser
|
|
fields = ('email',)
|
|
|
|
class CustomUserChangeForm(UserChangeForm):
|
|
|
|
class Meta:
|
|
model = CustomUser
|
|
fields = ('email',)
|
|
|
|
class FriendCodeForm(forms.ModelForm):
|
|
class Meta:
|
|
model = FriendCode
|
|
fields = ["friend_code"]
|
|
|
|
def clean_friend_code(self):
|
|
friend_code = self.cleaned_data.get("friend_code", "").strip()
|
|
# Remove any dashes from the input for validation.
|
|
friend_code_clean = friend_code.replace("-", "")
|
|
if len(friend_code_clean) != 16 or not friend_code_clean.isdigit():
|
|
raise forms.ValidationError("Friend code must be exactly 16 digits long.")
|
|
# Format the friend code as: XXXX-XXXX-XXXX-XXXX.
|
|
friend_code_formatted = f"{friend_code_clean[:4]}-{friend_code_clean[4:8]}-{friend_code_clean[8:12]}-{friend_code_clean[12:16]}"
|
|
return friend_code_formatted
|
|
|
|
class CustomSignupForm(SignupForm):
|
|
friend_code = forms.CharField(
|
|
max_length=19,
|
|
required=True,
|
|
label="Friend Code",
|
|
help_text="Enter your friend code in the format XXXX-XXXX-XXXX-XXXX.",
|
|
widget=forms.TextInput(attrs={'placeholder': 'XXXX-XXXX-XXXX-XXXX'})
|
|
)
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
# Remove the username field completely.
|
|
if "username" in self.fields:
|
|
del self.fields["username"]
|
|
|
|
def clean_friend_code(self):
|
|
friend_code = self.cleaned_data.get("friend_code", "").strip().replace("-", "")
|
|
if len(friend_code) != 16 or not friend_code.isdigit():
|
|
raise forms.ValidationError("Friend code must be exactly 16 digits long.")
|
|
formatted = f"{friend_code[:4]}-{friend_code[4:8]}-{friend_code[8:12]}-{friend_code[12:16]}"
|
|
return formatted
|
|
|
|
def save(self, request):
|
|
# First, complete the normal signup process.
|
|
user = super().save(request)
|
|
# Create the associated FriendCode record.
|
|
FriendCode.objects.create(
|
|
friend_code=self.cleaned_data["friend_code"],
|
|
user=user
|
|
)
|
|
return user |