我正在尝试从表单输入中检索数据并将其插入模型中。但我收到此错误:
[错误NoReverseMatch。 “ test-management / test / add_test /”不是有效的视图函数或模式名称。1
包含表单的.html文件。
<form class="form" method="POST" action="{% url 'test-management/test/add_test/' %}">
{% csrf_token %}
<h2>Add Test</h2>
<div class="card-body">
<div class="form-group bmd-form-group">
<div class="input-group">
<p>Name :</p>
<input type="text" class="form-control" name="name" placeholder="Test Name...">
</div>
</div>
<div class="form-group bmd-form-group">
<div class="input-group">
<p>Type :</p>
<input type="text" class="form-control" name="type" placeholder="Test Type...">
</div>
</div>
<div class="form-group bmd-form-group">
<div class="input-group">
<p>Date :</p>
<input type="date" class="form-control" name="date" placeholder="Test Date...">
</div>
</div>
</div>
<div class="modal-footer justify-content-right">
<input type="submit" value="Add">
<a href="." class="btn btn-primary btn-link btn-wd btn-lg" id="close">Close</a>
<a href="#pablo" class="btn btn-primary btn-link btn-wd btn-lg" id="add_new">Add & New</a>
<a href="." class="btn btn-primary btn-link btn-wd btn-lg" id="add">Add</a>
</div>
</form>
该错误可能是由于表单的操作引起的,但我不知道如何纠正它。
urls.py
from test_management.views import (test_list, subject_list, topic_list, question_list, import_question, add_test)
urlpatterns = [
url(r'^test-management/test/add_test/', add_test, name='add_test'),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .models import Test
def add_test(request):
if request.method == 'POST':
test_name = request.POST.get('name')
test_type = request.POST.get('type')
test_date = request.POST.get('date')
test_obj = Test(test_name = test_name, test_type = test_type, test_date = test_date)
test_obj.save()
tests = Test.objects.all()
return render(request, 'test_list.html', {'tests' : tests})
models.py
class Test(models.Model):
# candidate_id = models.ForeignKey('Candidate', on_delete=models.CASCADE)
# admin_id = models.OneToOneField('Admin', on_delete=models.CASCADE)
test_name = models.TextField(max_length=45)
test_type = models.TextField(max_length=45)
test_date = models.DateField()
create_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.test_name
感谢您帮助我解决错误!
答案 0 :(得分:3)
作为url
标签的参数,您应该使用网址名称,而不是正则表达式:
<form class="form" method="POST" action="{% url 'add_test' %}">
代替
<form class="form" method="POST" action="{% url 'test-management/test/add_test/' %}">