简体   繁体   中英

Django forms: List of checkboxes populated from a model

In Django I'm trying to render a list of checkboxes with the choices being populated from values in a model's field. Here is what I have so far:

models

#Model that feeds the list of checkboxes
class Category_Level1(models.Model):
    category_level1_name = models.CharField(max_length = 50)

forms

class ProductCategoryLevel1Form(forms.Form):
    product_category_level1 = forms.MultipleChoiceField(label = "Product Category", choices = Category_Level1.objects.all(), widget = forms.CheckboxSelectMultiple)

views

def select_product(request):
    product_category_level1 = ProductCategoryLevel1Form()
    if request.method == 'POST':
        product_category_level1_form = ProductCategoryLevel1Form(request.POST)
        if product_category_level1_form.is_valid():
            product_category_level1_list = product_category_level1_form.cleaned_data.get('product_category_level1', 'Unk')
    # Saving the selected categories to another table
            product_cat_obj = Product_Category_Level1(category_level1_name = product_category_level1_list)
            product_cat_obj.save()

    context = {
    'product_category_level1' : product_category_level1
    }

    return render(request, 'select_product/select.html', context)

template

<div class="row">
    <label for="id_prod_category"></label>
    {% product_category_level1 %}
</div>

I get the following error:

Invalid block tag on line 23: 'product_category_level1', expected 'endblock'. Did you forget to register or load this tag?

What am I doing wrong?

Appreciate any suggestions.

Django uses two types of markup - {% ... %} for tags and {{ ... }} for variables .

In this code you are trying to render the product_category_level1 variable , therefore you should use {{ product_category_level1 }} instead of {% product_category_level1 %} in your template.

However, there are also some other bugs in this code.

  1. You seem to be mixing product_category_level1 and product_category_level1_form in your view code. These should all be the same variable. You need to use the same variable so when binding the POST data and calling is_valid() the form you display to the user contains any validations errors. As you currently have it you always give the user a new instance of the form - if any data validations fail the form will be presented again with all the fields empty and no error messages.
  2. You need to tell Django how you want your form to be rendered - as p tags, as li tags, etc. As such you'll need to add the method call as_p like this: {{ product_category_level1.as_p }} . More rendering options can be found here: https://docs.djangoproject.com/en/1.10/topics/forms/#working-with-form-templates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM