尝试将用户提供的值从一页重定向到下一页。 一切都可以在一个视图中完成,但是当我尝试使用HttpResponseRedirect Django重定向到下一个视图时,返回错误“ / search_results处的NameError,名称”未定义”。如何将“文本”值从一个视图传递到另一个视图(到我的搜索结果)
我的views.py(效果很好,用户在一个字段中提供的值将从django过滤器返回相应的固化结果)
def test_views(request):
form = MeanForm(request.POST)
if form.is_valid():
text = form.cleaned_data['name']
else:
text = None
search_users = SearchWoman(request.GET, queryset=Woman.objects.all().filter(city=text))
context = { 'form': form, 'text': text, 'filter': search_users }
return render(request, 'test.html', context)
我的test.html
<h1>TEST_1</h1>
<form method="POST" class="post-form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Submit</button>
</form>
<h2> {{ text }} </h2>
<h1><br></br></h1>
{% for profile in filter.qs %}
<li>{{ profile.name }} </li>
{% endfor %}
我的过滤器。py
from .models import Woman
import django_filters
class SearchWoman(django_filters.FilterSet):
class Meta:
model = Woman
fields = ['city', 'rating']
我的表格。py
from django import forms
from .models import Mean
class MeanForm(forms.ModelForm):
class Meta:
model = Mean
fields = ('name',)
我如何尝试进行重定向(它返回错误“在/ search_results处出现NameError,nazwa”“未定义”)
def test_views(request):
form = MeanForm(request.POST)
if form.is_valid():
text = form.cleaned_data['name']
return HttpResponseRedirect('/search_results/')
else:
text = None
context = { 'form': form, 'text': text, }
return render(request, 'test.html', context)
def search_results(request):
search_users = SearchWoman(request.GET, queryset=Woman.objects.all().filter(city=text))
context = { 'search_user': search_users }
return render(request, 'search_results.html', context)
Tempaltes错误(应用第二个视图之后)
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/search_results/
Django Version: 2.1.3
Python Version: 3.7.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'host_app',
'django_filters']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\tymot\Desktop\agencja_modeli_modelek\env\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\tymot\Desktop\agencja_modeli_modelek\env\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\tymot\Desktop\agencja_modeli_modelek\env\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\tymot\Desktop\agencja_modeli_modelek\app_rama\host_app\views.py" in search_results
59. search_users = SearchWoman(request.GET, queryset=Woman.objects.all().filter(city=text))
Exception Type: NameError at /search_results/
Exception Value: name 'text' is not defined
**编辑:错误代码:**
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/test/
Django Version: 2.1.3
Python Version: 3.7.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'host_app',
'django_filters']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\tymot\Desktop\agencja_modeli_modelek\env\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\tymot\Desktop\agencja_modeli_modelek\env\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\tymot\Desktop\agencja_modeli_modelek\env\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\tymot\Desktop\agencja_modeli_modelek\app_rama\host_app\views.py" in test_views
50. return HttpResponseRedirect(reverse('search_results', args=[text]))
File "C:\Users\tymot\Desktop\agencja_modeli_modelek\env\lib\site-packages\django\urls\base.py" in reverse
90. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\tymot\Desktop\agencja_modeli_modelek\env\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
622. raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /test/
Exception Value: Reverse for 'search_results' not found. 'search_results' is not a valid view function or pattern name.
URLS应用
from django.conf.urls import url
from .import views
app_name = 'host_app'
urlpatterns = [
[...]
url(r'^test/$', views.test_views, name='test_views'),
url(r'^search_results/(?P<text>[\w\-]+)/$', views.search_results, name='search_results')
]
URLS Rama(在settings.py 旁边)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('host_app.urls', namespace='host_app')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
答案 0 :(得分:1)
您可以使用reverse尝试将参数发送到下一个视图:
# views
def test_views(request):
form = MeanForm(request.POST)
if form.is_valid():
text = form.cleaned_data['name']
eturn HttpResponseRedirect(reverse('search_result', args=[text]))
else:
text = None
context = { 'form': form, 'text': text, }
return render(request, 'test.html', context)
def search_results(request, text):
search_users = SearchWoman(request.GET, queryset=Woman.objects.all().filter(city=text))
context = { 'search_user': search_users }
return render(request, 'search_results.html', context)
# urls
path('search_result/<str:text>/', search_results, name="search_result")
# urls for django 1.11 or older versions
url(r'^search_result/(?P<text>[\w\-]+)/$',search_results, name="search_result")
答案 1 :(得分:1)
由于您使用的是django过滤器,因此将数据放入重定向的查询参数中是有意义的。
0a040000
传递数据的另一种方法是使用会话对象。这要求django的会话中间件处于活动状态,并且客户端使用cookie。两者都是标准的,因此它对于典型的网站应该能很好地工作。
from django.utils.http import urlencode
from django.urls import reverse
from django.http import HttpResponseRedirect
def test_views(request):
city, rating = 'Springfield', 11 # or get them from a form
query_string = urlencode({'city': city, 'rating': rating})
next_url = '{}?{}'.format(reverse(search_results), query_string)
return HttpResonseRedirect(next_url)
def search_results(request):
search_users = SearchWoman(request.GET)
# when redirected, the url and request.GET contains data from previous view
return render(request, 'search_results.html', {'search_users': search_users})
会话易于使用。如果您想了解有关会话如何工作的更多信息,请阅读django文档的以下部分:How to use sessions