我想允许用户在数据库中搜索该主题。并在网址中显示主题名称。 我已经在数据库中创建了子弹字段,但是当我尝试从数据库中获取数据时,URL无法正确显示。
网址显示:
http://127.0.0.1:8000/topic/<slug:topicname>/
我要显示的内容:
http://127.0.0.1:8000/topic/introduction-to-python/
我的urls.py文件
从django.urls导入路径 来自。导入视图
urlpatterns = [
path('', views.apphome),
path('topic/<slug:topicname>/', views.searchtopic, name = 'searchtopic'),
]
我的项目模型
class blogposts(models.Model):
topic = models.CharField(max_length = 200)
slug = models.SlugField(max_length = 150, null=True, blank = True)
post = models.TextField(max_length = 500)
def __str__(self):
return self.topic
这是我的观点
def searchtopic(request,topicname):
if request.method == 'POST':
topicname = request.POST.get('searchtopicname')
mypost = mypostlist.objects.filter(slug = topicname)
context = {
'mypost':mypost,
}
return render(request, 'blog/result.html',context)
我搜索主题的表格
<form action="topic/<slug:topicname>/" method="POST">
{% csrf_token %}
<input type="search" placeholder="Search topics or keywords" name="searchtopicname">
<button type="submit">Search</button>
</form>
答案 0 :(得分:0)
您可以使用安装了“ POST”的“ GET”方法 将表单替换为:
<form action="{%url 'searchtopic' %}" method="GET">
{% csrf_token %}
<input type="search" placeholder="Search topics or keywords" name="searchtopicname">
<button type="submit">Search</button>
</form>
替换urls.py:
urlpatterns = [
path('', views.apphome),
path('topic/', views.searchtopic, name = 'searchtopic'),
]
替换视图:
def searchtopic(request):
if request.method == 'GET':
topicname = request.GET['searchtopicname']
mypost = mypostlist.objects.filter(slug = topicname)
context = {
'mypost':mypost,
}
return render(request, 'blog/result.html',context)