Issue
I have two models, Group, and List Item. List Items belong inside Groups:
class List_Item(models.Model):
name = models.CharField("List Item Name", max_length=200, unique = True)
group = models.ForeignKey(Group, verbose_name="Group")
creation_date = models.DateTimeField("Creation Date", default=datetime.now)
notes = models.TextField("Notes", blank=True)
user = models.ForeignKey(User, editable=False)
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField("Group Name", max_length=200, unique = True)
notes = models.TextField("Notes", blank=True)
user = models.ForeignKey(User, editable=False)
def __unicode__(self):
return self.name
In my forms for List Items, a ModelForm has a dropdown for Groups. Currently, it lists all Groups, regardless of which user a Group belongs to. But I want to only display Groups that belong to the user logged in. How might I do this?
Solution
You would have to override the form field inside the init method. You could pass the logged in user to the form from the view and filter based on it
#form
class ListItemform(forms.ModelForm):
def __init__(self, *args, ** kwargs):
self.user = kwargs.pop('user', None)
super(ListItemform, self).__init__(*args, **kwargs)
self.fields['group'].queryset = Group.objects.filter(user = self.user)
#view
def displayform(request):
user = request.user
form = ListItemForm(user = user)
return ...
Answered By - Raunak Agarwal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.