渲染时IntegrityError并且不会采用自动完成值

时间:2012-04-04 21:13:30

标签: python django autocomplete django-views

说明:模板完全呈现自动完成功能......但是一旦我测试它并单击“添加管理器”,它就会返回此错误:

Exception Type:     IntegrityError
Exception Value:    investments_managesfund.manager_id may not be NULL

我无法弄清楚这一点。因为在POST中,它发送csrf_token和manager用户名。

添加资金来资助VIEWs.py:

@login_required
    def add_manager_to_fund(request, fund_id):
        fund = get_object_or_404(Fund, id=fund_id)
        if request.POST['from'] == 'fund':
            if 'omnibox' in request.POST:
                manager = ManagerProfile.objects.get(user=request.user)
                if not ManagesFund.objects.filter(verified=True, fund=fund, manager=manager).exists() and not request.user.is_staff:
                    return HttpResponseRedirect('/profile/fund/' + fund_id + '/')       
                try:
                    mp = ManagerProfile.objects.get(user__username=request.POST['omnibox'])
                    fundManager = ManagesFund.objects.get(manager=mp, fund=fund, from_user=True)
                    if not fundManager.verified:
                        fundManager.verified = True
                        fundManager.save()
                except ObjectDoesNotExist:
                    fundManager, created = ManagesFund.objects.get_or_create(manager__user__username=request.POST['omnibox'], fund=fund, from_user=False)
                    if created:
                        fundManager.save()
        return HttpResponseRedirect('/profile/edit/fund/' + fund_id + '/')

自动完成VIEWs.py:

@login_required
def managers(request):
    managers = ManagerProfile.objects.exclude(user=None)
    result = {}
    for manager in managers:
        result[manager.user.get_full_name()] = manager.user.username
    return HttpResponse(json.dumps(result))

自动完成视图传递用户名,add_manager_to_fund()获取用户名。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

你真的应该重组你的代码。您在try中有两个调用可能会引发ObjectDoesNotExist。我想其中一个必须是,但我们无法分辨哪个。除此之外,您似乎在创建ManagesFund而未指定经理。这就是造成IntegrityError的原因。

如果你需要从用户名中查找经理(看起来你正在尝试)。提前做好get_or_create。