=== html === 一个项目有很多费用,而我的下拉列表显示该项目的所有费用。它还将允许用户从下拉列表中选择其他值,然后单击“更新”按钮。它不会给出任何错误,但是不会将下拉列表中的选定值保存到数据库中。 任何帮助将不胜感激。
<select id="select_dropdown">
{% if project.id and emp.id %}
{% for expense in emp.expense_set.all %}
{% if expense.city %}
<option value="{{expense.id}}" selected="selected">{{expense.expense_type}}</option>
{% else %}
<option value="{{expense.id}}">{{expense.expense_type}}</option>
{% endif %}
{% endfor %}
{% endif %}
</select>
==== js =======
$("#save_change").click(function(e) {
e.preventDefault();
console.log("update fucntion is working!");
var value = $("#select_dropdown").find(":selected").val();
var text = $("#select_dropdown option:selected").text();
var project_id = $("#project_id").val();
var emp_id = $("#emp_id").val();
console.log(emp_id);
$.ajax({
url: "{% url 'update_form' %}",
//url: "/ajax/update_form/",
method: "POST",
data: {
"value": value,
"text": text,
"project_id": project_id,
"emp_id": emp_id,
csrfmiddlewaretoken: '{{ csrf_token }}',
},
dataType: "json",
success: function(data){
console.log("success");
console.log(data);
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
});
return false;
=== views.py ===
@csrf_exempt
def update_form(request):
if request.method == "POST" and request.is_ajax():
expense_id = request.POST.get('value')
expense_type = request.POST.get('text')
project_id = request.POST.get('project_id')
emp_id = request.POST.get('emp_id')
project_id = request.POST.get('project_id')
for exp in expense:
exp.expense_type = expense_type
exp.save()
data = serializers.serialize("json", expense)
return HttpResponse(data, content_type="application/json")