I'm trying to add some objects with the input field, but they don't show up on the website. I can find them in the admin page, but not in the table, where i want them. How can i fix it?
Here is my code:
models.py
class Kommentar(models.Model):
user = models.CharField(max_length=25)
comment = models.CharField(max_length=250)
def __str__(self):
return f"{self.user} {self.comment}"
views.py
def index(request):
if 'q' in request.GET:
q = request.GET['q']
# literatur = Literatur.objects.filter(name__icontains=q)
multiple_q = Q(Q(name__icontains=q) | Q(autor__icontains=q) | Q(jahr__icontains=q) | Q(auflage__icontains=q) | Q(verlag__icontains=q) | Q(ort__icontains=q) | Q(isbn__icontains=q))
literatur = Literatur.objects.filter(multiple_q)
else:
literatur = Literatur.objects.all()
return render(request, "literatur/index.html", {"literatur":literatur})
def commentAction(request):
user = request.POST["user"]
comment = request.POST["comment"]
print(user, comment)
Kommentar.objects.create(user=user,
comment = comment)
return HttpResponseRedirect(reverse('literatur:index'))
urls.py
app_name = "literatur"
urlpatterns = [
path('', views.index, name='index'),
path('<int:literatur_id>/', views.detail, name="detail"),
path('new', views.new, name="new"),
path('deleteAction/<int:i>/', views.deleteAction, name="deleteAction"),
path('commentAction', views.commentAction, name="commentAction"),
]
index.html
<table >
<thead >
<tr><th scope="col">Username</th><th scope="col">Kommentar</th></tr>
{% for i in kommentar %}
<tr>
<td>{{i.user}}</a></td>
<td>{{i.comment}}</td>
</tr>
{% endfor %}
</table>
CodePudding user response:
Inside index view function, you make a query to literatur, and pass that to render function to render html template. However the index.html does not care about literatur.
Make a query to Kommentar and pass the queryset to render function
def index(request):
… # Your view logic
kommentar = Kommentar.objects.all()
return render(request, ‘literatur/index.html’, {‘literatur’: literatur, ‘kommentur’: kommentur})
P.S.
- The literatur queryset is not used in the index.html template. You may want to just remove this part of view logic, or modify index.html to make use of the queryset;
- You may want to add trailing slash to ‘new’ and ‘commentAction’ url path in your urls.py
CodePudding user response:
Are you sure it's the right index.html ? It doesn't make sense to pass literatur there since your template fits the purpose of rendering user comments.
Anyway.. you forgot to pass a list of "Kommentar"-Items to your index.