Zhaolin Ma
Zhaolin Ma

Reputation: 73

Django CreatView with Foreignkey limit options

In my model I have

Person:
    name
Sneaker:
    owner(FK) = Person.id
    size
    colour
Booking:
    customer(FK) = Person.id
    sneaker(FK) = Sneaker.id
    time
    price

The logic is after a person login, he can start booking service for one of his sneakers. I have no problem setting the customer to request.user. But somehow in create view for booking, one can see all the sneakers record in the database(include his and other customers'), but I want the customer can only select his own sneaker. Can I put a limit on this? My create view is shown as below. Thx!

class Booking_Create_View(CreateView):
    fields = ['sneaker','time','price']
    model = Booking
    def form_valid(self, form):
        form.instance.customer = self.request.user
        return super(Booking_Create_View, self).form_valid(form)
    success_url = reverse_lazy("booking_system:index")

Upvotes: 1

Views: 88

Answers (1)

Ashish Acharya
Ashish Acharya

Reputation: 3399

You will need to create a custom BookingCreateForm that accepts a user kwarg and filters the queryset:

forms.py

class BookingCreateForm(forms.ModelForm):
    class Meta:
        model = Booking
        fields = ['sneaker', 'time', 'price']

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super().__init__(*args, **kwargs)
        self.fields['sneaker'].queryset = Sneaker.objects.filter(owner=user)

views.py

class Booking_Create_View(CreateView):
    form_class = BookingCreateForm

    def form_valid(self, form):
        form.instance.customer = self.request.user
        return super().form_valid(form)

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

    success_url = reverse_lazy("booking_system:index")

Upvotes: 2

Related Questions