Reputation: 31119
I have a global question and a question about a specific problem in a context of signals. In order to solve what the issues, signal dispatcher is most useful, overkill?
I have an issue of saving multiple modelforms with foreign key. I assumed that this a signal can solve it. But I can't get how, because I do not understand the scope of the signals.
model
class CV(models.Model):
title = models.CharField(max_length=255)
# And other fields...
class HigherEducation(models.Model):
cv = models.ForeignKey(CV, blank=True, null=True)
institution = models.CharField(max_length=255)
# And other fields...
class ProfessionalExperience(models.Model):
cv = models.ForeignKey(CV, blank=True, null=True)
company_name = models.CharField(max_length=255)
# And other fields...
All the forms are modelforms inherited from models above. The last two are used in modelformsets. All of this forms are displayed in one html form in template.
forms
class CVForm(forms.ModelForm):
class Meta:
# All the stuff
class EducationForm(forms.ModelForm):
class Meta:
# All the stuff
class ExperienceForm(forms.ModelForm):
class Meta:
# All the stuff
Education = modelformset_factory(HigherEducation,
form=EducationForm,
max_num=2)
Experience = modelformset_factory(ProfessionalExperience,
form=ExperienceForm,
max_num=1)
In the view I need to save the EducationForm
and ExperienceForm
with cv
field with the assigned ID of current CV
model.
Can I solve this problem by signals?
It was hard to formulate the problem, so if anything is not clear, I will edit the question.
Upvotes: 3
Views: 1899
Reputation: 53991
Signals are simply hooks that allow you to fire pieces of code after a particular action occurs, i.e. 'when an instance/row of a model Foo
is saved, run the function baz()
'. Signals have two components : the actual signal (the action that has been carried out - a save/delete etc.) and the receiving function (what to do when that action occurs).
Django has many signals built in (for example, that is fired after or before a save operation, a signal that is fired after or before a delete operation) but you can also create your own signals. If you had a signup process in your website, you could write a signal that fires when a user creates an account and then link that signal to a function that sends the user an email
I don't think your situation is related to using signals. It sounds to me like you want to create a single form (composed of 3 smaller forms) where the latter 2 forms (Education & Experience) rely on the previous form (CV) being saved first?
In this case the issue is that you can't fill out the 2nd and 3rd form without having filled out the 1st form first (as no CV will exist yet) so to achieve this you might be best creating a form wizard with 3 steps; first save the CV, then using the CV show the 2nd and 3rd steps (which at this stage the CV will already be saved)
Upvotes: 11