我正在尝试使用模型表单将数据从ajax调用保存到数据库。我认为问题是表单无效,因为代码运行时会打印test
。
这是基于类视图的Post部分
def post(self, request):
set_name = request.POST.get('set_name', None)
form = SetCreate(request.POST)
if form.is_valid():
instance = form.save(commit = False)
instance.name = set_name
teacher = Teacher.objects.get(user = request.user)
instance.teacher = teacher
instance.save()
else:
print('test')
这是表格:
class SetCreate(forms.ModelForm):
class Meta:
model = Set
fields = ('name',
'teacher',
'students')
这是AJAX:
function send(){
var set_name = $('#class_name').val();
//console.log(ids)
//console.log(set_name)
var url = window.location.pathname;
ids = JSON.stringify(ids)
$.ajax({
method: "POST",
url: url,
data: {
'set_name': set_name,
'student_ids': ids,
},
dataType: 'json',
success: function (data) {
//location.href = data.url;//<--Redirect on success
}
});
}
感谢您的帮助!