[英]Django: "NOT NULL constraint failed: users_investment.user_id" Error
I am working on a project where I would like for many users to register for many offered_funds, so I added a ManyToManyField.我正在从事一个项目,我希望许多用户注册许多提供的资金,所以我添加了一个 ManyToManyField。 I also wanted Django to automatically figure out which user was logged in and auto fill the user field so I wrote it in my views.py file.
我还希望 Django 自动找出哪个用户登录并自动填充用户字段,所以我将它写在我的 views.py 文件中。 However upon doing so, I came across the error:
但是在这样做时,我遇到了错误:
NOT NULL constraint failed: users_investment.user_id
NOT NULL 约束失败:users_investment.user_id
Here is my models.py:这是我的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:我的forms.py:
class InvestmentForm(forms.ModelForm):
class Meta:
model = Investment
fields = ('offered_fund','amount')
exclude = ['user']
and finally, my views.py:最后,我的 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)
In my views.py I have commented the bit of code that lead to this issue.I cant imagine why Django would be mad that the user field has a value (not null).在我的 views.py 中,我评论了导致这个问题的代码。我无法想象为什么 Django 会因为用户字段有一个值(非空)而生气。 Anyone have any ideas on how I can solve this?
有人对我如何解决这个问题有任何想法吗? I've don't a python manage.py flush to clear my database already, and still no luck.
我已经没有 python manage.py flush 来清除我的数据库,但仍然没有运气。 Thanks
谢谢
I think your issue is that you are receiving an anonymous user object instead of a fully authenticated user (Django will automatically populate request.user
with an anonymous user if an authenticated user isn't logged in. The id
for an anonymous user is always None
- hence the database constraint fails.我认为您的问题是您收到的是匿名用户对象而不是完全经过身份验证的用户(如果经过身份验证的用户未登录,Django 将自动使用匿名用户填充
request.user
。匿名用户的id
始终为None
- 因此数据库约束失败。
You need to make sure that your user isn't anonymous by checking whether request.user.is_authenticated()
first:您需要首先检查
request.user.is_authenticated()
是否确保您的用户不是匿名的:
if request.user.is_authenticated():
instance.user.add(request.user)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.