CheckboxSelectMultiple Django提取(如果已选中)

时间:2018-09-11 14:14:51

标签: python django

我被困在“ CheckboxSelectMultiple”上,我不知道如何提取用户选择的内容,而不提取什么。

例如,我的forms.py:

from django import forms

FAVORITE_COLORS_CHOICES = (
    ('blue', 'Blue'),
    ('green', 'Green'),
    ('black', 'Black'),
)


class MyForm(forms.Form):
    favorite_colors = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=FAVORITE_COLORS_CHOICES,
    )

我的views.py:

from accounts.forms import MyForm

def my_view(request):
    form = MyForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            try:
                if request.POST["favorite_colors"]:
                    print(request.POST["favorite_colors"])
            except:
                print(request.POST["favorite_colors"])
    return render(request, 'accounts/form.html', {'form': form})

当前,它给了我最后一个选中的复选框,如何检查是否选中了特定的复选框? (例如'if request.POST [“ favorite_colors.blue”]:print('blue')'或类似的东西。)

1 个答案:

答案 0 :(得分:2)

尝试这样的事情吗?

def my_view(request):
    form = MyForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            print("Selected: " + form.cleaned_data['favorite_colors'])
        else:
            print("error")

    return render(request, 'accounts/form.html', {'form': form})