Select from the dropdown the object car that has the field is_active

41 views
Skip to first unread message

Apolo Machine

unread,
Nov 15, 2020, 7:27:21 AM11/15/20
to Django users

hello, i'm a newbie using django and i have a problem that cannot solve.
In my createview i need to select from the dropdown the object car that has the field is_active = true,
how can i acomplish that?

class Car(models.Model):
    brand = models.charfield(...)
    is_active= models.BooleanField(default=True)

class Service(models.Model):
    car = models.ForeingKey('Car'....)
    name = models.Charfield()

class ServiceCreateView(CreateView):
    model = Service
    form = ServiceForm
    ...
    
If i change the field is_active to false in Car model, should not be shown in the dropdown.
can someone put me in the right direction?

David Nugent

unread,
Nov 15, 2020, 10:23:19 AM11/15/20
to django...@googlegroups.com, Apolo Machine
You didn't include source for ServiceForm - the work to do this will be there.

Assuming it is a ModelForm:

from django import forms
from .models import Service, Car

class ServiceForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['car'].queryset = Car.objects.filter(is_active=True)

class Meta:
model = Service
fields = ('car', 'name')

Apolo Machine

unread,
Nov 15, 2020, 3:41:09 PM11/15/20
to David Nugent, django...@googlegroups.com
Thanks a lot! that totally makes sense and works!
--
::Apolo::
Reply all
Reply to author
Forward
0 new messages