Jquery 输出django modelform字段值时的“未定义”值

Jquery 输出django modelform字段值时的“未定义”值,jquery,ajax,django,Jquery,Ajax,Django,我正在从LocForm记录city字段的值,但在输入值并点击submit按钮$'post-text'后,val返回undefined作为其值。控制台输出为: form submitted! create post is workin undefined 以下是代码的主要部分: views.py: def home(request): form = LocForm() context = { "form" : LocForm } return re

我正在从LocForm记录city字段的值,但在输入值并点击submit按钮$'post-text'后,val返回undefined作为其值。控制台输出为:

form submitted!
create post is workin
undefined
以下是代码的主要部分:

views.py:

def home(request):
    form = LocForm()
    context = {
        "form" : LocForm
    }
    return render(request, 'home.html', context) 
forms.py:form

class LocForm(ModelForm):
    class Meta:
        model = Location
        fields = ['city']
        labels = {
            'city': ('Where do you want to live'),
        }
        widgets = {
            'city': forms.TextInput(attrs = { 
                'id': 'post-text', 
                'required': True
            }),
        }
main.js:主javascript文件

$('#post-form').on('submit', function(event) {
    event.preventDefault();
    console.log("form submitted!")
    create_post();
});

function create_post() {  //AJAX call
    console.log("create post is workin");
    console.log($('#post-text').val());
    });
};
来自模板的表单html代码:

<form id="post-form" action="/create_post/" method="post" style="text-align: center">
    {% csrf_token %}
    {{ form|crispy }}
    <input class="btn btn-lg btn-primary" type="submit" value="submit">
</form>

代码中有几点需要检查:

$document.ready的用法: 您当前正在使用函数create_post中的document ready。这在你的情况下是没有用的。您需要的是确保您的文档已准备好捕获提交事件,因此应该在提交之前完成

function create_post() {
    $(document).ready(function(){ ... });
};
成为:

$(document).ready(function(){
    $('#post-form').on('submit', function(event) {
          create_post();
    });
});
id post文本的使用 根据您提供的代码,我们无法真正确定post文本是否正确使用。 您应该通过键入以下内容来检查控制台中此元素的可访问性:

$('#post-text');
然后

$('#post-text').val();

首先,在create_post函数中不需要document.ready处理程序,这样就可以删除它。其次,在HTML代码中,post_文本元素在哪里?是$document.ready导致了您的问题@rory mccrossan OP正在为form类中的字段设置post文本的自定义id。@RoryMcCrossan这是我关于堆栈溢出的第一个问题,因此感谢您的编辑:我已经删除了document.ready,但仍然无效。post|text是LocForm内部元素的id,我已经用{form | crispy}在标记内部导入了它。我还添加了my views.py以提供更多细节;正在提供以下输出:对象{context:HTMLDocument→ 127.0.0.1:8000,选择器:post-text}和$'post-text'.val;正在提供此输出:未定义。我还删除了document.ready,但仍然没有效果。在这种情况下,听起来您有多个id为post text的元素,而实际上应该只有一个。