Home > database >  Using foreign key as object in Django Telmplates
Using foreign key as object in Django Telmplates

Time:06-04

I'm trying to build a structure using django rest framework for show some data in my html templates. But I can not show data from a model with foreignkey.

My structure should be like this:

{% for category in categories %}
    {{ category.category }} #category is the variable name
    {% for channel in category.channel_set.all %}
        {{ channel.title }}
    {{ endfor }}
{{ endfor }}

But I never can print the channel variables in html files.

models.py:

class Category(models.Model):
    user = models.ForeignKey(
        'auth.User', 
        on_delete=models.DO_NOTHING,
        unique=False,
        )
    category = models.CharField(
    max_length=255,
    unique=True,
    )
    _id = models.ObjectIdField(auto_created=True, serialize=False)

    event_creation = models.DateTimeField(auto_now=True)
    event_updated = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'category'
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.category

class Channel(models.Model):
        user = models.ForeignKey(
            'auth.User', 
            on_delete=models.DO_NOTHING,
            )
        _id = models.ObjectIdField(auto_created=True, serialize=False)
        date_creation = models.DateTimeField(auto_now=True)
        date_updated = models.DateTimeField(auto_now=True)
        category = models.ForeignKey(
            Category,
            max_length=255,
            on_delete=models.PROTECT,
            related_name='channel',
            unique=False,
            to_field='category',
            )
        channel = models.CharField(
            max_length=255,
            unique=True,
            )
        def __str__(self):
            return self.category

views.py:

class Gallery(viewsets.ModelViewSet):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = '/gallery.html'
    queryset = Category.objects.all()
    queryset2 = Channel.objects.all()
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request, **kwargs):
        kwargs['categories_list'] = self.queryset
        serializer = CategorySerializer(self.queryset,many=True)
        serializer2 = ChannelSerializer(self.queryset2,many=True)
        return Response({
            'categories':serializer.data,
            'channels':serializer2.data
            })

    # @login_required(login_url='/login/')
    def list(self, request):
        queryset = Category.objects.all()
        response = {'categories': queryset}
        return Response({'categories':queryset})

serializers.py:

class CategorySerializer(serializers.ModelSerializer):
    # _id = serializers.ReadOnlyField()
    categories = Category()
    class Meta:
        model = Category
        fields = '__all__'

class ChannelSerializer(serializers.ModelSerializer):
    # _id = serializers.ReadOnlyField()
    channels = Channel()
    class Meta:
        model = Channel
        fields = '__all__'

gallery.html:

{% extends "/model-page.html" %}

{% load core_tags %}

{% block content %}

<h1> co. </h1>
<h2> Last Archives </h2>

<a href="/category-api/">
    <button type="button"> New input </button>
</a>
<ul>
    {% for category in categories %}
    <td> {% underscoreTag category "_id" as category_id %} </td>
    <div {% if category.get_pass_event %} style="color: red "{% endif %}>
        <li>{{ category.category }} - {{ category.get_creation }}
                <ul>
                    <li>{{ category }}</li>
                    <ul>
                        <div>
                            {% for channel in category.channel_set.all %}
                                <li>Teste {{ channel.title }}</li>
                           
                            {% endfor %}
                        </div>
                    </ul>
                </ul>
                    <a href="/category/?id={{category_id}}&{{category.category}}">Edit</a> / 
                    <a href="/category/delete/{{category_id}}">Delete</a>
                
            </li>
        </div>
    {% endfor %}
</ul>

{% endblock %}

I had trying for {% for channel in category.channel_set.all %},{% for channel in category.channels_set.all %}, {% for channel in category.channel.all %} and {% for channel in category.channels.all %} and any of these worked for me.

Another info from my project is that I'm using djongo (becouse my database is mongodb).

I accept any help, and thanks for now!!

CodePudding user response:

I think the code of the serializers isn't correct.

class ChannelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Channel
        fields = '__all__'

class CategorySerializer(serializers.ModelSerializer):
    channel = ChannelSerializer(many = True, read_only = True)

    class Meta:
        model = Category
        fields = '__all__'

And in the html, some attributes don't exist in the models. channel_set should be changed into channel and channel.title into channel.channel. There are no names like channel_set, title in the models.

...
<ul>
    <div>
        {% for channel in category.channel %}
            <li>Teste {{ channel.channel }}</li>                           
        {% endfor %}
    </div>
</ul>
...

Or you should modify the names in the models.

  • Related