Reputation: 11
I'm trying to display the data from table using dynamic url. However, when I try to do so, it just rendered out the attribute of the table instead. But when I use the same syntax to print on the shell, it works
here is my view
def taches(request):
taches = JobServices.objects.all()
if request.user.is_authenticated:
return render(request, 'taches.html', {'taches': taches})
else:
print('User is authenticated')
return redirect('login')
return render(request, 'taches.html', {'taches': taches})
def service_fait(request, my_id):
if request.user.is_authenticated:
elements = JobServices.objects.filter(id=my_id)
for element in elements:
print(element.service_name)
print(element.hour)
print(element.user)
print(element.description)
return render(request, 'services_faits.html', {'elements': elements})
else:
return redirect('login')
Here is the dynamic url:
path('servicefait/<str:my_id>', views.service_fait, name='servicefait')
The taches.html template:
<div class="container">
<h2>{{ user }}, voici les tâches disponibles pour vous</h2>
<div class="row">
{% for tache in taches %}
<div class="col">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="{{ tache.image_url }}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ tache.service_name }}</h5>
<b class="card-text">{{ tache.amount }} VT pour {{ tache.hour }} heures </b></p>
<a href="{% url 'servicefait' tache.id %}" class="btn btn-primary">Postuler</a>
</div>
</div>
</div>
{% endfor %}
</div>
services_faits.html template:
<div class="container">
{% for element in elements %}
<p>element.service_name</p>
<p>element.hour</p>
<p>element.amount</p>
<p>element.description</p>
{% endfor %}
Here is the output of the web page:
element.service_name
element.hour
element.amount
element.description
And the shell is working properly as it shows the content of the above attribute. Normally when I click the href link in taches.html it should redirect to the dynamic url by executing the method service_fait in the view
And finally, here is the model:
class JobServices(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
service_name = models.CharField(max_length=100, default="nom du service")
hour = models.IntegerField(default="Heures")
amount = models.FloatField(default="Cout")
service_date = models.DateTimeField(auto_now_add=True, null=True)
description = models.CharField(max_length=2000, null=True, default="annonce")
image_url = models.CharField(max_length=2000, null=True, blank=True)
image = models.ImageField(null=True, blank=True)
Upvotes: 0
Views: 1095
Reputation: 1703
You need to use double brackets in your for loop to print element attributes.
{% for element in elements %}
<p>{{ element.service_name }}</p>
...
{% endfor %}
Upvotes: 1