Search code examples
djangodjango-widget-tweaks

Django widget tweaks manually set input field value?


I am looking for an easy way to manually set a form field (ModelForm) value in a Django Template. I've tried this

{% render_field my_form.my_field value=200 %}

(tried with and without quotes) but it doesn't work, field is still displaying 0. I can't populate those fields in advance (overwriting form initialization in a ModelForm, or similar), because I will need to change input values dynamically later on, based on other input fields (using HTMX).


Solution

  • If I could get your question correct, you are looking for a way to manually set a form field value in the Template especially when you need to change the values dynamically later on with HTMX, you can use the value attribute of the form field widget. Here’s how you can do it.

         # update of your code, here is the correct version
      {{ my_form.my_field.value|default_if_none:"200" }}
    
    # NB: The above code will render the field with a value of 200 if the current value is None. If the field already has a value, it will display the existing value.
    
    

    PS: Remember, the render_field tag you mentioned is part of the django-widget-tweaks library, which allows you to tweak the form field rendering in the template, but it doesn’t directly set the value of the field. The value parameter in render_field is used to set the HTML value attribute, not the value of the bound field in the form instance. That is the reason why your code couldn't work initially.

    You can set the value in the form instance of your view, and then get it before the template context form rendering. Here is the code:

     my_form.fields['my_field'].initial = 200
    
    

    Please, do replace my_form and my_field to your actual form class, and field instance you have in your model. Goodluck!