Get type of Django form widget from within template

前端 未结 6 1506
你的背包
你的背包 2020-12-01 01:27

I\'m iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.

To do this accurately, I just need to

6条回答
  •  遥遥无期
    2020-12-01 01:57

    You can make every view that manages forms inherit from a custom generic view where you load into the context the metadata that you need in the templates. The generic form view should include something like this:

    class CustomUpdateView(UpdateView):
        ...
        def get_context_data(self, **kwargs):
           context = super().get_context_data(**kwargs)
           ...
           for f, value in context["form"].fields.items():
              context["form"].fields[f].type = self.model._meta.get_field(f).get_internal_type()
           ...
           return context
    

    In the template you can access these custom properties through field.field:

    {% if field.field.type == 'BooleanField' %}
         
    ...
    {% endif %}

    By using the debugger of PyCharm or Visual Studio Code you can see all the available metadata, if you need something else besides the field type.

提交回复
热议问题