1

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.

Tanuka
  • 122
  • 1
  • 11

2 Answers2

2

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">
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • How would I use it in this template with two forms? Added the template in the main edit. – Tanuka Sep 16 '15 at 09:21
  • I don't really understand. You only have one form in that template; it contains fields from two Django forms, but that's irrelevant from the point of view of the HTML. – Daniel Roseman Sep 16 '15 at 09:43
  • Thank you. I get it now. I was confusing the unit of granularity - there are two Django forms, but on the HTML page they are merged into a single one. I tried out your suggestion and it works now :-) – Tanuka Sep 16 '15 at 09:53
0

You can directly assign the id to the form element in your template.

<form id="my_id" name="some_name" action="/my/url/" method="POST">
Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
  • 1
    Thanks, Rahul, for responding. I've just accepted Daniel's answer because it came in first. – Tanuka Sep 16 '15 at 09:55