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'>×</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"
)
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