[Django]-Django 3 – Making Model's FK Dropdown Display Current User's Data Only

4👍

You’ll need to customize your form a bit, in order to modify the queryset for that particular field. We also need to pass a user from the view:

forms.py

class TicketForm(ModelForm):
    class Meta:
        model = Ticket
        fields = ['number', 'customer', 'date_created', 'work_description', 'mechanics', 'status']

    def __init__(self, user=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if user:
            self.fields['customer'].queryset = Customer.objects.filter(shopowner=user)

views.py

def createTickets(request):
    form = TicketForm(user=request.user)
    # ...

Exactly how you define the queryset is going to depend on how you’ve defined the relationship between Customer and Shopowner, but this should give you the right approach.

Leave a comment