Trying to filter out choices in a form based on the logged in user.

77 views
Skip to first unread message

GavinB841

unread,
Feb 9, 2019, 8:23:34 AM2/9/19
to Django users
Hi all,

If anyone could help or point me in the direction of some documentation for the below problem I am having I would really appreciate it.

Just to explain quickly:
  1. I have a model called "Team" which contains a foreign key to another model called "Club"
  2. The "Club" model contains a foreign key to the "User" model.
  3. I have a form for the "Team" model which takes in "club_id", currently it lists all the club_id for all users and I want to restrict this.
  4. I am looking to find out how I can auto-populate this field "club_id" based on the logged in user, which I will then hide in the form. 
Below is my forms.py

class ClubInfoForm(forms.ModelForm):
club_address2 = forms.CharField(required=False)
club_address3 = forms.CharField(required=False)

class Meta():
model = ClubInfo
fields = ('club_name', 'club_logo', 'club_address1', 'club_address2',
'club_address3', 'club_town', 'club_county', 'club_country',)

def clean_club_name(self):
club_name = self.cleaned_data['club_name']
if ClubInfo.objects.filter(club_name=club_name).exists():
raise ValidationError(_("Club already exists"))
return club_name


class TeamForm(forms.ModelForm):

class Meta():
model = Team
fields = ('club_id', 'team_name', 'manager_name')

def __init__(self, *args, **kwargs):
super(TeamForm, self).__init__(*args, **kwargs)


models.py

class ClubInfo(models.Model):

user = models.OneToOneField(User, on_delete=models.CASCADE)
club_name = models.CharField(max_length=50, default='', unique=True)
club_logo = models.ImageField(upload_to='profile_pics', blank=True)
club_address1 = models.CharField(max_length=30)
club_address2 = models.CharField(max_length=30, default='')
club_address3 = models.CharField(max_length=30, default='')
club_town = models.CharField(max_length=30)
club_county = models.CharField(max_length=30)
club_country = models.CharField(max_length=30)
created_date = models.DateTimeField(default=timezone.now)

def __str__(self):
return self.club_name

class Team(models.Model):

club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE)
team_name = models.CharField(max_length=30)
manager_name = models.CharField(max_length=20)


def __str__(self):
return self.team_name

Ricardo Cataldi

unread,
Feb 9, 2019, 8:40:09 AM2/9/19
to django...@googlegroups.com

Hello there Galvin,

 

You can create properties on the users and filter the queryset conditioning to the user. It depends on how many categories of user you have and how these users are supposed to be filtered by those teams.

 

For example, if you have a spatial selection based on user location, you create a property called ‘location_filter’ and set the separation rule on this property, like:

 

@property

def location_filter(self):

                location = self.location

                filter_rule = 5miles

                return [self.location - filter_rule, self.location + filter_rule]

 

and in your form you set a init argument to query those filter rules, in the fashion that you want:

 

def __init__(self, *args, **kwargs):

                user = kwargs.pop(‘user’, None)

                self.fields[‘club_id’].queryset = Club.objects.filter(place__lte=user.location_filter[1], place__gte=user.location_filter[0])

 

I have not tested this solution, but with some minor code changes it should work like a charm in filtering the club queryset.

Séanadh Ríomhphoist/

Email Disclaimer

Tá an ríomhphost seo agus aon chomhad a sheoltar leis faoi rún agus is lena úsáid ag an seolaí agus sin amháin é. Is féidir tuilleadh a léamh anseo. 

This e-mail and any files transmitted with it are confidential and are intended solely for use by the addressee. Read more here. 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8188ff6e-bf56-4010-9caf-90d8a294a187%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

GavinB841

unread,
Feb 9, 2019, 10:15:23 AM2/9/19
to Django users
Hi Ricardo,

Really appreciate your reply, I am struggling to understand where I would create this property as I am quite new to Django and haven't worked with these before.

Is it included in the model/view/form and under which model for the club, user or team. 

Thanks for your help.

Gavin 

Ricardo Cataldi

unread,
Feb 9, 2019, 3:43:12 PM2/9/19
to django...@googlegroups.com
You van create this property on your model, andam the init would bem applied to your form

Reply all
Reply to author
Forward
0 new messages