Search code examples
djangoforms

how to set form field value - django


I want to show empty form field if there is nothing to show, otherwise a form field with the value inside:

{% if somevalue %}
  {{form.fieldname}} #<---- how do i set the `somevalue` as value of fieldname here?
{% else %}
  {{form.fieldname}}
{% endif %}

Solution

  • In your view, if it is a class-based view, do it like so:

    class YourView(FormView):
        form_class = YourForm
    
        def get_initial(self):
            # call super if needed
            return {'fieldname': somevalue}
    

    If it is a generic view, or not a FormView, you can use:

    form = YourForm(initial={'fieldname': somevalue})