简体   繁体   English

Django model_mommy模型实例未保存在Ajax测试中

[英]Django model_mommy model instance isn't saved in Ajax test

I'm trying to test an django ajax view that saves a field. 我正在尝试测试保存字段的django ajax视图。 Here's the test: 这是测试:

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!

And here's the view: 这是视图:

@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

When I run the test, I get into the if block, and it can retrieve the comment and submission object, but when it returns to the test at the end, it's like the save never happened. 运行测试时,进入if块,它可以检索注释和提交对象,但是当它最后返回测试时,就像从未发生过保存。

What am I doing wrong here? 我在这里做错了什么?

Try calling sub.refresh_from_db() 尝试调用sub.refresh_from_db()

Changes made to a model instance will only affect the instance being modified. 对模型实例所做的更改只会影响正在修改的实例。 Any existing model instances will not be updated, refresh_from_db will get the changes from the database 任何现有的模型实例都不会更新, refresh_from_db将从数据库中获取更改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM