Sunday, November 15, 2020

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

Thanks a lot! that totally makes sense and works!

El dom., 15 nov. 2020 a las 11:07, David Nugent (<deeprave@gmail.com>) escribió:
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')



--
::Apolo::

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CALOuZTAa%2Bcm7sQ%3D6wZvw5ymG7yhHKh3DOiOaV93BSqHWz7pR4Q%40mail.gmail.com.

No comments:

Post a Comment