/ docker / auth / django 1.11形式的KeyError

时间:2017-07-10 11:52:30

标签: python django django-forms

我试图抓住并显示正在通过POST请求进行复制的django表单数据,但是我在KeyError中遇到了一个我的字段名称,

这是错误:

KeyError at /docker/auth/
'docker_name'
Request Method: POST
Request URL:    http://127.0.0.1:8000/docker/auth/
Django Version: 1.11.3
Exception Type: KeyError
Exception Value:    
'docker_name'
Exception Location: /Users/abdul/Documents/IGui/dockerDep/views.py in post, line 21
Python Executable:  /Users/abdul/IstioVirEnv/bin/python
Python Version: 3.6.1

这是我的models.py:

from django.db import models

class DockerAuth(models.Model):
    docker_name = models.CharField(max_length=255)
    docker_pass = models.CharField(max_length=255)

这是我的forms.py:

from django.forms import forms
from .import models

class DockerAuthForm(forms.Form):
    class Meta:
        fields = ('docker_name', 'docker_pass')
        model = models.DockerAuth

这是我的views.py:

from django.shortcuts import render
from django.views.generic import CreateView
from . import forms


class DockerAuth(CreateView):
form_class = forms.DockerAuthForm

def get(self, request, *args, **kwargs):
    return render(request, 'dockerDep/docker_login.html', {})

def post(self, request, *args, **kwargs):
    lform = forms.DockerAuthForm(request.POST)
    context = {}
    if lform.is_valid():
        data = lform.cleaned_data
        name = data['docker_name']
        password = data['docker_pass']
        context = {
            "form": lform,
            "uname": name,
            "upass": password
        }
    return render(request, 'dockerDep/response.html', context)

这是我的HTML模板表单:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DOCKER</title>
</head>
<body>
    <form method="post" action=".">
        {% csrf_token %}
        <input type="text" name="docker_name" title="Name">
        <input type="password" name="docker_pass" title="Password">. 
        <input type="submit" value="Submit"/>
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

使用ModelForm应修复KeyError。在forms.py

  • from django.forms import forms更改为from django import forms
  • class DockerAuthForm(forms.Form)更改为class DockerAuthForm(forms.ModelForm)