0

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

我的问题是我无法传递用户名参数,如果您可以使用 Django 2.0 url 模式,请提供帮助

网址.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

class LifeCoachSearch(forms.Form):
    user_name = forms.CharField(label='Username', max_length=100, required = False)

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

2 回答 2

1

请原谅我在手机上的简短回复。尝试使用路径将您的用户名作为字符串传递<str:user_name>

于 2018-01-28T21:53:56.720 回答
0

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

使用表单,将视图划分为有用的,以便 GET 请求拉出空白或预先填充的表单(空搜索框),并且 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'])

在使用 request.USER['username'] 时,有一个名为 username 的字段可能会与您发生冲突或使您感到困惑。不要忘记更改您的表单 html!一切顺利!

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

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

HTML (lifecoaching.html)

<form action="{% url 'just_gains:life_coaching' %}" method="POST" >
    {% csrf_token %}
    {{ form }}     
    <input type="submit" value="OK">
</form>

HTML (resultslifecoaching.html)

<ul>
 {% for item in username_list %}
    <li>{{item.user_name}} - {{item.achievement}} </li>
 {% endfor %}
</ul>
于 2018-01-28T22:26:42.643 回答