pythondjangodjango-templatesdjango-widgetdjango-widget-tweaks

Correct way to implement django-widget-tweaks markup


I am trying to render a form using django-widget-tweaks to help with css and widget types. I performed the following steps:

Install widget tweaks with pip3 in my venv successfully.

Put 'widget_tweaks', in INSTALLED_APPS in settings.py.

Put the following in the template code. (The rest of the template tags render as expected).

{% load widget_tweaks %}
{% render_field form.color0 type="color" id="color0" class+="input-color" %}
<!--replaces <input type="color" id="color0" class="input-color" />-->

My <input> element isn't rendering when I use the template markup (renders fine with static html, of course). The development server shows no errors, and if I print myform.as_table() in the shell it renders all the fields, so my Form object must be correct. What have I screwed up with django-widget-tweaks here?

Edit: I also tried

{{ form.color0 | add_class:"input-color" | attr:"type:color" | attr:"id:color0" }}

I know the template engine is parsing it because if I deliberately misspel attr the webserver shows the error page.


Solution

  • Realised that form wasn't instantiated until after POSTing (when I was debugging the request). Need to do something like:

    if request.method == "POST":
        #process the form data
    else:
        return render(request, "my_template.html", {"form":MyForm()})