我不知道我在哪里弄乱了我的代码

时间:2019-12-06 07:10:31

标签: python django

from django.http import HttpResponse
from django.shortcuts import render,redirect, get_list_or_404, get_object_or_404
from .models import Users
from .forms import UsersForm
from django.contrib.auth import authenticate

# Create your views here.

def login(request):

    #Username = request.POST.get(‘username’)
    #password = request.POST.get(‘password’)

    form = UsersForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = UsersForm()
        return redirect('/product/itemlist')  
    user = authenticate(username='username', password='password')
    if user is not None:
    # redirect to homepage
        return redirect('/product/itemlist')
    else:
    # display login again
        return render(request, 'users/login.html',  {'form':form})

这是我运行服务器时的视图页面,需要我登录页面然后输入我的密码并尝试登录时问题开始

  

找不到页面(404)请求方法:POST请求   URL:http://127.0.0.1:8000/users/login/index.html使用URLconf   在mazwefuneral.urls中定义,Django在此尝试了这些URL模式   订单:

     

admin /产品/用户/登录/ [name ='login']主要/帐户/

     

当前路径users / login / index.html与任何这些都不匹配。

     

您看到此错误,因为您的Django中的DEBUG = True   设置文件。将其更改为False,Django将显示一个   标准404页面。

这是越来越错误了

1 个答案:

答案 0 :(得分:1)

您是否要在此处使用登录功能对用户进行身份验证?如果是这样,您需要像这样更改视图:

def login(request):
   form = UsersForm()
   # first check if the request is post 
   if request.method == 'POST':
      form = UsersForm(request.POST)
      if form.is_valid():
         # get username and password if the form is valid
         username = form.cleaned_data['username']
         password = form.cleaned_data['password']
        #now authenticate user
         user = authenticate(request,username=username, password=password)
         if user is not None:
           #redirect to your success url
           return redirect('/product/itemlist')
         else:
         # redirect to login page
          messages.error(request,"Invalid username or password")
          return redirect('login')

    return render(request,'users/login.html',{'form':form})
相关问题