是否有可能从html模板中的表单输入添加到django项目的url ?



在我的主页的侧边栏中,有一个搜索框,用户可以在其中键入条目的名称并被带到该页面。因此,例如,如果他们输入css,他们将被带到http://127.0.0.1:8000/wiki/css,在那里输入的值被附加到url。(首页url为http://127.0.0.1:8000/wiki/)

当我在表单中使用get方法时,它最终会搜索/wiki/?q=css,而不仅仅是在url的末尾拥有/css。但是,当我在我的表单中使用post方法时,url保持在http://127.0.0.1:8000/wiki/,最后没有额外的url。

如何将输入附加到url的末尾?

HTML:

<h2>Wiki</h2>
<form action="/wiki/" method="post">
{% csrf_token %}
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>

urls . py:

from tokenize import Name
from unicodedata import name
from django.urls import path
from django.http import HttpResponse
from . import views
urlpatterns = [
path("", views.index, name="index"),
path('hello/', views.hello, name='hello'),
path('<str:name>', views.entry, name='entry'),
path('new/', views.new, name='new'),
path('random/', views.randomEntry, name='random')
]

views.py:

from django.shortcuts import render
from django.http import HttpResponse
from django import forms
import random
from . import util

def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})

def hello(request):
return HttpResponse('Hello, world')

def entry(request, name):
return HttpResponse(util.get_entry(name))

def search(name):
value = util.get_entry(name)
if value != None:
return value

class searchForm(forms.Form):
search = forms.CharField(label='Search Encyclopedia')
# this was not used as I do not know if it would be useful

def new(request):
return render(request, "encyclopedia/new.html", {
"entries": util.list_entries()
})

def randomEntry(request):
list = []
for i in util.list_entries():
list.append(i)
num = random.randint(0, len(list)-1)
page = list[num]
return render(request, f"entries/layout.html", {
"entries": util.list_entries()
})

util.py(我不知道这是否有用,但它可以使用):

import re
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage

def list_entries():
"""
Returns a list of all names of encyclopedia entries.
"""
_, filenames = default_storage.listdir("entries")
return list(sorted(re.sub(r".md$", "", filename)
for filename in filenames if filename.endswith(".md")))

def save_entry(title, content):
"""
Saves an encyclopedia entry, given its title and Markdown
content. If an existing entry with the same title already exists,
it is replaced.
"""
filename = f"entries/{title}.md"
if default_storage.exists(filename):
default_storage.delete(filename)
default_storage.save(filename, ContentFile(content))

def get_entry(title):
"""
Retrieves an encyclopedia entry by its title. If no such
entry exists, the function returns None.
"""
try:
f = default_storage.open(f"entries/{title}.md")
return f.read().decode("utf-8")
except FileNotFoundError:
return None

让您的输入表单发送到一个新视图,该视图检索字段值,然后根据该值重定向到您的wiki条目

html

<h2>Wiki</h2>
<form action="{% url 'wiki-lookup' %}" method="post">

views.py

def wiki-lookup(request):
#first we get the posted q term, or return 'notfound' if the form fails to provide a value
term = request.POST.get('q', 'notfound')
#....test term for validity here as appropriate
#next redirect to 'entry' passing the term as the name value for that URL
return redirect('entry', name = term)

urls . py

...
path('wiki-lookup/', views.wiki-lookup, name='wiki-lookup'),

Django实际上很简洁,视图不必是真正的页面——它们可以做一些工作来确定用户应该最终到达哪个页面。

相关内容

  • 没有找到相关文章