我在尝试保存我的 Django 表单时收到 Key 错误消息。我无法将数据从 Django 表单保存到数据库
I am getting Key error message while trying to save my Django form. I am not able to save data from Django form to the database
我正在尝试使用 Django 表单将客户端与用户模型一起添加到我的客户端模型中。但截至目前,我遇到了一个关键错误。我无法弄清楚这有什么问题,希望对此有所帮助。
我的客户模型是这样的
class Clients(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE)
primaryphone = models.CharField(max_length=15, unique=True)
location = models.CharField(max_length=30, choices=States)
project_id = models.ForeignKey(Projects, on_delete=models.DO_NOTHING, default=1)
contract_id = models.ForeignKey(Contracts, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
对此的看法是
def add_client(request):
form = AddClientForm()
context = {
"form": form
}
return render(request, 'admintemplate/add_client_template.html', context)
def add_client_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect('add_client')
else:
form = AddClientForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
phone = form.cleaned_data['phone']
location = form.cleaned_data['location']
project_id = form.cleaned_data['project_id']
contract_id = form.cleaned_data['contract_id']
try:
user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3)
user.clients.location = location
user.client.primaryphone = phone
project_obj = Projects.objects.get(id=project_id)
user.clients.project_id = project_obj
contract_obj = Contracts.objects.get(id=contract_id)
user.clients.contract_id = contract_obj
user.clients.save()
messages.success(request, "Client Added Successfully!")
return redirect('add_client')
except:
messages.error(request, "Failed to Add Client!")
return redirect('add_client')
else:
return redirect('add_client')
这是我的forms.py
class AddClientForm(forms.Form):
email = forms.EmailField(label="Email", max_length=50, widget=forms.EmailInput(attrs={"class":"form-control"}))
password = forms.CharField(label="Password", max_length=50, widget=forms.PasswordInput(attrs={"class":"form-control"}))
first_name = forms.CharField(label="First Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
last_name = forms.CharField(label="Last Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
username = forms.CharField(label="Username", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
phone = forms.CharField(label="Phone", max_length=15, widget=forms.TextInput(attrs={"class":"form-control"}))
#For Displaying Projects
try:
projects = Projects.objects.all()
project_list = []
for project in projects:
single_project = (project.id, project.project_name)
project_list.append(single_project)
except:
project_list = []
#For Displaying Contracts
try:
contracts = Contracts.objects.all()
contract_list = []
for contract in contracts:
single_contract = (contract.id, contract.contract_name)
contract_list.append(single_contract)
except:
contract_list = []
project_name = forms.ChoiceField(label="Project", choices=project_list, widget=forms.Select(attrs={"class":"form-control"}))
contract_id = forms.ChoiceField(label="Contract", choices=contract_list, widget=forms.Select(attrs={"class":"form-control"}))
location = forms.ChoiceField(label="Location", choices=States, widget=forms.Select(attrs={"class":"form-control"}))
这是我的添加客户端模板
{% block main_content %}
{% load static %}
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<!--general form elements -->
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Add Client</h3>
</div>
<!--/.card-header -->
<!--form start -->
{% url 'add_client_save' as action_path %}
{% include 'admintemplate/form_template.html' with messages=messages form=form action_path=action_path button_text="Add Client" %}
</div>
/.card
</div>
</div>
</div><!-- /.container-fluid -->
</section>
{% endblock main_content %}
我收到以下错误消息
KeyError at /add_client_save/
'project_id'
Request Method: POST
Request URL: http://d1bbcb8e2c574d65bcfc28f937c87503.vfs.cloud9.us-east-2.amazonaws.com/add_client_save/
Django Version: 3.0.7
Exception Type: KeyError
Exception Value:
'project_id'
Exception Location: /home/ec2-user/environment/powercons/powercons_app/adminviews.py in add_client_save, line 337
Python Executable: /usr/bin/python3
Python Version: 3.7.10
Python Path:
['/home/ec2-user/environment/powercons',
'/usr/lib64/python37.zip',
'/usr/lib64/python3.7',
'/usr/lib64/python3.7/lib-dynload',
'/home/ec2-user/.local/lib/python3.7/site-packages',
'/usr/local/lib64/python3.7/site-packages',
'/usr/local/lib/python3.7/site-packages',
'/usr/lib64/python3.7/site-packages',
'/usr/lib/python3.7/site-packages']
Server time: Sun, 8 Aug 2021 10:23:08 -0600
您的表单 AddClientForm
不包含 project_id
字段但您想在 form.cleaned_data['project_id']
中使用它
您的错误是:
Exception Type: KeyError
Exception Value: 'project_id'
我正在尝试使用 Django 表单将客户端与用户模型一起添加到我的客户端模型中。但截至目前,我遇到了一个关键错误。我无法弄清楚这有什么问题,希望对此有所帮助。
我的客户模型是这样的
class Clients(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE)
primaryphone = models.CharField(max_length=15, unique=True)
location = models.CharField(max_length=30, choices=States)
project_id = models.ForeignKey(Projects, on_delete=models.DO_NOTHING, default=1)
contract_id = models.ForeignKey(Contracts, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
对此的看法是
def add_client(request):
form = AddClientForm()
context = {
"form": form
}
return render(request, 'admintemplate/add_client_template.html', context)
def add_client_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect('add_client')
else:
form = AddClientForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
phone = form.cleaned_data['phone']
location = form.cleaned_data['location']
project_id = form.cleaned_data['project_id']
contract_id = form.cleaned_data['contract_id']
try:
user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3)
user.clients.location = location
user.client.primaryphone = phone
project_obj = Projects.objects.get(id=project_id)
user.clients.project_id = project_obj
contract_obj = Contracts.objects.get(id=contract_id)
user.clients.contract_id = contract_obj
user.clients.save()
messages.success(request, "Client Added Successfully!")
return redirect('add_client')
except:
messages.error(request, "Failed to Add Client!")
return redirect('add_client')
else:
return redirect('add_client')
这是我的forms.py
class AddClientForm(forms.Form):
email = forms.EmailField(label="Email", max_length=50, widget=forms.EmailInput(attrs={"class":"form-control"}))
password = forms.CharField(label="Password", max_length=50, widget=forms.PasswordInput(attrs={"class":"form-control"}))
first_name = forms.CharField(label="First Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
last_name = forms.CharField(label="Last Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
username = forms.CharField(label="Username", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
phone = forms.CharField(label="Phone", max_length=15, widget=forms.TextInput(attrs={"class":"form-control"}))
#For Displaying Projects
try:
projects = Projects.objects.all()
project_list = []
for project in projects:
single_project = (project.id, project.project_name)
project_list.append(single_project)
except:
project_list = []
#For Displaying Contracts
try:
contracts = Contracts.objects.all()
contract_list = []
for contract in contracts:
single_contract = (contract.id, contract.contract_name)
contract_list.append(single_contract)
except:
contract_list = []
project_name = forms.ChoiceField(label="Project", choices=project_list, widget=forms.Select(attrs={"class":"form-control"}))
contract_id = forms.ChoiceField(label="Contract", choices=contract_list, widget=forms.Select(attrs={"class":"form-control"}))
location = forms.ChoiceField(label="Location", choices=States, widget=forms.Select(attrs={"class":"form-control"}))
这是我的添加客户端模板
{% block main_content %}
{% load static %}
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<!--general form elements -->
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Add Client</h3>
</div>
<!--/.card-header -->
<!--form start -->
{% url 'add_client_save' as action_path %}
{% include 'admintemplate/form_template.html' with messages=messages form=form action_path=action_path button_text="Add Client" %}
</div>
/.card
</div>
</div>
</div><!-- /.container-fluid -->
</section>
{% endblock main_content %}
我收到以下错误消息
KeyError at /add_client_save/
'project_id'
Request Method: POST
Request URL: http://d1bbcb8e2c574d65bcfc28f937c87503.vfs.cloud9.us-east-2.amazonaws.com/add_client_save/
Django Version: 3.0.7
Exception Type: KeyError
Exception Value:
'project_id'
Exception Location: /home/ec2-user/environment/powercons/powercons_app/adminviews.py in add_client_save, line 337
Python Executable: /usr/bin/python3
Python Version: 3.7.10
Python Path:
['/home/ec2-user/environment/powercons',
'/usr/lib64/python37.zip',
'/usr/lib64/python3.7',
'/usr/lib64/python3.7/lib-dynload',
'/home/ec2-user/.local/lib/python3.7/site-packages',
'/usr/local/lib64/python3.7/site-packages',
'/usr/local/lib/python3.7/site-packages',
'/usr/lib64/python3.7/site-packages',
'/usr/lib/python3.7/site-packages']
Server time: Sun, 8 Aug 2021 10:23:08 -0600
您的表单 AddClientForm
不包含 project_id
字段但您想在 form.cleaned_data['project_id']
您的错误是:
Exception Type: KeyError
Exception Value: 'project_id'