Search code examples
djangoformsdjango-webtest

How to assign form id to Django ModelForm?


I am using django-webtest to create automated functional tests for my application.

As I have multiple forms on a single web page, I'm currently using a hard-coded index to select the form of interest. For instance:

    # Forms on this page are: forms[0] = Establishment form,
    # forms[1]= School Form
    school_form = school_page.forms[1]
    school_form['phone'] = self.school_phone_number
    school_form.submit(value='Submit')

I would like to use the form id instead of a hard-coded index to select the form of interest, so that the code is maintainable. But when I print school_form.id in my code, the value is None.

Template is:

<form action="" method="post" >
{% csrf_token %}
<p>
    {{ establishment_form|crispy }}
    <br><br>
    {{ school_form|crispy }}
</p>
<button type="submit" class="btn btn-lg btn-primary">Submit</button>

I couldn't locate in the Django documentation how to assign the form id (not the form field id) to a ModelForm. Could someone help me with this?

I'm using Django 1.7, django-webtest 1.7.8, WebTest 2.0.18 and django-crispy-forms 1.4.0.


Solution

  • Django forms aren't responsible for outputting the form element itself. So there is nothing to be done at the form declaration level.

    You can always pass an attribute from the view and use it in your template:

    <form id="{{ form_id_from_view }}" action="." method="POST">