'Django - Data from view not rendered in template
I'm having quite some troubles understanding how variables are passed to templates in Django, I'm new so keep this in mind. My problem is that, when the URL is loaded data from databases can't be rendered except for the user(request.user.username) which is strangely loaded. I even tried to declare variables inside the view's def but even them are not rendered
The model is imported inside the views.py.
My idea is that, since the user from request.user is loaded, there must be some problem with loading the database model, but this doesn't explain why even freshly declared variables inside the view's def are not passed.
In the /admin page all the models work fine.
Below are the fragments of my code, they should be enough to understand the problem, if not I can upload other parts.
Thank you in advance.
views.py:
def load_main(request):
diet_list = DietTable.objects.all()
return render(request, 'main/main.html',
{
'diet_list': diet_list,
'user': request.user.username,
})
part in the main.html:
<body>
...
<header>
...
</header>
...
{% block content %}
<strong>
{{ user }}
{% for element in diet_list %}
{{ element }}
{% endfor %}
</strong>
{% endblock %}
...
</body>
urls.py:
from django.urls import path, include
from main import views
urlpatterns = [
path('', views.load_main, name='main_view'),
]
models.py
...
class DietTable(models.Model):
diet_id = models.AutoField(primary_key=True) # to not use the default 'id; given by django
dietName = models.CharField(max_length=50)
dietType = models.ForeignKey(DietTypes, on_delete=models.PROTECT)
startDate = models.DateTimeField()
dayLength = models.IntegerField()
def __str__(self):
return str(str(self.dietName) + "(" + str(self.dayLength) + ")")
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
