Home > Enterprise >  Object created in view isn't rendering in template
Object created in view isn't rendering in template

Time:11-29

I'm creating a new object in a view through an external function. This is the code:

def index(request):
    sousei = suii_scratch(SOUSEI_URL)
    s_jikan = sousei[0]
    s_suii = sousei[1]
    sousei_obj = Sousei.objects.create(jikan=s_jikan, suii=s_suii)
    #print(sousei_obj)
    context = {
        sousei_obj : 'sousei',
    }
    return render(request, 'index.html', context)

The external function is returning two values, that are being catched in s_jikan and s_suii variables. These variables are then used to create a new object (the model has only this two fields).

If I uncomment the print statement, I get printed the __str__ method of the model with the newly obtained data from the external function. Also, if I check the admin, the new record in the database is beign saved correctly. Until here seems everything is working fine, but when passing the created object to the template I can't get it rendered. This is template code:

{% if sousei %}

<p>{{sousei.jikan}}</p>
<p>{{sousei.suii}}</p>

{% else %}

<p>No data.</p>

{% endif %}

But I keep getting there is no data. What am I missing?

CodePudding user response:

In a dictionary the key comes before the value, you were using the created object as the key and a string as the value in your context

def index(request):
    ...
    context = {
        'sousei': sousei_obj
    }
    return render(request, 'index.html', context)
  • Related