Django ForeignKey limit_choices_to a different ForeignKey id

后端 未结 3 1690
囚心锁ツ
囚心锁ツ 2020-12-15 08:58

I\'m trying to limit Django Admin choices of a ForeignKey using limit_choices_to, but I can\'t figure out how to do it properly.

This code does what I want if the ca

3条回答
  •  感情败类
    2020-12-15 09:54

    I had the same question and your self-answer helped me get started. But I also found another post (question-12399803) that completed the answer, that is, how to filter when creating a new entry.

    In views.py

    form = CustomerForm(groupid=request.user.groups.first().id)
    

    In forms.py

    def __init__(self, *args, **kwargs):
        if 'groupid' in kwargs:
            groupid = kwargs.pop('groupid')
        else:
            groupid = None
        super(CustomerForm, self).__init__(*args, **kwargs)
        if not groupid:
            groupid = self.instance.group.id
        self.fields['address'].queryset = Address.objects.filter(group_id=groupid)
    

    So, whether adding a new customer or updating an existing customer, I can click on a link to go add a new address that will be assigned to that customer.

    This is my first answer on StackOverflow. I hope it helps.

提交回复
热议问题