Answer the question
In order to leave comments, you need to log in
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='Кошелек')
...
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)
...
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question