【问题标题】:why I don't get clean data when i use cleaned_data为什么我在使用cleaned_data 时没有得到干净的数据
【发布时间】:2018-06-12 23:27:41
【问题描述】:

我正在尝试为我的网站创建一个登录表单,但是当我在 views.py 中使用 clean_data 时,我没有得到正确的数据。 这是我的代码:

views.py

def login_page(request):
    form = LoginForm(request.POST or None)
    context = {
        'form': form
    }
    if form.is_valid():
        print(form.cleaned_data)
        username = form.cleaned_form.get("username")
        password = form.cleaned_form.get("password")
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect("/")
        else:
            print("Error")
    return render(request, "auth/login.html", context)


forms.py

class LoginForm(forms.Form):
    username = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "class": "form-control",
                "placeholder": "Username"
            }
        )
    )
    password = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                "class": "form-control",
                "placeholder": "Password"
            }
         )
    )


login.html

<form action="POST">{% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-default">Submit</button>
</form>


这是我填写用户名和密码字段并单击提交时得到的结果。 print(form.cleaned_data) 显示 url 字段中有我想使用但无法访问的数据。

【问题讨论】:

  • 你不想写username = form.cleaned_data[..而不是username = form.cleaned_form[..,即_data而不是_form吗?
  • 是的,你是对的,但这不是真正的问题。我在 forms.py 中更改了一些内容,但在发布之前我忘记更正了。问题在于使用操作而不是方法。

标签: python django forms authentication login


【解决方案1】:

你的观点完全错误,用这个

def login_page(request):
   form = LoginForm(request.POST or None)
   context = {
    'form': form
   }
   if request.method == 'POST':
      if form.is_valid():
          print(form.cleaned_data)
          username = form.cleaned_data["username"]
          password = form.cleaned_data["password"]
          user = authenticate(request, username=username, password=password)
          if user is not None:
             login(request, user)
             return redirect("/")
          else:
             print("Error")
      else:
          print('form not valid')
return render(request, "auth/login.html", context)

和html到

<form method="post" action="">
    {% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-default">Submit</button>
</form>

【讨论】:

  • 非常感谢,问题是使用动作而不是方法。我检查了我的代码超过 10 次,但我没有注意到。
  • 完成! @Exprator
【解决方案2】:

您的 HTML 中有错误 - 您应该使用 method="post" 而不是 action。现在,您在/login/POST 发送带有输入作为查询参数的GET,而不是在/login 发送POST。这在您附加的屏幕截图中很明显。

有效表单应如下所示:

<form method="post">
    {% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-default">Submit</button>
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-19
    • 2011-11-27
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    相关资源
    最近更新 更多