urls.py
:
urlpatterns = [
path('employee/add_employee/', views.add_employee, name='add-employee'),
path('employee/add_employee/add/', views.add_employee_action, name='add-employee-action'),
]
我有add-employee
页和一些要填写的表格。
views.py
:
def add_employee(request):
personal_form = PersonalEmployeeForm()
history_form = EmployeeHistoryForm()
return render(
request,
'sections/add_employee.html',
context={
'personal_form': personal_form,
'history_form': history_form,
}
)
def add_employee_action(request):
if request.method == "POST":
personal_form = PersonalEmployeeForm(request.POST)
history_form = EmployeeHistoryForm(request.POST)
if personal_form.is_valid() and history_form.is_valid():
# here is some logic with models
return redirect('add-employee')
else:
personal_form = PersonalEmployeeForm()
history_form = EmployeeHistoryForm()
return render(
request,
'sections/add_employee.html',
context={
'personal_form': personal_form,
'history_form': history_form,
}
)
模板:
<form id="a-submit-form" action="add/" method="POST">
{% csrf_token %}
<div class="column-wrapper">
<div class="column">
<div class="form-wrapper">
{% for field in personal_form.visible_fields %}
{% include "elements/forms/form_line.html" %}
<br>
{% endfor %}
</div>
</div>
<div class="column">
<div class="form-wrapper">
{% for field in history_form.visible_fields %}
{% include "elements/forms/form_line.html" %}
<br>
{% endfor %}
</div>
</div>
</div>
<div class="button-bar-wrapper">
<div class="button_bar">
<a class="a-button positive" id="submit">Добавить</a>
<a class="a-button" href="{% url 'employee' %}">Сотрудники</a>
<a class="a-button" href="{% url 'index' %}">На главуную</a>
</div>
</div>
</form>
按元素提交已经过测试,并且可以与jQuery脚本一起很好地工作。
问题是在提交无效表格后,我的页面带有blah-blah/employee/add_employee/add/
URL。而且,如果我尝试再次提交表单,则我的页面带有blah-blah/employee/add_employee/add/add/
URL,这是不正确的。如何使用blah-blah/employee/add_employee/
URL渲染页面并显示所有错误消息?
这可能是因为您在<form>
模板的sections/add_employee.html
标记中写了relative URL。因此,模板包含以下内容:
<form method="post" action="add/">
...
</form>
您可以在{% url … %}
template tag [Django-doc]中使用URL:
{% url … %}
此外,通常使用same路径来处理GET和POST请求。因此,实际上您可能只是删除了<form method="post" action="{% url 'add-employee-action' %}">
...
</form>
路径。