我是新的django和ajax,我正试图在用户点击我的html页面中的按钮时向django视图发送帖子请求。当我尝试这样做时,django视图必须返回一个json对象,它给我一个错误说
TypeError: Object of type 'QuerySet' is not JSON serializable
我们如何在django中发送可序列化的Object类型。
Manage_project.html
<form action="{% url 'supervisor:manageproject' %}" id="my_form" method="post">
{% csrf_token %}
<input type="hidden" name="project_id", value={{project.id}}>
<div class="form-group row">
<label for="projectName" class="col-sm-2 col-form-label">Project Name</label>
<div class="col-sm-10">
<input type="text" name="project" class="form-control-plaintext" id="projectName" value="{{project.project_name}}">
</div>
</div>
<h6>Manage the employees list:</h6>
<p>Check the boxes to remove employees:</p>
<div class="container">
<div class="row">
<div class="col-xs-6">
<table class="table">
{% for employee in employees_could_add.all %}
<tr>
<td><input type="checkbox" name="employees_inproject" value="{{employee.id}}"> {{employee}}</td>
</tr>
{% endfor%}
<tr>
<td><button class="btn btn-primary" name="perform" value = "Add" type="submit">Add Employees</button></td>
</tr>
</table>
</div>
<div class="col-xs-6">
<table class="table">
{% for employee in project.employees.all %}
<tr>
<td><input type="checkbox" name="employees" value="{{employee.id}}"> {{employee}}</td>
</tr>
{% endfor%}
<tr>
<td><button class="btn btn-danger" name="perform" value="delete" type="submit">Delete</button></td>
</tr>
</table>
</div>
</div>
</div>
</form>
ajaxcalls.js
$(document).ready(function() {
//alert("hi")
$('#my_form').submit(function(e) { // catch the form's submit event
// e.preventDefault()
//console.log($(this))
$.ajax({ // create an AJAX call...
data: $(this).serialize() + '&perform='+$('button').val(), // get the form data
type: $(this).attr('method'), // GET or POST
dataType: "json",
url: $(this).attr('action'), // the file to call
success: function(data){
console.log(data);
},
error:function(data){
console.log('error')
console.log(data)
}
});
return false;
});
});
views.py
if request.POST['perform'] == 'Add':
employee_ids = request.POST.getlist('employees_inproject')
project_id = request.POST['project_id']
project = Project.objects.filter(id=project_id)[0]
for e_id in employee_ids:
emp = Profile.objects.filter(id=e_id)[0]
project.employees.add(emp)
employees = Profile.objects.all()
employees_inproject = project.employees.all()
employees_could_add = employees.difference(employees_inproject)
print(1, employees_could_add)
data = {
'employees_could_add' : employees_could_add,
'project' : project
}
print(data['employees_could_add'])
#return JsonResponse( model_to_dict(data) )
return HttpResponse(json.dumps({'data': data}), content_type="application/json")
堆栈跟踪
`[27/Mar/2018 11:41:14] "GET /supervisor/manageproject/?project_id=10& manage_project=Manage+Project HTTP/1.1" 200 2902
<QueryDict: {'csrfmiddlewaretoken': ['Fawz6ZbzuvWyPGGcLqDccOEGWwmZM6TsoBvUenAuEFEkXWkk1Ra6f0d1uvzedV6Z'], 'project_id': ['10'], 'project': ['Project P'], 'employees_inproject': ['10'], 'perform': ['Add']}>
Add
1 <QuerySet [<Profile: uday>, <Profile: sandeep>]>
<QuerySet [<Profile: uday>, <Profile: sandeep>]>
Internal Server Error: /supervisor/manageproject/
Traceback (most recent call last):
File "C:\Users\team\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Users\team\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\team\AppData\Local\Programs\Python\Python36-32 \lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\team\Desktop\django\TMS_1\TMS_1\TMS\supervisor\views.py", line 131, in manageproject_view
return HttpResponse(json.dumps({'data': data}), content_type="application/json")#({'data' : list(data)})
File "C:\Users\team\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Users\team\AppData\Local\Programs\Python\Python36-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\team\AppData\Local\Programs\Python\Python36-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\team\AppData\Local\Programs\Python\Python36-32\lib\json\encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'QuerySet' is not JSON serializable
[27/Mar/2018 11:41:16] "POST /supervisor/manageproject/ HTTP/1.1" 500 15895`
编辑:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
emp_name = models.CharField(max_length=500)
gender = models.CharField(max_length=10)
job_position = models.CharField(max_length=20)
salary = models.IntegerField()
def __str__(self):
return self.emp_name
class Project(models.Model):
project_name = models.CharField(max_length=200)
employees = models.ManyToManyField(Profile)
def __str__(self):
return self.project_name
答案 0 :(得分:0)
data = {
'employees_could_add' : employees_could_add.values(),
'project' : project.values()
}
使用此