使用 render_to_string 库无效

using render_to_string library is not working

我有一个 Django 代码,允许用户使用 javascript 函数将书籍添加到列表中,一旦用户单击按钮,该函数就会处理 ajax 请求。我正在使用 BootStrap 4

问题是,一旦用户单击按钮,控制台就会显示以下错误:

File "C:\Users\LTGM~1\Desktop\CRUDDJ~1\env\lib\site-packages\widget_tweaks\templatetags\widget_tweaks.py", line 163, in render_field raise TemplateSyntaxError(error_msg + ": %s" % pair) django.template.exceptions.TemplateSyntaxError: 'render_field' tag requires a form field followed by a list of attributes and values in the form attr="value": class

urls.py

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"),
]

views.py

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})

partial_book_create.html

{% 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">&times;</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>

books.js

$(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_tweaksrender_to_string

的新手

我将不胜感激。

您的 render_field 标签中的 = 之前有一个额外的 space。

{% render_field field class="form-control" %}