Django check if checkbox is selected

后端 未结 3 694
星月不相逢
星月不相逢 2021-01-31 12:09

I\'m currently working on a fairly simple django project and could use some help. Its just a simple database query front end.

Currently I am stuck on refining the searc

3条回答
  •  隐瞒了意图╮
    2021-01-31 12:32

    Radio Buttons:

    In the HTML for your radio buttons, you need all related radio inputs to share the same name, have a predefined "value" attribute, and optimally, have a surrounding label tag, like this:

    Then in your view, you can look up which was selected by checking for the shared "name" attribute in the POST data. It's value will be the associated "value" attribute of the HTML input tag:

    # views.py
    def my_view(request):
        ...
        if request.method == "POST":
            display_type = request.POST.get("display_type", None)
            if display_type in ["locationbox", "displaybox"]:
                # Handle whichever was selected here
                # But, this is not the best way to do it.  See below...
    

    That works, but it requires manual checks. It's better to create a Django form first. Then Django will do those checks for you:

    forms.py:

    from django import forms
    
    DISPLAY_CHOICES = (
        ("locationbox", "Display Location"),
        ("displaybox", "Display Direction")
    )
    
    class MyForm(forms.Form):
        display_type = forms.ChoiceField(widget=forms.RadioSelect, choices=DISPLAY_CHOICES)
    

    your_template.html:

    {# This will display the radio button HTML for you #} {{ form.as_p }} {# You'll need a submit button or similar here to actually send the form #}

    views.py:

    from .forms import MyForm
    from django.shortcuts import render
    
    def my_view(request):
        ...
        form = MyForm(request.POST or None)
        if request.method == "POST":
            # Have Django validate the form for you
            if form.is_valid():
                # The "display_type" key is now guaranteed to exist and
                # guaranteed to be "displaybox" or "locationbox"
                display_type = request.POST["display_type"]
                ...
        # This will display the blank form for a GET request
        # or show the errors on a POSTed form that was invalid
        return render(request, 'your_template.html', {'form': form})
    

    Checkboxes:

    Checkboxes work like this:

    forms.py:

    class MyForm(forms.Form):
        # For BooleanFields, required=False means that Django's validation
        # will accept a checked or unchecked value, while required=True
        # will validate that the user MUST check the box.
        something_truthy = forms.BooleanField(required=False)
    

    views.py:

    def my_view(request):
        ...
        form = MyForm(request.POST or None)
        if request.method == "POST":
            if form.is_valid():
                ...
                if request.POST["something_truthy"]:
                    # Checkbox was checked
                    ...
    

    Further reading:

    https://docs.djangoproject.com/en/1.8/ref/forms/fields/#choicefield

    https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#radioselect

    https://docs.djangoproject.com/en/1.8/ref/forms/fields/#booleanfield

提交回复
热议问题