0

I have a UserProfile model for each user that has a many to many relationship with another Team model to store a list of teams that each member belongs to.

class Team(models.Model):
    team_name = models.CharField(max_length=200)
    organization_name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.organization_name

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True, related_name='profile')
    team = models.ManyToManyField(Team)

I want to create a form which includes a team field that would allow the user to select from a list teams that are filtered to only allow that user to pick teams which they belong to by relation.

I'm confused as to how to approach this, but I'm assuming it would be some sort of filtered queryset?

markwalker_
  • 12,078
  • 7
  • 62
  • 99
Kyle B.
  • 389
  • 1
  • 6
  • 22
  • 1
    Why would you want a form like this it seems to have no use, you are not adding a team because you are just trying to get the teams that they already belong to, so what are you going to do with the teams in this form. –  Aug 16 '15 at 02:43
  • I mean this is fairly easy to do just explain to me why you want to do it. –  Aug 16 '15 at 02:44
  • It is on a form for coaches to add players, but coaches may coach multiple teams so they need to assign the newly created users to the correct team when adding the players – Kyle B. Aug 16 '15 at 18:14

1 Answers1

0

First you will need a model form which is pretty straight forward, then you simply have to query the model you need in your view and create and instance of that in your form via instance=query, or you could do it this way but its a little more difficult but much more specific and can accomplish more specific operations, so I will just link it, How To Exclude A Value In A ModelMultipleChoiceField?.

forms.py

 class GetTeamForm(forms.ModelForm):
    class Meta:
       model = UserProfile
       exclude = ('user',)

views.py

def GetTeamView(request):
    user = request.user #assuming the user is signed in
    get_users_teams = UserProfile.objects.filter(user=user)
    if request.method == 'POST':
      form = Get_Team_Form(request.POST, instance=get_user_teams):
      if form.is_valid():
        form.save()
      else:
        print form.errors()
    else:
      form = GetTeamForm(instance=get_user_teams)
     return render(request, 'htmlfile.html', {'form':form},)
devunt
  • 347
  • 3
  • 9
  • I'm not sure I'm able to use this method because my form isn't a ModelForm since I need to be able to work with multiple models in the form (to create a new user and also to manipulate that users UserProfile setting the team). The form is also entered into a formset so that multiple players can be added – Kyle B. Aug 17 '15 at 05:24