Django - 表格问题

时间:2017-05-26 10:35:09

标签: django

我正在使用带有python 3.6的Django 1.11。 我有一个表单,当表单发送时没有选中任何单选按钮,表单是valide。 但是,如果我发送带有单选按钮“性别”的表单,无论是男性还是女性,表单都不是valide。

你知道这是什么问题吗?

模板:

<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

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:0)

尝试在字段定义中设置required=False

答案 1 :(得分:0)

forms.ChoiceField是解决方案。