Django POST请求通过ajax?

时间:2018-04-16 14:13:07

标签: python ajax django django-models django-forms

我正在尝试通过ajax向django后端提交值,但我一直收到此错误Advice matching query does not exist,但它确实存在于数据库中。我不知道我做错了什么。 这是我的AJAX请求代码片段:

$.ajax({
    type: 'POST',
    url: '{% url "recsystem:saveData" %}',
    data: {
        'csrfmiddlewaretoken' : "{{  csrf_token  }}",
        'ansId' : data.ansId,
        'queTitle': data.queTitle,
        'queText' : data.queText,
        'desc': data.desc,
        'optionType': data.optionType,
        'anstextArray': data.anstextArray,
        'ansAdvicesArray': data.ansAdvicesArray
     },
     success: function(data){
         console.log(data);
     },
     error: function(error){
         console.log(error);
     }
});

这是我在Django视图中保存此数据的函数。

def saveData(request):

if request.method =='POST' and request.is_ajax():    
    q = Question()
    q.question_title = request.POST['queTitle']
    q.question_text = request.POST['queText']
    q.description = request.POST['desc']
    q.options_type = request.POST['optionType']
    q.save()

    if not request.POST['ansId'] is None:
        followup = FollowUp()
        followup.description = ""
        followup.answer = Answer.objects.get(pk=request.POST['ansId'])
        followup.question = q
        followup.save()

    if not request.POST.get('anstextArray', False) is None:
        answers = []
        advices = []
        answers = request.POST.get('anstextArray', False)
        advices = request.POST.get('ansAdvicesArray', False)
        for an, ad in zip(itertools.repeat(answers), itertools.repeat(advices)):
            adviceList = []
            adviceList = ad
            answer = Answer()
            answer.question = q
            answer.answer_text = an

            for id in itertools.repeat(adviceList):
                answer.advice = Advice.objects.get(pk=id)

            answer.save()

    return JsonResponse({'result':'ok'})

else:
    return JsonResponse({'result':'nok'})

这是我的数据库模型:

class Question(models.Model):
  question_title = models.CharField(max_length = 250)
  question_text = models.TextField(max_length = 3000)
  description = models.TextField(max_length = 3000)
  options_type = models.CharField(max_length = 250)

  def __str__(self):
         return self.question_title

class Advice(models.Model):
  advice_label = models.TextField(max_length = 2000)
  advice_text = models.TextField(max_length = 3000)
  time_stamp = models.TextField( default=timezone.now, max_length= 2000)


  def __str__(self):
        return self.advice_label


class Answer(models.Model):
  question = models.ForeignKey(Question, on_delete=models.CASCADE)
  answer_text = models.CharField(max_length = 250)
  advices = models.ManyToManyField(Advice)
  def __str__(self):
         return self.answer_text


class FollowUp(models.Model):
  description = models.CharField(max_length = 250)
  answer = models.ForeignKey(Answer, on_delete=models.CASCADE)
  question = models.ForeignKey(Question, on_delete=models.CASCADE)

问题出在某处,我试图将数组保存为列表,然后迭代它。

Traceback: 

File "C:\Users\habib\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\django\core\handlers\exception.py" in inner
41.             response = get_response(request)

File "C:\Users\habib\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\django\core\handlers\base.py" in _get_response
187.                 response = self.process_exception_by_middleware(e, 
request)

File "C:\Users\habib\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\django\core\handlers\base.py" in _get_response
185.                 response = wrapped_callback(request, *callback_args, 
**callback_kwargs)

File "C:\Users\habib\Desktop\recommender\src\recsystem\views.py" in saveData
177.                     answer.advice = Advice.objects.get(pk=id)

File "C:\Users\habib\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\django\db\models\manager.py" in manager_method
 85.                 return getattr(self.get_queryset(), name)(*args, 
**kwargs)

File "C:\Users\habib\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\django\db\models\query.py" in get
380.                 self.model._meta.object_name

Exception Type: DoesNotExist at /recsystem/saveData/
Exception Value: Advice matching query does not exist.

2 个答案:

答案 0 :(得分:1)

您的问题对我来说有点不清楚,但是当您尝试使用Model.objects.get()方法从db检索不存在的数据时,会发生这种错误。

我怀疑你的问题在于代码。

Advice.objects.get(pk=id)

因此,为了确保这一点,调试此点以获取id,然后手动检入db是否存在与该id相关联的数据。

您也可以使用其他方法从数据库中检索数据,例如get_object_or_404(Advice, pk=id)甚至filter()方法可以帮助您。

答案 1 :(得分:0)

异常类型:DoesNotExist表示您根据pk进行过滤,但后面的数据是" ="不是身份证。 确保这个itertools.repeat(adviceList)是一个ID列表。