如何在Django中设置表单的ID?

时间:2016-05-18 14:07:45

标签: javascript jquery html django django-forms

我创建了一个页面,用户可以在其中进行订购。因此,他们可以填写一些字段,如 description notes 等,包括"语言",这是formset的一个字段。

因此,在我的view中,有一个job_creation_form几乎包含所有字段,然后有一个FormsetLanguage个表单组成。

我想使用JQuery validate插件验证字段而不刷新页面。问题是,我可以在form中看到一个HTML标记,该标记没有任何id。如何设置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)

1 个答案:

答案 0 :(得分:2)

在Django中django.forms.Form只处理表单的内部(即字段,验证,保存)部分,而不是与提交有关的任何细节(提交按钮,操作,方法)。

这就是为什么在模板中渲染表单时的原因如下:

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

如果您愿意,可以在表单上设置id属性,并在模板中访问<form ... id='{{ form.id }}'>,或者只在表单上添加id。