pkmntrade.club/accounts/forms.py

61 lines
No EOL
2.3 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 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 CustomUserCreationForm(SignupForm):
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = ['email', 'username', 'friend_code']
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)
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(CustomUserCreationForm, self).save(request)
# Create the associated FriendCode record.
friend_code_pk = FriendCode.objects.create(
friend_code=self.cleaned_data["friend_code"],
user=user
)
user.default_friend_code = friend_code_pk
user.save()
return user