【发布时间】:2018-07-07 13:53:34
【问题描述】:
我正在用 Python 编写一个非常基本的网页,它有一个文本框,用户可以在其中输入用户名,然后点击 Ok 按钮,该按钮使用 GET 请求提交表单。 GET 将用户名作为参数传递并搜索数据库中的 auth_user 表。
我的问题是我无法传递用户名参数,如果你可以使用 Django 2.0 url 模式,请帮忙
urls.py
app_name = 'just_gains'
urlpatterns = [
path('lifecoaching', views.LifeCoach, name='life_coaching'),
path('lifecoaching/resultslifecoaching/<str:user_name>', views.LifeCoachSearchResults, name='results_life_coaching'),
]
forms.py
class LifeCoachSearch(forms.Form):
user_name = forms.CharField(label='Username', max_length=100, required = False)
views.py
def LifeCoach(request):
if request == 'GET':
form = LifeCoachSearch(request.GET)
if form.is_valid:
user_name = form.cleaned_data['user_name']
LifeCoachSearchResults(request,user_name)
else:
form = LifeCoachSearch()
return render(request, 'just_gains/life_coaching.html', {'form': form})
def LifeCoachSearchResults(request, user_name):
testUser = User.objects.filter(username__startswith=user_name)
context = {'TestUser': testUser}
return render(request, 'just_gains/results_life_coaching.html', context)
HTML(生活教练)
<form action="{% url 'just_gains:results_life_coaching' %}" method="GET" >
{% csrf_token %}
{{ form }}
<input type="submit" value="OK">
</form>
HTML(结果生活辅导)
<ul>
<li><a>print usernames that match the argument</a></li>
</ul>
【问题讨论】:
-
re_path('lifecoaching/resultslifecoaching/(?P
[\w.@+-]+)/', views.LifeCoachSearchResults, name='results_life_coaching'), 你必须导入路径旁边的 re_path
标签: python html django python-3.6 django-2.0