1

I am learning how to handle JSON files in Django and I have successfully unpacked JSON, but now I would like to put it inside the table.

Is there a way to do that with pure HTML and using so called "tornado brackets" {{ }} not with jQuery / JS functions?

My code:

API BACKEND FILE

from requests import get


default_values = {
    "repoName": "",
    "repoURL": ""
    }

def get_response():
    response = get_json()

    main_dictionary = {
        "items":[]
    }

    try:
        for repos in response:
            main_dictionary["items"].append({
                "repoName": repos["name"],
                "repoURL": repos["html_url"]
                })

    except KeyError as error:
        print("Key Error, check the validity of the keys you try to use to decode JSON")

    return main_dictionary["items"]


def get_json():
    first_response = get('https://api.github.com/users/jacobtoye/repos')

    response = first_response.json()

    return response

A FAILED ATTEMPT AT RENDERING PURE HTML TABLE

{% block content %}

<table>
    <tr>
{% for repos in response %}
        <td>{{ repoName }}</td>
    {% if not forloop.last and forloop.counter == 3 or forloop.counter == 6 %}
    </tr>
    {% endif %}
    <tr>
{% endfor %}
    </tr>
</table>

The table doesn't show at all. I don't think that any other code files are substantial for this problem, but if you think you need more code, LMK I will gladly show you :)

1
  • You will need JSON.parse() to use the JSON response in the frontend and for that, you would javascript Commented Jun 12, 2022 at 14:40

1 Answer 1

1

In Django's views you usually pass such values as context.

function based view:

def a_view(request):
    context = {
        'some_things': Thing.objects.all()
    }
    return render(request, 'your_template.html', context)

class based view:

class TheView(View):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['some_things'] = Thing.objects.all()
        return context

With any of given approaches in template it will work like this:

{% for thing in some_things %}
    {{ thing }}, {{ thing.id }}, {{ thing.get_related_things }}
{% endfor %}
Sign up to request clarification or add additional context in comments.

3 Comments

You're an awesome person @NixonSparrow. Thank you. You helped me figure it out and not did it for me. There is a special place in heaven for people like you :)
I just had similar problems and sometimes can relate ;)
Still thanks for not doing this for me, but helping me grow <3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.