Reputation: 6128
I'm looking for update my Django form after user submission.
I filled my BirthCertificateForm
with some data and I just have one field which is not filled : social_number
.
Why ? Because after submitting form, I created a unique social number from data form. So, I would like to update my previous form and add this social number according to the good field and validate it.
My models.py file looks like :
class BirthCertificate(models.Model):
lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille')
firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)')
sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
birthday = models.DateField(null=False, verbose_name='Date de naissance')
birthhour = models.TimeField(null=True, verbose_name='Heure de naissance')
birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance')
birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
fk_parent1 = models.ForeignKey(Person, related_name='ID_Parent1', verbose_name='ID parent1', null=False)
fk_parent2 = models.ForeignKey(Person, related_name='ID_Parent2', verbose_name='ID parent2', null=False)
mairie = models.CharField(max_length=30, null=False, verbose_name='Mairie')
social_number = models.CharField(max_length=30, null=True, verbose_name='numero social')
created = models.DateTimeField(auto_now_add=True)
And my views.py file have 2 functions :
First function :
# First function which let to fill the form with some conditions / restrictions
@login_required
def BirthCertificate_Form(request) :
# Fonction permettant de créer le formulaire Acte de Naissance et le remplissage
query_lastname_father = request.GET.get('lastname_father')
query_lastname_mother = request.GET.get('lastname_mother')
if request.method == 'POST':
form = BirthCertificateForm(request.POST or None)
if form.is_valid() : # Vérification sur la validité des données
post = form.save()
return HttpResponseRedirect(reverse('BC_treated', kwargs={'id': post.id}))
else:
form = BirthCertificateForm()
parent1 = Person.objects.filter(lastname=query_lastname_father)
parent2 = Person.objects.filter(lastname=query_lastname_mother)
form = BirthCertificateForm(request.POST or None)
form.fields['fk_parent1'].queryset = parent1.filter(sex="Masculin")
form.fields['fk_parent2'].queryset = parent2.filter(sex="Feminin")
context = {
"form" : form,
"query_lastname" : query_lastname_father,
"query_lastname_mother" : query_lastname_mother,
}
return render(request, 'BC_form.html', context)
Second function :
# Second function which resume the previous form and create my social number
@login_required
def BirthCertificate_Resume(request, id) :
birthcertificate = get_object_or_404(BirthCertificate, pk=id)
#Homme = 1 / Femme = 2
sex_number = []
if birthcertificate.sex == 'Masculin' :
sex_number = 1
print sex_number
else :
sex_number = 2
print sex_number
#Récupère année de naissance
birthyear_temp = str(birthcertificate.birthday.year)
birthyear_temp2 = str(birthyear_temp.split(" "))
birthyear = birthyear_temp2[4] + birthyear_temp2[5]
#Récupère mois de naissance
birthmonth_temp = birthcertificate.birthday.month
if len(str(birthmonth_temp)) == 1 :
birthmonth = '0' + str(birthmonth_temp)
else :
birthmonth = birthmonth_temp
#Récupère N° Mairie (ici récupère nom mais sera changé en n°)
birth_mairie = birthcertificate.mairie
print birth_mairie
#Génère un nombre aléaloire :
key_temp = randint(0,999)
if len(str(key_temp)) == 1 :
key = '00' + str(key_temp)
elif len(str(key_temp)) ==2 :
key = 'O' + str(key_temp)
else :
key = key_temp
print key
social_number = str(sex_number) + ' ' + str(birthyear) + ' ' + str(birthmonth) + ' ' + str(birth_mairie) + ' - ' + str(key)
print social_number
return render(request, 'BC_resume.html', {"birthcertificate" : birthcertificate})
My question is : How I can take again my form and modify it in order to fill thesocial_number
field just created ?
Thank you !
Upvotes: 0
Views: 2517
Reputation: 6128
I found a solution which works in order to update my models.
I had this function :
@login_required
def BirthCertificate_Resume(request, id) :
birthcertificate = get_object_or_404(BirthCertificate, pk=id)
#Homme = 1 / Femme = 2
sex_number = []
if birthcertificate.sex == 'Masculin' :
sex_number = 1
print sex_number
else :
sex_number = 2
print sex_number
#Récupère année de naissance
birthyear_temp = str(birthcertificate.birthday.year)
birthyear_temp2 = str(birthyear_temp.split(" "))
birthyear = birthyear_temp2[4] + birthyear_temp2[5]
#Récupère mois de naissance
birthmonth_temp = birthcertificate.birthday.month
if len(str(birthmonth_temp)) == 1 :
birthmonth = '0' + str(birthmonth_temp)
else :
birthmonth = birthmonth_temp
# #Récupère première lettre nom
# lastname_temp = birthcertificate.lastname
# lastname = lastname_temp[0]
# print lastname
# #Récupère première lettre prénom
# firstname_temp = birthcertificate.firstname
# firstname = firstname_temp[0]
# print firstname
#Récupère N° Mairie (ici récupère nom mais sera changé en n°)
birth_mairie = birthcertificate.mairie
print birth_mairie
#Génère un nombre aléaloire :
key_temp = randint(0,999999)
if len(str(key_temp)) == 1 :
key = '00000' + str(key_temp)
elif len(str(key_temp)) == 2 :
key = '0000' + str(key_temp)
elif len(str(key_temp)) == 3 :
key = '000' + str(key_temp)
elif len(str(key_temp)) == 4 :
key = '00' + str(key_temp)
elif len(str(key_temp)) == 5 :
key = '0' + str(key_temp)
else :
key = key_temp
print key
social_number = str(sex_number) + ' ' + str(birthyear) + ' ' + str(birthmonth) + ' ' + str(birth_mairie) + ' - ' + str(key)
print social_number
return render(request, 'BC_resume.html', {"birthcertificate" : birthcertificate, "social_number" : social_number})
So I just add two lines and it seems to work pretty well :
birthcertificate.social_number = social_number
birthcertificate.save()
What do you think about this method ?
Upvotes: 0
Reputation: 10399
For starters, I would recommend you refer to this article and this article.
Now, based on what you're trying to do, I would write the post_save
in your models.py where you have your model defined. Thus, this is what it would look like:
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
class BirthCertificate(models.Model):
... # your model attributes
# Here is where the post_save hook happens
@receiver(post_save, sender=BirthCertificate, dispatch_uid='generate_social_number') # You can name the dispatch_uid whatever you want
def gen_social(sender, instance, **kwargs):
if kwargs.get('created', False):
# Auto-generate the social number
# This is where you determine the sex number, birth year, birth month, etc. that you have calculated in your views.py.
# Use the instance object to get all the model attributes.
# Example: I'll calculate the sex number for you, but I leave the other calculations for you to figure out.
if instance.sex == 'Masculin':
sex_number = 1
else:
sex_number = 2
... # Calculate the other variables that you will use to generate your social number
... # More lines to create the variables
instance.social_number = str(sex_number) + ... # Now set the instance's social number with all the variables you calculated in the above steps
instance.save() # Finally your instance is saved again with the generated social number
NOTE: I'm assuming you want to generate the social_number when a birth certificate record is newly created, not when you're making a modification to an existing record. That's why I used the if kwargs.get('created', False)
conditional. This conditional basically checks if you're creating a new record or modifying an existing one. If you want this post_save to run even after modifying a record, then remove the condition.
Upvotes: 2