2016-11-21 158 views
0

我被Django困住了,我想了解更多關於這個框架的知識。我讀了一些教程(英文和法文教程),並且在我開始時,我沒有找到我想要的東西。帶有Django表單的ModelChoiceField

我有一個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或自動添加?

非常感謝!

+0

您有與該表格相關的模型嗎?還有幾乎任何你可以在[Django真棒文檔](https://docs.djangoproject.com/en/1.10/)中找到的東西! –

+0

@vishes_shell不,我的models.py文件是空的。是否有必要有一個?我遵循的教程沒有指定模型文件。 – Deadpool

回答

2

ModelChoiceField是,嗯,這來自於車型選擇。如果你不需要模型(並且我不明白你如何處理你的數據,但是沒關係),那麼你只需要使用ChoiceField

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

謝謝你的回答。通過我的表單數據,我想替換文本中的一些變量。我不寫一個模型文件,因爲我下面的教程沒有指定model.py文件。但如果有必要,我會製作一個。 – Deadpool

+0

即使是法國人,我也喜歡!:) –