cqtu/contest/forms.py

159 lines
5.3 KiB
Python

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.utils import timezone
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout
from django.urls import reverse
from .models import User, Reference, QSO, ShadowCall, EntryCategory, Contest
from .validators import CallUsernameValidator, CallLogValidator
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ("username",)
username = forms.CharField(max_length=50, validators=[CallUsernameValidator()])
class UpdateRefForm(forms.Form):
existingRef = forms.ModelChoiceField(label="Existing Reference", queryset=Reference.objects.all(), help_text="If reference already exists, select it here.", required=False)
newRefName = forms.CharField(max_length=50, label="New Reference", help_text="Enter name of new ref, if we should create a new", required=False)
def clean_newRefName(self):
data = self.cleaned_data["newRefName"].strip().upper()
if Reference.objects.filter(name=data).count() > 0:
raise forms.ValidationError("Reference already exists")
return data
def clean(self):
cleaned_data = super(UpdateRefForm, self).clean()
existingRef = cleaned_data.get("existingRef")
newRefName = cleaned_data.get("newRefName")
if existingRef and newRefName:
raise forms.ValidationError("Select an existing ref or create a new one, not both!")
if not existingRef and not newRefName:
raise forms.ValidationError("Select either an existing ref or create a new one!")
class UpdateCategoryForm(forms.Form):
entry = forms.ModelChoiceField(label="Entry category", queryset=EntryCategory.objects.all())
def __init__(self, *args, **kwargs):
super(UpdateCategoryForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = "form-inline "
self.helper.form_style = 'inline'
self.helper.field_template = "bootstrap3/layout/inline_field.html"
self.helper.action = reverse("profile")
self.helper.add_input(Submit('submit', 'Set category'))
self.helper.layout = Layout('entry')
def clean(self):
contest = Contest.objects.get(id=1)
if contest.deadline < timezone.now():
raise forms.ValidationError("The deadline for setting your contest category has passed")
class QSOForm(forms.ModelForm):
class Meta:
model = QSO
fields = ["ownNo", "band", "call", "reportTX", "reportRX", "refStr", "otherNo", "remarks"]
def __init__(self, user, *args, **kwargs):
super(QSOForm, self).__init__(*args, **kwargs)
self.user = user
self.helper = FormHelper()
self.helper.form_id = "qso-log-form"
#self.helper.form_class = "form-inline "
#self.helper.form_class = "form-horizontal"
#self.helper.form_style = 'inline'
#self.helper.field_template = "bootstrap3/layout/inline_field.html"
self.helper.action = reverse("contest:log")
self.helper.add_input(Submit('submit', 'Log'))
#self.helper.layout = Layout(
# #*(QSOForm.Meta.fields + [ButtonHolder(Submit('submit', 'Submit', css_class='button white'))]))
# *(QSOForm.Meta.fields + [FormActions(Submit('submit', 'Log!'))]))
def clean_call(self):
data = self.cleaned_data["call"].upper().strip()
if Reference.objects.filter(name=data).count() > 0:
raise forms.ValidationError("Reference already exists")
try:
CallLogValidator()(data)
except forms.ValidationError:
raise forms.ValidationError("Enter a valid callsign (1-2 chars, a number, 1-4 chars, maybe a /[A-Z])")
if data == self.user.username:
raise forms.ValidationError("You cannot log QSOs with yourself")
return data
def clean_ownNo(self):
data = self.cleaned_data["ownNo"]
if data < 1 or data > 100000:
raise forms.ValidationError("Number has to be in range of [1, 1000000]")
try:
QSO.objects.get(owner=self.user.id, ownNo=data)
raise forms.ValidationError("You already logged a QSO with the number %s" % data)
except QSO.DoesNotExist:
return data
def clean_otherNo(self):
data = self.cleaned_data["otherNo"]
if not data:
# empty value
return None
if data < 1 or data > 100000:
raise forms.ValidationError("Number has to be in range of [1, 1000000]")
return data
def clean_refStr(self):
return self.cleaned_data["refStr"].upper()
def clean(self):
cleaned_data = super(QSOForm, self).clean()
band = cleaned_data.get("band")
if band.contest.deadline < timezone.now():
raise forms.ValidationError("The deadline for logging and editing QSOs has passed")
class QSOFormWithTime(QSOForm):
class Meta:
model = QSO
fields = ["time", "ownNo", "band", "call", "reportTX", "reportRX", "otherNo", "refStr", "remarks"]
class ShadowCallAddForm(forms.ModelForm):
class Meta:
model = ShadowCall
fields = ['username']
def __init__(self, *args, **kwargs):
super(ShadowCallAddForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = "form-inline "
self.helper.form_style = 'inline'
self.helper.field_template = "bootstrap3/layout/inline_field.html"
self.helper.action = reverse("contest:registerRefs")
self.helper.add_input(Submit('submit', 'Add shadow'))
self.helper.layout = Layout('username')
def clean_username(self):
data = self.cleaned_data["username"]
if User.objects.filter(username=data).count() > 0:
raise forms.ValidationError("A user with this call already exists, this is not a shadow!")
return data