pythonDjango 2.0 URL模式,传递参数

2024-10-01 13:39:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python编写了一个非常基本的web页面,其中有一个文本框,用户可以在其中输入用户名,然后单击Ok按钮,该按钮使用GET请求提交表单。GET将用户名作为参数传递,并在数据库中搜索auth_user表。在

我的问题是我不能传递用户名参数,请帮助如果你可以django2.0url模式

在网址.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'),
    ]

在表单.py在

^{pr2}$

在视图.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>

Tags: namepyform表单getrequest按钮results
2条回答

请原谅我的简短回应,因为我正在移动。尝试在路径中使用<str:user_name>将用户名作为字符串传递

通常我认为表单应该通过POST而不是GET提交,然后提交的用户名的值就可以在字典中找到了请求.POST['用户名']。GET应用于从服务器获取表单;将信息发布回服务器。POST确保浏览器将表单中的所有内容打包并发送完整,但是GET尝试在URL中对其进行编码,并且不做任何保证。在

使用forms时,将视图划分开来是很有帮助的,这样getrequests会拉上来空白的或预先填充的表单(空的搜索框),POST请求被处理并重定向到您所拥有的参数化结果屏幕。在

然后创建一个httpRedirect,用一个参数将请求重新分配给URL。我认为这个链接,例2是正确的方法。在

https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#redirect

所以你的函数应该是:

def LifeCoach(request):
    if request.method = 'GET':
       return render(request, 'just_gains/life_coaching.html', context)
    elif request.method = 'POST':
       # I have skipped form validation here for brevity        
       return redirect('results_life_coaching',request.POST['username'])

有一个名为username的字段可能会在以后使用时与您发生冲突或混淆请求.用户['用户名']。别忘了更改表单html!祝你一切顺利!在

[编辑1]我的代码错误;GET应调用lifecoaching表单,POST应重定向到results\u life_coaching页面。在

[编辑2]我对模板的建议:

HTML格式(生活辅导.html)在

^{pr2}$

HTML格式(结果LifeCoaching.html)在

<ul>
 {% for item in username_list %}
    <li>{{item.user_name}} - {{item.achievement}} </li>
 {% endfor %}
</ul>

相关问题 更多 >