在CustomLabelModelChoiceField

时间:2017-03-07 10:22:18

标签: python django forms django-models django-forms

我正在尝试改进网站Django forms中的某些元素,但我需要您的帮助才能找到我的context_processors variable未出现在我的过滤条件中的原因。

我有一个模型(BirthCertificate),根据另一个模型(Identity)有两个ForeignKeys。

  • 身份:此模型包含有关城镇居民的所有信息(姓氏,名字,......)

  • BirthCertificate:此模型包含有关来自身份模型的新子项和父项信息的所有信息

当我显示两个ForeignKey选项字段时,列表很长,我想像这样过滤这个ForeignKeys:

仅显示姓名与子女性相同的人

为了做到这一点,我正在使用CustomLabelModelChoiceField而我正在制作queryset filter。我也在使用context_processors,但我没有克服在query filter中获取变量。

我的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(Identity, related_name='ID_Parent1', verbose_name='ID parent1', null=False)
    fk_parent2 = models.ForeignKey(Identity, related_name='ID_Parent2', verbose_name='ID parent2', null=False)
    created = models.DateTimeField(auto_now_add=True)

在我的views.py文件中,我有:

def BirthCertificate_Form(request) :

    query_lastname = request.GET.get('lastname')
    cache.set('VarLastname', query_lastname, 300)
    print cache.get('VarLastname')

    if request.method == 'POST':
    ....

在我的context_processors.py文件中:

def cached_queries(request):
    return {'VarLastname' : cache.get('VarLastname')}

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

class BirthCertificateForm(forms.ModelForm):
    fk_parent1 = CustomLabelModelChoiceField(Identity.objects.filter(lastname = cached_queries), required=False, label = "Père", label_func=lambda obj: '%s %s %s %s' % (obj.lastname, obj.firstname, obj.birthday, obj.birthcity))
    fk_parent2 = CustomLabelModelChoiceField(Identity.objects.filter(sex = "Feminin"), required=False, label = "Mère", label_func=lambda obj: '%s %s %s %s' % (obj.lastname, obj.firstname, obj.birthday, obj.birthcity))

但是,查询过滤器不适用于我的VarLastname。我得到一个空列表。

如果我更换:

CustomLabelModelChoiceField(Identity.objects.filter(lastname = cached_queries) CustomLabelModelChoiceField(Identity.objects.filter(lastname = "test")它有效!

如果您有任何想法?

编辑:

来自@Udi的回答,我的观点如下:

def BirthCertificate_Form(request) :
    # Fonction permettant de créer le formulaire Acte de Naissance et le remplissage

    query_lastname = request.GET.get('lastname')

    if request.method == 'POST':

        parents = Identity.objects.filter(lastname=query_lastname)
        Bform = BirthCertificateForm(request.POST)
        Bform.fields['fk_parent1'].queryset = parents.filter(sex="Masculin")
        Bform.fields['fk_parent2'].queryset = parents.filter(sex="Feminin")

        if Bform.is_valid() :   # Vérification sur la validité des données
            if '_save2' in request.POST :
                post = Bform.save()
                return HttpResponseRedirect(reverse('BC_treated', kwargs={'id': post.id}))

    else:
        Bform = BirthCertificateForm()

    context = {
        "Bform" : Bform,
        "query_lastname" : query_lastname,
    }

    return render(request, 'BC_form.html', context)

但它似乎不起作用。我正在寻找为什么^^

1 个答案:

答案 0 :(得分:1)

视图中,创建表单实例后,修改字段查询集:

parents = Identity.objects.filter(lastname=query_lastname)
form = BirthCertificateForm()
form.fields['fk_parent1'].queryset = parents.filter(sex="M")
form.fields['fk_parent2'].queryset = parents.filter(sex="F")

无需使用context_processors或cache。

修复后(和某些风格):

def get_form(lastname, data=None):
    form = BirthCertificateForm(data)

    if lastname:
        qs = Identity.objects.filter(lastname=query_lastname)
        form.fields['fk_parent1'].queryset = qs.filter(sex="Masculin")
        form.fields['fk_parent2'].queryset = qs.filter(sex="Feminin")

    return form

def birth_certificate_view(request) :
    lastname = request.GET.get('lastname')

    if request.method == 'POST':
        form = get_form(lastname, request.POST)
        if form.is_valid() :   # Vérification sur la validité des données
            if '_save2' in request.POST :
                post = form.save()
                return HttpResponseRedirect(reverse('BC_treated', kwargs={'id': post.id}))

    else:
        form = get_form(lastname)

    context = {
        "form" : form,
        "lastname" : lastname,
    }

    return render(request, 'bc_form.html', context)