2017-05-26 44 views
0

我使用Django 1.11與python 3.6。 我有一個表單,當表單發送時沒有任何單選按鈕選中,表單是valide。 但是,如果我發送帶有單選按鈕「性別」的表格進行檢查,無論是男性還是女性,表單都不是精確的。Django - 表單問題

你知道這是什麼問題嗎?

模板:

<form action="{% url 'games' %}" method="POST"> 
    {% csrf_token %} 
    <p>{{ form.identifiant|add_class:"form-control"|attr:"placeholder:Quel sera votre identifiant unique ?"|attr:"name:identifiant" }}</p> 
    <p>{{ form.email|add_class:"form-control"|attr:"placeholder:Indiquez-y votre email !"|attr:"name:email" }}</p> 
    <p>{{ form.password|add_class:"form-control"|attr:"placeholder:Créer votre mot de passe ici."|attr:"name:password" }}</p> 
    <p>{{ form.confirm_password|add_class:"form-control"|attr:"placeholder:Retaper votre mot de passe."|attr:"name:confirm_password" }}</p> 
    <p>{{ form.sex|attr:"" }}</p> 
    <input class="btn btn-lg btn-primary" type="submit" value="Continuer"> 
</form> 

forms.py

class MinimumRegisterForm(forms.Form): 
    identifiant = forms.CharField(
     max_length=50, 
    ) 
    email = forms.EmailField(
    ) 
    password = forms.CharField(
     widget=forms.PasswordInput, 
    ) 
    confirm_password = forms.CharField(
     widget=forms.PasswordInput, 
    ) 
    sex_choice = (
     ('H', 'Homme'), 
     ('F', 'Femme'), 
    ) 
    sex = forms.MultipleChoiceField(
     widget=forms.RadioSelect(), 
     choices=sex_choice, 
    ) 

views.py

def view_games(request): 
    if request.method == 'POST': 
     form = MinimumRegisterForm(request.POST) 
     if form.is_valid(): 
      identifiant = form.cleaned_data['identifiant'] 
      email = form.cleaned_data['email'] 
      password = form.cleaned_data['password'] 
      confirm_password = form.cleaned_data['confirm_password'] 
      sex = form.cleaned_data['sex'] 
      form = GamesRegisterForm() 
      return render(request, 'games.html', locals()) 
     else:   
      messages.add_message(request, messages.INFO, 'Formulaire invalide') 
      return redirect(view_register) 
    else: 
     return redirect(view_register) 

enter image description here

非常感謝您的幫助。

+0

你試過設置required = False嗎? – sureshvv

+0

@sureshvv是的,我試過要求假,但它沒有解決問題。 – GrandGTO

+3

@sureshvv嘗試'forms.ChoiceField' –

回答

0

forms.ChoiceField是解決方案。

1

嘗試在字段定義中設置required=False