Steve Smith
Steve Smith

Reputation: 1089

Django Many To Many Field Causing Me Grief

I am trying to list players who may belong to multiple teams. I set up my code for users to be able to select multiple teams, and that is working fine. However, now that I have done this, the automatic population of fields is no longer working. It worked fine with a foreign key but once I changed the model field reference to ManyToManyField, the auto population of the dropdown fields I set up no longer works. Please help! I'm a newbie, so if there's a better way to go about what I'm trying to accomplish I'm open to other thoughts. Here is my code:

Models.Py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    users = User.objects.select_related('userprofile').all()        
    team = models.ManyToManyField(Team,related_name='teamprofile')

    def __str__(self):
       return self.user.get_full_name()

class Team(models.Model):
    team = models.CharField(max_length=264,unique=True)
    user = models.ForeignKey(User,null=True,on_delete=models.CASCADE)

    class Meta:
        ordering = ["team"]

    def __str__(self):
       return self.team

Views.Py

def view_byteam(request):
    form = ViewByTeam(request.user, request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            department = form.cleaned_data['dropdown']
            return HttpResponseRedirect(team.get_absolute_url1())
    return render(request,'/view_byteam.html',{'form':form})

Forms.py

class ViewByTeam(forms.Form):

    dropdown = forms.ModelChoiceField(queryset=Team.objects.none())

    def __init__(self, user,*args, **kwargs):
    super(ViewByTeam, self).__init__(*args, **kwargs)
    qs = Team.objects.filter(team=user.userprofile.team)
        self.fields['dropdown'].queryset = qs
        self.fields['dropdown'].widget.attrs['class'] = 'choices1'
        self.fields['dropdown'].empty_label = ''

The above works with a foreignkey field reference on team but when I change it to ManyToMany, the field is now blank. I've already tried to change user.userprofile.team to user.userprofile.team.all() and to user.userprofile.team.all and continue to receive error messages that I can't decipher. The code above returns nothing, I still get the form but the dropdown is blank. It's as if the code can no longer decipher the team of the user from their profile. I've checked in other places and the system is taking the team value, but not able to use it in this section of my code for some reason. I'm trying to get it to return multiple values, minimally at least one but it should be able to return multiple values. Any thoughts are appreciated.

Upvotes: 0

Views: 77

Answers (2)

zaidfazil
zaidfazil

Reputation: 9235

Change this line in form.init() method,

qs = Team.objects.filter(team__in=user.userprofile.team.all())

After you've changed the field to ManyToMany relation, the attribute is a list of objects. Change your filter accordingly.

Upvotes: 1

Steve Smith
Steve Smith

Reputation: 1089

Answer to the original question of what to change after changing field from foreignkey to manytomany was to update my filter from qs = Team.objects.filter(user.userprofile.team) to qs = Team.objects.filter(team__in=user.userprofile.team.all()).

Upvotes: 0

Related Questions