djangodjango-template-filtersgeneric-foreign-key

Django show extra content in class based view with ForeignKey models


I'm trying to add extra content to Djangos Class-based view to the template

I have some models like this

class District(models.Model):
    district = models.CharField(max_length=255, null=False, unique=False, blank=True)

    def __str__(self):
        return self.district


class Street(models.Model):
    street_name = models.CharField(max_length=255, null=False, unique=False, blank=True)
    district = models.ForeignKey(District, verbose_name=_('district'), on_delete=models.CASCADE, null=True, blank=True)
    zone = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return self.street_name


class Article(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name="author", on_delete=models.SET_NULL)
    timestamp = models.DateTimeField(auto_now_add=True)   
    status = models.CharField(max_length=1, choices=STATUS, default=CREATED)
    comment = models.CharField(max_length=255, null=True, unique=False, blank=True)
    name = models.CharField(max_length=255, null=True, unique=False)
    street = models.ForeignKey(Street, verbose_name=_('street'), on_delete=models.CASCADE, null=True, blank=True)


class ArticlesListView(LoginRequiredMixin, PermissionRequiredMixin,ListView):
    model = Article
    paginate_by = 50
    context_object_name = "articles"
    permission_required = 'is_staff'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['Filter_name'] = Article.objects.order_by().values('name').distinct()
        context['Filter_user'] = Article.objects.order_by().values('user').distinct()
        return context


    def get_queryset(self, **kwargs):
        return Article.objects.all()

And late in the template

{% for f in Filter_name %}
  <ul>
    <li>{{f.name}}</li>
  </ul>
{% endfor %}

How can I display a list of the district names and a list of the author names in the template with ForeignKey?


Solution

  • U can try something like that

    {% for item in model_1.foreign_model_set.all %}
        <h1>{{ item }}</h1>
    {% endfor %}