0

我正在尝试测试保存字段的 django ajax 视图。这是测试:

def test_ajax_save_draft(self):
    self.client.force_login(self.test_user) # view requires login
    sub = mommy.make(QuestSubmission, quest=self.quest2)
    draft_comment = "Test draft comment"
    # Send some draft data via the ajax view, which should save it.
    ajax_data = {
        'comment': draft_comment,
        'submission_id': sub.id,
    }

    self.client.post(
        reverse('quests:ajax_save_draft'), 
        data=ajax_data,
        HTTP_X_REQUESTED_WITH='XMLHttpRequest',
    )

    self.assertEqual(draft_comment, sub.draft_text) # sub.draft_text = None, as if the ajax view was never called!

这是视图:

@login_required
def ajax_save_draft(request):
    if request.is_ajax() and request.POST:

        submission_comment = request.POST.get('comment')
        submission_id = request.POST.get('submission_id')

        sub = get_object_or_404(QuestSubmission, pk=submission_id)
        sub.draft_text = submission_comment
        sub.save()

        response_data = {}
        response_data['result'] = 'Draft saved'

        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )

    else:
        raise Http404

当我运行测试时,我进入了 if 块,它可以检索评论和提交对象,但是当它最后返回测试时,就像保存从未发生过一样。

我在这里做错了什么?

4

1 回答 1

2

试着打电话sub.refresh_from_db()

对模型实例所做的更改只会影响正在修改的实例。任何现有的模型实例都不会更新,refresh_from_db将从数据库中获取更改

于 2019-09-15T02:34:49.943 回答