简体   繁体   中英

How to implement a dependent drop down list with Django CreateView?

I am trying to create a CreateView for one of my models "service". My "service" model has a foreign key to an "asset" model. "asset" model has a foreign key to the current user.

I would like to populate a drop down in "service" CreateView with all the "assets" owned by the current logged in "user".

Service model

class Service(models.Model):
    name = models.CharField(max_length=100)
    category = models.CharField(max_length=100)
    provider = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE)

Asset model

class Asset(models.Model):
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=100)
    suburb = models.CharField(max_length=100)
    postcode = models.CharField(max_length=4)
    state = models.CharField(max_length=3)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

ServiceCreateView in views.py

class ServiceCreateView(LoginRequiredMixin, CreateView):
    model = Service
    fields = ['name', 'category', 'provider', 'asset']

If I user 'asset' in fields, I get all the assets added to the drop-down list. I need it to be only the assets owned by the current user.

Any help in this much appreciated.

Thank you.

(I am using the Django 2.2)

Modify your ServiceCreateView to use distinct form, specify template and send current user to that form, so it will know for which user it will need to filter asset

views.py:

class ServiceCreateView(LoginRequiredMixin, CreateView):
    form_class = ServiceCreateForm
    template_name = 'service_form.html'

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

Create ModelForm with same fields and model, that will take user instance on init and filter your asset field accordingly.

forms.py:

class ServiceCreateForm(forms.ModelForm):
    class Meta:
        model = Service
        fields = ['name', 'category', 'provider', 'asset']

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)

        self.fields['asset'].queryset = self.fields['asset'].queryset.filter(
            owner=user)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM