Django:MultiValueDictKeyError

Django: MultiValueDictKeyError

我创建了这个注册表单,它运行良好。在同一个模板上,我创建了一个登录表单。注册表单有 3 个参数电子邮件、用户名和密码,而登录表单只有用户名和密码输入。当我尝试注册时一切正常,但是当我尝试登录时,它给了我 MultiValueDictKeyError

这是我的 views.py

from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from django.db import IntegrityError

# Create your views here.

def usersignup(request):
    if request.method == 'GET':
        return render(request, 'social_media/user.html')
    else:
        try:
            user = User.objects.create_user(username=request.POST.get['username'], password=request.POST.get['password'], email=request.POST['email'])
            user.save()
            login(request, user)
            return render(request, 'social_media/base.html')
        except IntegrityError:
            return render(request, 'social_media/user.html', {'error':'User already exists'})

def loginuser(request):
    if request.method == 'GET':
        return render(request, 'social_media/user.html')
    else:
        user = authenticate(request, username=request.POST.get['username'], password=request.POST.get['password'])
        if user is none:
            return render(request, 'social_media/user.html', {'errorsignin':'Invalid User man'})
        else:
            login(request, user)
            return render(request, 'social_media/base.html')

这是我的 HTML 表格:

{% load static %}

<form action="" method="POST">
    {% csrf_token %}
    <input type="text" name="username" placeholder="Username">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Sign In</button>
</form>
                
<form action="" method="POST">
    {% csrf_token %}
    <input type="text" name="username" placeholder="Username">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Sign Up</button>
</form>

   

有什么方法可以让我只使用用户名和密码来注册用户而不是电子邮件,或者我是否必须添加一个电子邮件输入字段来登录用户!

此致

范什

替换

request.POST['']

request.POST.get('')

无处不在

例子

request.POST['username']

request.POST.get('username')

get 是 views.py
中用 get() 替换 get[] 的方法 在 html

中纠正您的表单操作