Andromedae93 Andromedae93 - 17 days ago 7
Python Question

ModelChoiceField with Django Forms

I'm stuck with Django and I would like to learn more and more on this framework. I read some tutorials (English and French tutorials) and as I'm beginning, I don't find what I want.

I have a

forms.py file
in my app directory :

#-*- 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'


And this is my
views.app
file :

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) I would like to have the choice between 2 options in sexe field. The user have to select
M
or
F
. I think I have to use
ModelChoiceField
but I don't know how I can use this function.

2) Other question : When the use submits the form, the database which is behind is updated right ? So I have to specify the
rowid
somewhere or it's automatically added ?

Thank you so much !

Answer

ModelChoiceField is for, well, choices that come from models. If you don't want models (and I don't understand what you're doing with your data if you don't, but never mind) then you just use ChoiceField.

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