weixin_33708432 2015-10-24 08:18 采纳率: 0%
浏览 46

Django和Ajax错误

Testing a basic ajax form and can't figure out why i'm getting the error init() got an unexpected keyword argument 'cost'

I'm trying to follow this https://realpython.com/blog/python/django-and-ajax-form-submissions/

It worked fine with one field, but getting the error when adding in more fields into the form, so i suspect it's a simple mistake

any thoughts?

The View

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

The form

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

------------- EDIT ------------------
I think i've made some progress, i have the values coming in the the java script but post.save() isn't the right thing to use here, any thoughts

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"
        )
  • 写回答

1条回答 默认 最新

  • csdn产品小助手 2015-10-24 08:24
    关注

    That's not how you initialize forms at all. As the error says, the don't expect keyword arguments for the field values.

    Also, you forgot to check whether the form was actually valid before saving; and, the pk is on the result of form.save, not on the form itself.

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办