【发布时间】:2020-09-19 15:16:57
【问题描述】:
我想允许用户在数据库中搜索主题。并在 url 中显示主题名称。 我已经在数据库中创建了 slug 字段,但是当我尝试从数据库中获取数据时,url 显示不正确。
网址显示:
http://127.0.0.1:8000/topic/<slug:topicname>/
我想展示的内容:
http://127.0.0.1:8000/topic/introduction-to-python/
我的 urls.py 文件
from 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>
【问题讨论】:
标签: django django-models django-forms django-views django-templates