Answer the question
In order to leave comments, you need to log in
Django. How to display a ForeignKey field in a template with a certain condition?
hello world!
Can you please tell me how to display the ForeignKey field in a template with a certain condition?
Everything happens in Django 1.11.5.
I have this model:
# ./citizenship/models.py
class Citizenship(models.Model):
name = models.CharField(_('Country name'), max_length=55, unique=True)
is_active = models.BooleanField(default=True)
is_available_for_order = models.BooleanField(default=True)
class CitizenshipInvitationPrice(models.Model):
country = models.ForeignKey(Citizenship, on_delete=models.CASCADE)
type = models.CharField(_('Type'), max_length=25, default=None)
cost = models.IntegerField(_('Cost, RUR'), default=0)
# ./visa/models.py
class TouristVisaSupport(models.Model):
citizenship = models.ForeignKey(Citizenship, on_delete=None)
...
# ./visa/views.py
class TouristVisaSupportView(View):
template_name = 'visa/index.html'
form_class = TouristVisaSupportForm
def get(self, request):
form = self.form_class()
return render(request, self.template_name, {'form': form})
# ./visa/forms.py
class TouristVisaSupportForm(forms.ModelForm):
class Meta:
model = TouristVisaSupport
widgets = {
'citizenship': forms.Select(
attrs={
'class': 'citizenship-select',
},
),
...
<!-- ./templates/visa/index.html -->
{{ form.as_p }}
...
citizenship
in the view, for example, by the value type
from the CitizenshipInvitationPrice
. That is, of all the values, only the one that satisfies the filter condition will get into the select. Answer the question
In order to leave comments, you need to log in
Figured it out myself.
All we had to do was to redefine this field in the + view annotate
so that duplicates were not displayed:
# ./visa/views.py
from django.db.models import Avg
class TouristVisaSupportView(View):
...
def get(self, request):
form = self.form_class()
form.fields['citizenship'].queryset = Citizenship.objects.filter(citizenshipinvitationprice__type=1).annotate(Avg('id'))
return render(request, self.template_name, {'form': form})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question