Sunday, November 15, 2020

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

On 15 Nov 2020, at 23:27, Apolo Machine <apolomachine@gmail.com> wrote:

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?


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')

No comments:

Post a Comment