我想通过带有基类ListView的搜索表单,并通过搜索查询和模板中的视图来过滤标题或内容。
models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ('-date_posted', )
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', kwargs={'pk': self.pk})
forms.py:
from django import forms
class SearchForm(forms.Form):
keyword = forms.CharField()
views.py:
class PostListView(ListView):
model = Post
template_name = 'blog/index.html'
context_object_name = 'posts'
paginate_by = 5