我有一个django代码,该代码允许用户使用javascript函数将图书添加到列表中,一旦用户单击该按钮,该脚本就可以处理ajax请求。我正在使用BootStrap 4
问题在于,一旦用户单击按钮,控制台就会显示以下错误:
文件“ C:\ Users \ LTGM〜1 \ Desktop \ CRUDDJ〜1 \ env \ lib \ site-packages \ widget_tweaks \ templatetags \ widget_tweaks.py”,第163行,位于render_field 提高TemplateSyntaxError(error_msg +“:%s”%对) django.template.exceptions.TemplateSyntaxError:'render_field'标签需要一个表单字段,其后是属性和值的列表,形式为attr =“ value”:class
from django.contrib import admin
from django.urls import path
from .views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('books/',book_list, name = "book_list"),
path('books/create/',book_create, name = "book_create"),
]
from django.shortcuts import render
from books.models import Book
from books.forms import BookForm
from django.http import JsonResponse
from django.template.loader import render_to_string
def book_list(request):
books = Book.objects.all()#list all records
return render(request, './book_list.html',{'books':books})
def book_create(request):
form = BookForm()
context= {'form':form}
html_form = render_to_string('./partial_book_create.html',context,request=request,)
return JsonResponse({'html_form':html_form})
{% load widget_tweaks %}
<form method="post">
{% csrf_token %}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-lable="Close">
<span aria-hidden = "true">×</span>
</button>
<h4 class="modal-title">Create a new book</h4>
</div>
<div class="modal-body">
{% for field in form %}
<div class="form-group{% if field.errors %} has-error{% endif %}">
<label for ="{{ field.id_for_lable }}">{{ field.lable }}</label>
{% render_field field class ="form-control" %}
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
</div>
<div class="modal-footer">
<button type="buuton" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Create book</button>
</div>
</form>
$(function(){
$(".js-create-book").click(function(){
$.ajax({
url:"/books/create/",
type:"get",
dataType:"json",
beforeSend:function(){
$("#modal-book").modal("show");
},
success: function(data){
$("#modal-book .modal-content").html(data.html_form);
}
});
});
});
我不明白这是什么以及如何解决该错误
我是 widget_tweaks 和 render_to_string
的新手我将不胜感激。
答案 0 :(得分:1)
您的render_field标签中=
之前有多余的空格。
{% render_field field class="form-control" %}