0

Just quickly to summarize I have an app, which allows clubs to sign up and carry out different tasks. One of the features is a scheduling / rosters. Currently I have a form to add times to the roster. The club pages work off a session key based on the initially selected club.

My form consists of: club_id - which I have hidden and initialized based on the logged in user. pitch_id - which is currently displaying all pitches associated to all clubs but I need this to only show pitches based on the foreign key for the club_id

Would appreciate any help.

form.py

from django import forms
from clubkit.roster.models import RosterId
import datetime
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _


class RosterForm(forms.ModelForm):

class Meta():
    model = RosterId
    fields = ('club_id', 'pitch_id', 'team_id', 'date',
              'start_time', 'finish_time', 'reoccuring_event',)
    widgets = {
        'date': forms.DateInput(attrs={'id': 'datepicker'})
    }

    def clean_date(self):
        date = self.clean_date['date']
        if date < datetime.date.today():
            raise ValidationError(_('Date cannot be in the past.'))
        return date

def __init__(self, *args, **kwargs):
    super(RosterForm, self).__init__(*args, **kwargs)
    self.fields['club_id'].widget = forms.HiddenInput()

models.py for pitch

class Pitch(models.Model):
club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE, related_name="pitches")
pitch_name = models.CharField(max_length=30)
PITCH_SIZES = (
    ('S', 'Small'),
    ('M', 'Medium'),
    ('L', 'Large'),
)
PITCH_TYPE = (
    ('1', 'Outdoor'),
    ('2', 'Indoor'),
)
pitch_size = models.CharField(max_length=1, choices=PITCH_SIZES)
pitch_type = models.CharField(max_length=1, choices=PITCH_TYPE)
open_time = models.TimeField(default='09:00')
close_time = models.TimeField(default='22:00')
RENT_TYPE = (
    ('0', 'Not Available To Rent'),
    ('1', 'Available To Rent'),
)
rental = models.CharField(max_length=1, choices=RENT_TYPE)
rental_price = models.DecimalField(default=0.00, max_digits=6, decimal_places=2)
max_people = models.IntegerField(null=True)

def __str__(self):
    return self.pitch_name

models.py for roster

from django.db import models
from clubkit.clubs.models import ClubInfo, Pitch, Team


# Model to store roster information
class RosterId(models.Model):
club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE)
pitch_id = models.ForeignKey(Pitch, on_delete=models.CASCADE)
team_id = models.ForeignKey(Team, on_delete=models.CASCADE)
date = models.DateField(max_length=8)
start_time = models.TimeField(default='')
finish_time = models.TimeField(default='')
reoccuring_event = models.BooleanField(default=False)

views.py

class ClubRoster(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'roster.html'

# Get method to retrieve current roster information and form
def get(self, request):
    if request.user.is_authenticated:
        club_pk = request.session.get('pk')
        club_info = ClubInfo.objects.filter(user=request.user).first()
        reoccuring_event = RosterId.objects.filter(reoccuring_event=True, club_id=club_pk)
        inital_data = {
            'club_id': club_info,
        }
        form = RosterForm(initial=inital_data)
        roster = RosterId.objects.filter(club_id=club_pk)
        return Response({'form': form,
                         'roster': roster,
                         'club_pk': club_pk,
                         'reoccuring_event': reoccuring_event
                         })
  • Possible duplicate of [How do I filter ForeignKey choices in a Django ModelForm?](https://stackoverflow.com/questions/291945/how-do-i-filter-foreignkey-choices-in-a-django-modelform) – djvg Apr 08 '19 at 11:29

1 Answers1

0

Sounds like you're looking for some manipulation of the form field query. Maybe this answer will provide further help.

The result could look like this.


from django import forms
from clubkit.roster.models import RosterId, Pitch
import datetime
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _


class RosterForm(forms.ModelForm):

    class Meta():
        model = RosterId
        fields = ('club_id', 'pitch_id', 'team_id', 'date',
                  'start_time', 'finish_time', 'reoccuring_event',)
        widgets = {
            'date': forms.DateInput(attrs={'id': 'datepicker'})
        }

    def clean_date(self):
        date = self.clean_date['date']
        if date < datetime.date.today():
            raise ValidationError(_('Date cannot be in the past.'))
        return date

    def __init__(self, *args, **kwargs):
        super(RosterForm, self).__init__(*args, **kwargs)
        self.fields['club_id'].widget = forms.HiddenInput()

        instance = kwargs.get('instance', None)
        if instance:
            self.fields['pitch_id'].queryset = Roster.objects.filter(club_id=instance.club_id)

Ah well or adjust instance to your 'initial'.

Bloodmallet
  • 414
  • 4
  • 9