我有两个模型,具有外键关系的客户端模型和联系人模型,在创建客户端时我使用Django信号来创建联系人,但是我从数据库中收到错误:(1048,“ Column'client_id'不能为null”),当我检查数据库时发现联系人和客户行,那么如何摆脱此错误?
models.py
class Client_Data(models.Model):
RC = models.CharField(max_length=50)
Raison_social = models.CharField(max_length=254)
NIF = models.CharField(max_length=50,unique=True)
AI = models.CharField(max_length=50,unique=True)
NIS = models.CharField(max_length=50,unique=True)
Banque = models.CharField(max_length=50,unique=True)
CB = models.CharField(max_length=50)
adresse = models.CharField(max_length=50)
slug = models.SlugField(blank=True, unique=True)
active = models.BooleanField(default=True)
class Contact(models.Model):
client = models.ForeignKey(Client_Data,blank=True,on_delete=models.CASCADE)
Nom = models.CharField(max_length=50)
post = models.CharField(max_length=50)
Tel = models.CharField(max_length=50)
email = models.EmailField(max_length=255,unique=True)
contact_type = models.CharField(default='Client_contact',max_length=50)
@receiver(post_save, sender=Client_Data)
def create_contact(sender, **kwargs):
if kwargs['created']:
conatact = Contact.objects.create(client=kwargs['instance'])
post_save.connect(create_contact, sender=Client_Data)
views.py
def save_client_form(request, form,Contact_form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid() and Contact_form.is_valid():
form.save()
Contact_form.save()
data['form_is_valid'] = True
books = Client_Data.objects.all()
data['html_book_list'] = render_to_string('Client_Section/partial_client_c.html', {
'client': books
})
else:
print(form.errors)
print(Contact_form.errors)
data['form_is_valid'] = False
context = {'form': form,'contact_form':Contact_form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
def client_create(request):
if request.method == 'POST':
form = ClientForm(request.POST)
contact_form = Contact_Form(request.POST)
else:
form = ClientForm()
contact_form = Contact_Form()
return save_client_form(request, form,contact_form, 'Client_Section/partial_client.html')
forms.py
class ClientForm(forms.ModelForm):
class Meta:
model = Client_Data
fields = ('id', 'RC','Raison_social','NIF','AI','NIS','CB','Banque', 'adresse', 'active' ,)
class Contact_Form(forms.ModelForm):
class Meta:
model = Contact
fields = ('Nom','post','Tel','email','contact_type',)
答案 0 :(得分:0)
我认为问题出在这里
Contact_form.save()
Contact_form将保存到没有client_id的数据库中。与您的帖子保存无关。
如果您想在Contact
中为Contact_form
设置客户端,请尝试以下操作:
client = form.save()
contact = Contact_form.save(commit=False)
contact.client = client
contact.save()