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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号