2016-11-21 3 views
0

私はDjangoに悩まされています。私はこのフレームワークについてもっと学びたいと思います。私はいくつかのチュートリアル(英語とフランス語のチュートリアル)を読み、私が始めているように、私は自分が望むものを見つけません。ModelChoiceField with Django Forms

私は私のアプリのディレクトリに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つのオプションの選択を持っていると思います。ユーザーはMまたはFを選択する必要があります。私はModelChoiceFieldを使用しなければならないと思うが、私はこの機能をどのように使うことができるのか分からない。

2)その他の質問:フォームを送信すると、後ろのデータベースが正しく更新されますか?ですから、rowidをどこかに指定する必要がありますか、それとも自動的に追加されますか?

ありがとうございました!

+0

フォームに関連するモデルがありますか?また、[Django awesome docs](https://docs.djangoproject.com/ja/1.10/)で見つけることができるほとんどすべて! –

+0

@vishes_shellいいえ、私のmodels.pyファイルは空です。 1つ持っている必要がありますか?私が従っているチュートリアルでは、モデルファイルを指定していません。 – Deadpool

答えて

2

ModelChoiceFieldはモデル出身の選択肢、よく、のためです。モデルがほしいと思っていない場合(そして私があなたのデータを使って何をやっているのか分からない場合は気にしないでください)、ChoiceFieldを使用してください。

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

あなたの答えをありがとう。私のフォームデータでは、例えばテキスト内のいくつかの変数を置き換えたいと思います。私はモデルファイルを書きません。私が従っているチュートリアルでは、model.pyファイルを指定していないからです。しかし、必要なら、私は1つを作っていきます。 – Deadpool

+0

フランス語でも、私はそれが好き!:) –

0

性別に関する情報を保存するモデルは必要ありません。あなたが必要とするのは、選択肢を持つCharFieldだけです。

この答えでは例を見てください:https://stackoverflow.com/a/8077907/4890586

関連する問題