Использование foreignkey в элементе формы select извлекает данные, но в базе данных они равны null
Я создаю приложение на Django. У меня есть несколько моделей, как определено ниже
id = HashidAutoField(primary_key=True, salt='ClientBgColor' + settings.HASHID_FIELD_SALT)
color = models.CharField(max_length=10, blank=True, null=True)
def __str__(self):
return self.color
class Client(models.Model):
id = HashidAutoField(primary_key=True, salt='Client' + settings.HASHID_FIELD_SALT)
company_name = models.CharField(max_length=100, blank=True, null=True)
contact_name = models.CharField(max_length=100, blank=True, null=True)
contact_email = models.EmailField(max_length=100, blank=True, null=True)
phone = models.CharField(max_length=100, blank=True, null=True)
address = models.CharField(max_length=100, blank=True, null=True)
country = models.CharField(max_length=100, null=True, blank=True)
city = models.CharField(max_length=100, null=True, blank=True)
logo = models.ImageField(upload_to='clients/logo/', blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
template = '{0.company_name}'
return template.format(self)
class ProjectType(models.Model):
id = HashidAutoField(primary_key=True, salt='ProjectType' + settings.HASHID_FIELD_SALT)
name = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
template = '{0.name}'
return template.format(self)
class Project(models.Model):
id = HashidAutoField(primary_key=True, salt='Project' + settings.HASHID_FIELD_SALT)
project_name = models.CharField(max_length=100, blank=True, null=True)
client = models.ForeignKey('Client', on_delete=models.CASCADE, related_name='clientProjects')
created_on = models.DateTimeField(auto_now_add=True)
description = models.TextField(null=True, blank=True)
project_type = models.ForeignKey('ProjectType', on_delete=models.CASCADE, related_name='typeOfProject', blank=True, null=True)
last_updated = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.project_name
в файле forms.py,
from dataclasses import fields
from django import forms
from app.models import *
class NewProjectForm(forms.ModelForm):
project_name = forms.CharField(
label = '',
widget=forms.TextInput(attrs={
'id' : '',
'class' : 'form-control form-control-lg',
'placeholder' : 'Project name'
})
)
client = forms.ModelChoiceField(
queryset=Client.objects.all(),
# initial='Select client',
label = '',
widget=forms.Select(attrs={
'id' : 'taProjectClient',
'class' : 'form-control form-control-lg',
'placeholder' : 'Select client'
})
)
project_type = forms.ModelChoiceField(
queryset=ProjectType.objects.all(),
label = '',
widget=forms.Select(attrs={
'id' : 'taProjectType',
'class' : 'form-control form-control-lg',
'placeholder' : 'Select project type'
})
)
description = forms.CharField(
label = '',
widget=forms.Textarea(attrs={
'id' : '',
'class' : 'form-control form-control-lg',
'placeholder' : 'Project overview'
})
)
class Meta:
model = Project
fields = ['project_name', 'client', 'description']
В файле views.py, вот как я управляю формой
def post(self, request, *args, **kwargs):
new_project_form = NewProjectForm(request.POST or None)
if request.method == 'POST' and 'createProjectBtn' in request.POST:
if new_project_form.is_valid():
new_project = new_project_form.save(commit=False)
new_project.created_by = request.user
new_project.save()
new_project_form = NewProjectForm()
else:
msg = 'Invalid form. Please, check and try again'
new_project_form = NewProjectForm()
projects = Project.objects.all().order_by('-last_updated')
context = {
'projects' : projects,
'new_project_form' : new_project_form,
}
return render(request, 'app/projects.html', context)
В шаблоне оба элемента выбора типа проекта и клиента имеют правильные данные. Но в базе данных, когда я отправляю форму, клиент сохраняется правильно, но тип_проекта является нулевым.