【问题标题】:ModelChoiceField with Django Forms带有 Django 表单的 ModelChoiceField
【发布时间】:2016-11-21 09:03:53
【问题描述】:

我被 Django 困住了,我想更多地了解这个框架。我阅读了一些教程(英语和法语教程),但在开始时,我没有找到我想要的。

我的应用目录中有一个forms.py file

#-*- coding: utf-8 -*-

from django import forms

class BirthCertificateForm (forms.Form) :

#   rowid = forms.IntegerField()  # rowid primary key
#   numero_acte = forms.IntegerField()  # Form number
    date_acte = forms.DateField('%d/%m/%Y')    # Form date
    heure_acte = forms.TimeField('%H:%M:%S')   # Form hour
    nom = forms.CharField(max_length=30, label=u"Nom")   # Lastname
    prenom = forms.CharField(max_length=30, label=u"Prénom")   # Firstname
    sexe = forms.  # <== I would like to have the choice between 'M' or 'F'

这是我的views.app 文件:

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import loader
from BirthCertificate.forms import BirthCertificateForm

# Create your views here.

def BirthCertificateAccueil(request) :
    # Fonction permettant de créer la page d'accueil de la rubrique Acte de Naissance 

    #Cherche le fichier html accueil et le renvois
    template = loader.get_template('accueil.html') 
    return HttpResponse(template.render(request))


def BirthCertificateCreationAccueil(request) :
     # Fonction permettant de créer la page de création du formulaire de la partie : Acte de Naissance 

     template = loader.get_template('creation_accueil.html')
     return HttpResponse(template.render(request))

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

    if request.method == 'POST' :
        form = BirthCertificateForm(request.POST or None)

        if form.is_valid():
            numero_acte = form.cleaned_data["Numero de l'acte"]
            nom = form.cleaned_data['Nom']
            prenom = form.cleaned_data['Prenom']

    return render_to_response(request, 'birthform.html', {'form' : form})

1) 我想在 sexe 字段中的 2 个选项之间进行选择。用户必须选择MF。我想我必须使用ModelChoiceField,但我不知道如何使用此功能。

2) 其他问题:用户提交表单时,后面的数据库是否更新了?所以我必须在某处指定rowid,否则它会自动添加?

非常感谢!

【问题讨论】:

  • 您有与该表单相关的模型吗?还有几乎所有你能在Django awesome docs找到的东西!!!
  • @vishes_shell 不,我的 models.py 文件是空的。有必要拥有一个吗?我正在关注的教程没有指定模型文件。

标签: python django django-forms


【解决方案1】:

ModelChoiceField 用于来自模型的选择。如果您不想要模型(如果您不想要模型,我不明白您在用您的数据做什么,但没关系),那么您只需使用 ChoiceField

sexe = forms.ChoiceField(choices=(('M', 'Mâle'), ('F', 'Femelle'))

【讨论】:

  • 感谢您的回答。例如,我想用我的表单数据替换文本中的一些变量。我没有编写模型文件,因为我遵循的教程没有指定 model.py 文件。但如果有必要,我会做一个。
  • 即使是法语,我也喜欢!:)
【解决方案2】:

您不需要模型来存储性别信息。您所需要的只是带有选项的 CharField。

请查看此答案中的示例:https://stackoverflow.com/a/8077907/4890586

【讨论】:

    猜你喜欢
    • 2010-10-11
    • 2015-11-12
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    相关资源
    最近更新 更多