vendredi 21 août 2020

How to access specific object from the database in Django to display it in the webpage?

I am trying to display the title and description from an SQLite database in Django? I have all the data from my database and from views file I have returned it as context.
Here's the model.py file:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse


# Create your models here.

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

Here's my views.py file:

def home(request):
    posts = Post.objects.all()
    search_query = request.GET.get('q')
    if search_query:
        posts = posts.filter(
            Q(title__icontains = search_query) |
            Q(content__icontains = search_query)
        )

    context={
        'posts': posts
    }
    return render(request,'blog/home.html', context)

And here the HTML code:-

    

Is there any way to get my job done i.e., display one title at a time or like what I am trying to say is, is there something like: post.title[1], post.title[2],.... or anything like this?




Aucun commentaire:

Enregistrer un commentaire