Django:" NOT NULL约束失败:users_investment.user_id"错误

时间:2015-11-02 03:35:31

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

我正在开发一个项目,我希望许多用户注册许多offer_funds,所以我添加了一个ManyToManyField。我还希望Django能够自动确定登录的用户并自动填充用户字段,以便我在views.py文件中编写它。但是,在这样做时,我遇到了错误:

  

NOT NULL约束失败:users_investment.user_id

这是我的models.py:

# Not sure if this class is relevant to my question
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    first_name = models.CharField(max_length=24)
    last_name = models.CharField(max_length=24)
    phone_number = models.CharField(max_length=12)
    account_type = models.CharField(max_length=55, choices=ACCOUNT_TYPES)

    def __str__(self):
        return self.user.username

class Investment(models.Model):
    user = models.ManyToManyField(User, blank=True)
    offered_fund = models.ForeignKey(OfferedFunds)
    amount = models.IntegerField(default=0)
    purchase_date = models.DateTimeField(auto_now_add=True)

    def __int__(self):
        return self.offered_fund.fund_name.name

my forms.py:

class InvestmentForm(forms.ModelForm):
    class Meta:
        model = Investment
        fields = ('offered_fund','amount')
        exclude = ['user']

最后,我的views.py:

def of_details(request, slug):
    context_dict = {}

    of = get_object_or_404(OfferedFunds, slug=slug)
    context_dict['of'] = of

    default_state = OfferedFunds.objects.get(slug=slug)
    form = InvestmentForm(request.POST or None, initial={'offered_fund': default_state})

    if form.is_valid():
        instance = form.save(commit=False)
        #instance.user = request.user
        instance.offered_fund = default_state
        instance.save()
        instance.user.add(request.user) # Where the problem started
    context_dict['form'] = form

    return render(request, 'funds/offered-funds-details.html', context_dict)

在我的views.py中,我评论了导致这个问题的一些代码。我无法想象为什么Django会因为用户字段有一个值(非空)而生气。任何人对我如何解决这个问题都有任何想法?我已经没有python manage.py flush来清理我的数据库,但仍然没有运气。谢谢

1 个答案:

答案 0 :(得分:2)

我认为您的问题是您收到anonymous user object而不是完全通过身份验证的用户(如果经过身份验证的用户未登录,Django会自动使用匿名用户填充request.user。匿名用户的id始终为None - 因此数据库约束失败。

您需要首先检查request.user.is_authenticated()是否确保您的用户不是匿名的:

if request.user.is_authenticated():
    instance.user.add(request.user)