简体   繁体   English

提交表单后,Django POST请求重定向到空URL

[英]Django POST request redirects to empty url after submitting form

I have a login form with POST method and when I submit the login data, it goes straight to the empty url and doesn't execute the login method in views.py. 我有一个使用POST方法的登录表单,提交提交数据时,它会直接转到空url,并且不会在views.py中执行该登录方法。 Ideally, after I submit the form in www.url.com/login via submit button, it should return a HttpResponse but instead, it takes me to www.url.com/ 理想情况下,当我通过“提交”按钮在www.url.com/login中提交表单后,它应该返回HttpResponse,但是它将我带到www.url.com/

I am new to Django, I'd appreciate it if you could look into it. 我是Django的新手,如果您可以研究它,我将不胜感激。 Thanks! 谢谢!

home.html home.html的

    <center><h1>Welcome to my website</h1>
    <form method='POST'> {% csrf_token %}
    {{ form }}
    <button type='submit' class='btn btn-default'>Submit</button>
    </form>
    </center>

urls.py urls.py

from django.contrib import admin
from django.urls import path

from .views import home, login

urlpatterns = [
    path('', home),
    path('login/', login),
    path('admin/', admin.site.urls),
]

forms.py forms.py

from django import forms

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

views.py views.py

from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.shortcuts import render

from .forms import LoginForm

def home(request):
    context={
        "form": "Test"
    }
    return render(request, "home.html", context)

def login(request):
    login_form = LoginForm(request.POST or None)
    context={
        "form": login_form
    }
    if login_form.is_valid():
        username = login_form.cleaned_data.get('username')
        password = login_form.cleaned_data.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            #request.user.is_authenticated()
            login(request, user)
            return HttpResponse("You are now logged in")
        else:
            return HttpResponse('Error')
    return render(request, "home.html", context)

First, you should set an attribute action in the form which set a url to send. 首先,您应该以设置要发送的网址的形式设置属性action

Second, a url value in action must be clear. 其次,必须清楚实际使用的url值。 It's not a matter of Django but HTML. 这不是Django的问题,而是HTML。 I'd like to recommend you to use absolute path . 我建议您使用absolute path If you use relative path , a slash string would be added whenever you send a request. 如果使用relative path ,则每当您发送请求时都会添加一个斜杠字符串。

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

This is because your form doesn't contain action , ie where should the POST call be made with the user credentials. 这是因为您的表单不包含action ,即使用用户凭据在哪里进行POST调用。

Try following change in home.html : 尝试在home.html以下更改:

<center><h1>Welcome to my website</h1>
<form action="" method='POST'> {% csrf_token %}
{{ form }}
<button type='submit' class='btn btn-default'>Submit</button>
</form>
</center>

Following the answers before, it would be a good practice to use named patterns instead of fixed urls. 按照之前的回答,使用命名模式而不是固定的URL是一个好习惯。

# urls
...
path('login/', login, name='login'),
...

# template
<form action="{% url 'login' %}" method='POST'>

So if you change for example 所以如果你改变例如

login/

for 对于

accounts/login/

You don't have to change the template as well. 您也不必更改模板。

urlpatterns = [
    re_path('^$', home_page),
    re_path('^admin/', admin.site.urls),
    re_path('^register/$', register_page, name='register'),
    re_path('^login/$', login_page, name='login'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

I solved this by adding ^$ to the beginning and end of the patterns. 我通过在模式的开头和结尾添加^$来解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM