djangodjango-3.0

how to use django post_save signal


I have two models, client and contact model with foreign key relation, I using Django signals to create contact while the creation of the client, but I getting an error from the database : ( 1048, "Column 'client_id' cannot be null") when I check the database I found the contact and the client rows, so how to get rid of this error?

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',)


Solution

  • I think the problem is here

    Contact_form.save()
    

    The Contact_form will save to database without a client_id. It has nothing to do with your post save.

    If you want to set a client for your Contact within your Contact_form try something like this:

    client = form.save()
    contact = Contact_form.save(commit=False)
    contact.client = client
    contact.save()