Milano
Milano

Reputation: 18745

How to set ID for form in Django?

I've created a page, where user can make an order. So they can fill some fields like description,notes etc. including "language", which is a one field of formset.

So in my view, there is a job_creation_form which contains almost all fields, then there is a Formset consists of Language forms.

I would like to use JQuery validate plugin to validate fields without refreshing the page. The problem is that I can see one form tag in HTML, which doesn't have any id. How to set the id?

enter image description here

def create_order(request):
    LanguageLevelFormSet = formset_factory(LanguageLevelForm, extra=5, max_num=5)
    language_level_formset = LanguageLevelFormSet(request.POST or None)
    job_creation_form = JobCreationForm(request.POST or None, request.FILES or None)

    context = {'job_creation_form': job_creation_form,
               'formset': language_level_formset}

    if request.method == 'POST':
        if job_creation_form.is_valid() and language_level_formset.is_valid():
            cleaned_data_job_creation_form = job_creation_form.cleaned_data
            cleaned_data_language_level_formset = language_level_formset.cleaned_data
            for language_level_form in [d for d in cleaned_data_language_level_formset if d]:
                language = language_level_form['language']
                level = language_level_form['level']
                job = Job(
                        customer=request.user,
                        text_to_translate=cleaned_data_job_creation_form['text_to_translate'],
                        file=cleaned_data_job_creation_form['file'],
                        short_description=cleaned_data_job_creation_form['short_description'],
                        notes=cleaned_data_job_creation_form['notes'],
                        language_from=cleaned_data_job_creation_form['language_from'],
                        language_to=language,
                        level=level,
                )
                job.save()
            return HttpResponseRedirect('/order-success')
        else:
            print job_creation_form.errors
            print language_level_formset.errors
            return render(request, 'auth/jobs/create-job.html', context=context)

    return render(request, 'auth/jobs/create-job.html', context=context)

Upvotes: 1

Views: 6107

Answers (1)

James Fenwick
James Fenwick

Reputation: 2211

In Django django.forms.Form only deals with the internal (i.e. fields, validation, saving) parts of a form, not any of the details relating to submission(submit buttons, actions, method).

That is why when you render a form in a template it is like:

{% extend base.html %}
{% block content %}
<form action='' method='post'>
{{ form }}
</form>
{% endblock %}

If you want you can set an id property on the form and access it in the template like <form ... id='{{ form.id }}'>, or just put an id on the form.

Upvotes: 3

Related Questions