Я получаю сообщение об ошибке Key при попытке сохранить мою форму Django. Я не могу сохранить данные из формы Django в базу данных

Я пытаюсь добавить клиента к моей модели клиента вместе с моделью пользователя, используя Django forms. Но пока что я получаю ошибку ключа. Я не могу понять, что не так, и буду признателен за помощь в этом вопросе.

Моя клиентская модель такова

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'
Вернуться на верх