【问题标题】:Python - Django 2.0 - URL patterns, passing argumentsPython - Django 2.0 - URL 模式,传递参数
【发布时间】: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


【解决方案1】:

请原谅我在移动设备上的简短回复。尝试使用&lt;str:user_name&gt;在路径中将您的用户名作为字符串传递

【讨论】:

  • 感谢您的回复@Riptide34,我已更新我的问题以反映“str:”,但这并不能解决问题。
【解决方案2】:

通常我认为表单应该通过 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>

【讨论】:

  • 谢谢@Atcrank,我应该把我的论点的名称(用户名)放在我的表单 html 中 - 它有
  • 对不起,我刚刚回顾了我的答案,不得不进行更正。
  • 因为我让 GET 转到“结果”而不是输入表单。您不需要在第一次将参数名称放在 URL 中 - 而是将其发布到视图的请求中。命名 URL 参数用于为用户创建更具体的页面,您可以从任何地方将浏览器发送到该页面。例如,您可以通过在 username=request.USER['username'] 上设置结果视图过滤器来始终将用户发送到他们自己的页面。您在评论中的行不起作用,'user_name' 需要渲染到 url 中,但不能因为它不是可用于渲染的上下文的一部分
  • 到达那里,@Atcrank 我做了所有的更改,但得到了这个异常:异常类型:NoReverseMatch 异常值:未找到“results_life_coaching”的反向。 “results_life_coaching”不是有效的视图函数或模式名称。它在我的 url 模式中,名称为 = 'results_life_coaching'
  • 可能是视图名称应该使用应用命名空间调用,例如:'just_gains:results_life_coaching。您会发现您通常也需要在模板中执行此操作。
猜你喜欢
  • 2018-12-30
  • 2020-09-19
  • 2014-03-22
  • 2021-01-05
  • 1970-01-01
  • 2015-11-18
  • 2017-08-11
  • 2023-03-04
  • 2021-09-12
相关资源
最近更新 更多