Issue
Im using Django and trying to get a response by using AJAX. I have two forms, the first one works just fine. Though I use the same logic in my second form handling it does not work well.
models.py
class AskMe(models.Model):
name = models.CharField(max_length=1000)
views.py
def AskMeQ(request):
if request.method == POST:
name = request.POST['name']
AskMe.objects.create(name=name)
urls.py
url('r^askmeQ/$', views.AskMeQ)
ajax logic
$('.former').on('submit', '.ajaxform', function(event) {
event.preventDefault();
$.ajax({
url: '/askmeQ/',
type: 'POST',
data: {name: $('#name').val(),
csrfmiddlewaretoken: csrftoken
}
})
.done(function() {
console.log("success");
$('.formset').slideToggle(400)
});
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
ERROR
Traceback:
File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__
77. list_ = super().__getitem__(key)
During handling of the above exception ('name'), another exception occurred:
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pc/Django_Projects/vikas/vikas/views.py" in askmeQ
40. name = request.POST['name']
File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__
79. raise MultiValueDictKeyError(key)
Exception Type: MultiValueDictKeyError at /askmeQ/
Exception Value: 'name'
The logic I use above used to work in all the previous forms, but here it throws me an error.
The SQLite3 table has been created as projectname_model.name
.
How can I correct this?
Solution
It seems that the name was not posted with the request. Due to which, you name = request.POST['name']
will throw an error since the key won't be part of the POST
dict.
To correct this, alter your code to:
def AskMeQ(request):
if request.method == POST:
name = request.POST.get('name')
if name:
AskMe.objects.create(name=name)
# else:
# error condition handling
Answered By - Anshul Goyal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.