【问题标题】:'Undefined' value when outputting value of a django modelform field输出 django modelform 字段值时的“未定义”值
【发布时间】:2016-05-22 11:12:33
【问题描述】:

我正在从LocForm 记录city 字段的值,但在输入一个值并点击提交按钮后,$('#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: (表单)

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 函数内的 document.ready 处理程序,因此您可以将其删除。其次,您的 HTML 代码中的哪个位置是 #post_text 元素?
  • $(document).ready 导致了您的问题。 @rory-mccrossan OP 正在为表单类中的字段设置自定义 ID post-text
  • @RoryMcCrossan 这是我关于堆栈溢出的第一个问题,所以感谢您的编辑:) 我已经删除了 document.ready 但仍然没有效果。 #post_textLocForm 内的元素的 ID,我已在 &lt;form&gt; 标记内导入了 {{ form|crispy }} 。我还添加了我的 views.py 以提供更多详细信息。

标签: jquery ajax django


【解决方案1】:

您的代码有几点需要审查:

  • $(document).ready()的用法:

您当前正在函数 create_post() 中使用准备好的文档。在您的情况下,这没有用。您需要确保您的文档已准备好捕捉您的提交事件,因此应该在此之前完成。

function create_post() {
    $(document).ready(function(){ ... });
};

成为:

$(document).ready(function(){
    $('#post-form').on('submit', function(event) {
          create_post();
    });
});
  • 您的 id “post-text” 的用法

根据您提供的代码,我们无法确定 post-text 是否正确使用。 您应该通过键入以下内容在控制台中检查此元素的可访问性:

$('#post-text');

然后

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

【讨论】:

  • $('#post-text'); 给出这个输出:Object { context: HTMLDocument → 127.0.0.1:8000, selector: "#post-text" }$('#post-text').val(); 给出这个输出:undefined。我也删除了document.ready,但仍然没有效果。
  • 在这种情况下,听起来你有多个元素,而 idpost-text 应该只有一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 2020-08-09
  • 2013-09-26
  • 2013-02-12
相关资源
最近更新 更多