我有一个页面,其中有一个/ tag / name_of_tag路径,您可以看到所有带有该标签标记的帖子。 在页面内,您还可以选择表单中的另一个标签并转到该标签。 问题在于,它转到/ tag /?search = searched_tag而不是转到/ tag / searched_tag 如何更改它不离开?search =部分?
urls.py:
url(r'tag/(?P<input_tag>\w+)$', views.tag_view, name='tag'),
views.py:
def tag_view(request, input_tag):
form = TagSearchForm()
if request.method == 'GET':
form = TagSearchForm(request.GET)
if form.is_valid():
input = form.cleaned_data['search']
print(input)
return redirect('fortykwords:tag_view', input)
else:
form = SearchForm()
latest_post_list = Post.objects.filter(tags=input_tag, status__exact="published")
paginator = Paginator(latest_post_list, 3)
page = request.GET.get('page')
posts = paginator.get_page(page)
context = {'latest_post_list': latest_post_list, 'page_tag': input_tag, 'form': form}
return render(request, 'fortykwords/tag.html', context)
forms.py:
class TagSearchForm(forms.Form):
search = tagulous.forms.SingleTagField(
tag_options=tagulous.models.TagOptions(
autocomplete_view='fortykwords:post_tags_autocomplete'
),
label='Tags',
required=True,
help_text=_('Filter by lead tags. You can organize leads by any tag you want.'),
)
tag.html:
{% extends "base_generic.html" %}
{% block content %}
<form action="." method="get">
{{ form }}
<input type="submit" value="Submit" />
</form>
<h3>Posts with the tag {{ page_tag }}</h3>
{% if latest_post_list %}
<ul>
{% for post in latest_post_list %}
<li> {{ post.author }} {{ post.pub_date }}
<br>
<a href="{% url 'fortykwords:detail' post.id %}">{{ post.title }}</a></li>
{% for tag in post.tags.all %}
<a href="{% url 'fortykwords:tag' tag.name %}">{{ tag.name }}</a>
{% endfor %}
{% endfor %}
</ul>
{% else %}
<p>No posts are available.</p>
{% endif %}
{% endblock %}
答案 0 :(得分:0)
您需要将input
的参数redirect
提供给input_tag=input
。
示例:
return redirect('fortykwords:tag_view', input_tag=input)
答案 1 :(得分:0)
它显示为/tag/?search=searched_tag
,因为您的表单是由GET
提交的,但从未进入重定向。似乎is_valid()
返回了False
。
我已经测试了您的代码的非常相似的版本,并且认为它不是tagulous的错误,但是仍然有兴趣知道出了什么问题(我写了tagulous)。发现了几个可以简化代码的地方,因此请尝试::
def tag_view(request, input_tag):
# Can't see any POSTs in your example, so you can pass the form GET here
# Might also be nice to pass the original tag in so it shows in the form
form = TagSearchForm(request.GET, initial={'search': input_tag})
# The form already has the GET, so you can go straight into the is_valid
if form.is_valid():
input = form.cleaned_data['search']
print('Valid: ', input)
return redirect('fortykwords:tag_view', input)
else:
print('Invalid: ', form.errors, form.non_field_errors)
# You can remove the else for if not GET, which would never be reached
# on to pagination as before
(尽管我建议使用ipdb而不是print
)