D
D
damir_bashirov2021-10-17 23:07:05
Django
damir_bashirov, 2021-10-17 23:07:05

How to make a dependent selection of two fields in django?

Good afternoon everyone.

How to implement a dropdown list in Django so that the list is filtered by two fields?

Model file:

class Wallet(models.Model):
    title = models.CharField(max_length=150)
    currency = models.ForeignKey(Currency, on_delete=PROTECT, verbose_name='Валюта')
    description = models.TextField(blank=True)
    user = models.ForeignKey(
        get_user_model(),
        on_delete=CASCADE,
    )

typeIncome = 'Доход'
typeExpense = 'Расход'
type_choices = [
        (typeExpense, 'Расход'),
        (typeIncome, 'Доход'),
    ] 

class Category(models.Model):
    title = models.CharField('Название', max_length=150)
    type = models.CharField(max_length=10, choices=type_choices, default=typeExpense)
    user = models.ForeignKey(
        get_user_model(),  
        on_delete=CASCADE,
    )

class Operation(models.Model):
    type = models.CharField('Тип', max_length=10, choices=type_choices, default=typeExpense)
    user = models.ForeignKey(
        get_user_model(),
        on_delete=CASCADE,
    )
    category = ChainedForeignKey(
        'Category', 
        on_delete=PROTECT, 
        chained_field="type",
        chained_model_field="type", 
        show_all=False, 
        auto_choose=True,
        verbose_name='Категория'
    )
    date = models.DateTimeField('Дата', default=datetime.now)
    wallet = models.ForeignKey(Wallet, on_delete=PROTECT, verbose_name='Кошелек')


In the view file, I set the selection by the current user:
...
class OperationCreateView(CreateView):
    model = Operation
    context_object_name = 'operation'
    form_class = OperationCreateForm
    success_url = reverse_lazy('operations')
    template_name_suffix = '_form'

    def get_context_data(self, **kwargs):
        context = super(OperationCreateView, self).get_context_data(**kwargs)
        context['form'].fields['wallet'].queryset = Wallet.objects.filter(user=self.request.user)
        context['form'].fields['category'].queryset = Category.objects.filter(user=self.request.user) 
        return context

    def form_valid(self, form):
        object = form.save(commit=False)
        object.user = self.request.user
        object.save()
        return super(OperationCreateView, self).form_valid(form)
...


The main task is for each user to see only their categories and their wallets. Accordingly, when creating an Operation, the user should see only their categories of the corresponding type (only income or only expenses), for this I use django-smart-selects, but it turns out that in the form for creating an Operation, categories of all users by the selected type are displayed and apply a filter only for current user is not available.

How to differentiate in this case? I'm still just learning django, so I would like to understand in which direction to go.
Thank you.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question