V
V
Vic Shostak2017-09-10 00:11:10
Django
Vic Shostak, 2017-09-10 00:11:10

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)

I connect it to another model:
# ./visa/models.py
class TouristVisaSupport(models.Model):
    citizenship = models.ForeignKey(Citizenship, on_delete=None)
...

Which has this view:
# ./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})

The form widget for this field:
# ./visa/forms.py
class TouristVisaSupportForm(forms.ModelForm):
    class Meta:
        model = TouristVisaSupport
        widgets = {
            'citizenship': forms.Select(
                attrs={
                    'class': 'citizenship-select',
                },
            ),
...

In the template I output, as usual:
<!-- ./templates/visa/index.html -->
{{ form.as_p }}
...

I would like to immediately filter the values ​​from the ForeignKey field citizenshipin the view, for example, by the value typefrom the CitizenshipInvitationPrice. That is, of all the values, only the one that satisfies the filter condition will get into the select.
Tell me, please, how can this be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vic Shostak, 2017-09-10
@vikkyshostak

Figured it out myself.
All we had to do was to redefine this field in the + view annotateso 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 question

Ask a Question

731 491 924 answers to any question