javascript - Django 和 ajax 错误

标签 javascript jquery python ajax django

测试基本的 ajax 表单,但无法弄清楚为什么会出现错误 init() 收到意外的关键字参数“cost”

我正在尝试遵循此https://realpython.com/blog/python/django-and-ajax-form-submissions/

它在一个字段上工作正常,但在将更多字段添加到表单中时出现错误,所以我怀疑这是一个简单的错误

有什么想法吗?

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

表格

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"
        )

最佳答案

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

此外,您忘记在保存之前检查表单是否确实有效;并且,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

关于javascript - Django 和 ajax 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33316029/

相关文章:

javascript - 使用 src 属性访问脚本标签的内容(包括模板)

jquery - 将 Accordion 小部件合并到 Squarespace 6 中

javascript - 在浏览器选项卡标题中添加一个空格

javascript - 如何设置iframe src属性

javascript - 使用 onClick 添加的表单字段验证 HTML 表单

javascript - 图表如何找到缩放图表的局部边界

javascript - Aurelia 获取客户端中的 "Unhandled rejection"错误

python - 在使用 try 和 except 语句赋值之前引用的局部变量

python - 在python numpy.linalg中使用逆矩阵函数 "inv"

python - 调用 setup.py test 命令时如何告诉 pbr 使用 pytest?