Django - 在表单提交后更新一个字段

时间:2017-03-24 13:46:56

标签: python django forms

我正在寻找用户提交后更新我的Django表单。 我在BirthCertificateForm填写了一些数据,我只有一个未填充的字段:social_number

为什么?因为在提交表单后,我从数据表单创建了一个唯一的社交号码。所以,我想更新我以前的表格,并根据好的字段添加这个社交号码并验证它。

我的 models.py 文件如下所示:

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)

我的 views.py 文件有两个功能:

第一个功能:

# 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 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})

我的问题是:如何重新填写表单并进行修改以填充刚刚创建的social_number字段?

谢谢!

2 个答案:

答案 0 :(得分:1)

对于初学者,我建议您参考此article和此article

现在,根据您尝试执行的操作,我会在 models.py 中编写post_save,您可以在其中定义模型。因此,这就是它的样子:

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

注意:我假设您想要在创建出生证明记录时生成social_number,而不是在您进行修改时到现有记录。这就是我使用if kwargs.get('created', False)条件的原因。此条件基本上检查您是否正在创建新记录或修改现有记录。如果您希望在修改记录后立即运行此post_save,则删除条件。

答案 1 :(得分:0)

我找到了一个解决方案,可以更新我的模型。

我有这个功能:

@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})

所以我只添加了两行,它似乎工作得很好:

birthcertificate.social_number = social_number
birthcertificate.save()

您如何看待这种方法?

相关问题