【问题标题】:Django and ajax errorDjango 和 ajax 错误
【发布时间】:2016-01-23 19:09:16
【问题描述】:

测试一个基本的 ajax 表单,但不知道为什么会出现错误 init() 得到了一个意外的关键字参数 'cost'

我正在尝试关注这个https://realpython.com/blog/python/django-and-ajax-form-submissions/

它在一个字段上运行良好,但是在向表单中添加更多字段时出现错误,所以我怀疑这是一个简单的错误

有什么想法吗?

观点

def create_post(request):
    if request.method == 'POST':
        post_name = request.POST.get('the_name')
        post_cost = request.POST.get('the_cost')
        response_data = {}

        post = CostsForm(name=post_name, cost=post_cost)
        post.save()

        response_data['result'] = 'Create post successful!'
        response_data['postpk'] = post.pk
        response_data['name'] = post.name
        response_data['cost'] = post.cost
        response_data['created'] = post.created.strftime('%B %d, %Y %I:%M %p')

        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )
    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )

Javascript

// AJAX for posting
function create_post() {
    console.log("create post is working!") // sanity check
    $.ajax({
        url : "create_post/", // the endpoint
        type : "POST", // http method
        data : { the_name : $('#post-name').val(), the_cost : $('#post-cost').val()}, // data sent with the post request
        // handle a successful response
        success : function(json) {
            $('#post-name').val(''), $('#post-cost').val(''); // remove the value from the input
            console.log(json); // log the returned json to the console
            $("#talk").prepend("<li id='post-"+json.postpk+"'><strong>"+json.name+"</strong> - <em> "+json.owner+"</em> - <span> "+json.created+
                "</span> - <a id='delete-post-"+json.postpk+"'>delete me</a></li>");
            console.log("success"); // another sanity check
        },
        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

形式

class SundayForm(forms.ModelForm):
    class Meta:
        model = Sunday
        fields = ['name','owner']
        widgets = {
            'name': forms.TextInput(
                attrs={'id': 'post-name', 'required': True, 'placeholder': 'Sunday Name..'}
                ),
            'owner': forms.TextInput(
                attrs={'id': 'post-owner','required': True, 'placeholder': 'Sunday Owner..'}
            )
        }


class CostsForm(forms.ModelForm):
    class Meta:
        model = Costs
        fields = ['name', 'cost']
        widgets = {
            'name': forms.Select(
                attrs={'id': 'post-name', 'required': True}
                ),
            'cost': forms.TextInput(
                attrs={'id': 'post-cost', 'required': True, 'placeholder': 'Sunday Cost'}
            )
        }

---------- 编辑 ------
我想我已经取得了一些进展,我在 java 脚本中有值,但是 post.save() 在这里使用不是正确的,任何想法

def create_post(request):
    if request.method == 'POST':
        post_name = request.POST.get('the_name')
        post_cost = request.POST.get('the_cost')
        response_data = {}

        post = Costs(name_id=post_name, cost=post_cost)
        post.save()

        form = CostsForm(request.POST)
        if form.is_valid():
            post = form.save()
            response_data['result'] = 'Create post successful!'
            response_data['postpk'] = post.pk
            response_data['name'] = post.name_id
            response_data['cost'] = post.cost
            response_data['created'] = post.created.strftime('%B %d, %Y %I:%M %p')

        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )
    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )

【问题讨论】:

    标签: javascript jquery python ajax django


    【解决方案1】:

    这根本不是您初始化表单的方式。正如错误所说,不要期望字段值的关键字参数。

    另外,您忘记在保存之前检查表单是否实际有效;而且,pk 是 form.save 的结果,而不是表单本身。

    if request.method == 'POST':
        post = CostsForm(request.POST)
        if form.is_valid():
            post = form.save()
            response_data[postpk] = post.pk
            ...
        else:
            # do something with form.errors; probably send them back in response_data
    

    【讨论】:

    • 感谢@Daniel Roseman,我想我已经取得了一些进展,并将两者都添加了......我得到了价值观,但仍然有点卡住
    猜你喜欢
    • 2013-08-05
    • 2011-10-08
    • 2012-05-28
    • 2011-11-30
    • 2011-09-04
    • 2017-12-23
    • 2011-12-08
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多