我正在使用Django 1.11
我有一个商业模式。
class Business(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE)
class Meta:
verbose_name = 'business'
verbose_name_plural = 'businesses'
db_table = 'businesses'
def __str__(self):
return self.name
当我跑python3 manage.py makemigration business
时,它会给出
You are trying to add a non-nullable field 'user' to business without a default;
我想将此字段设置为默认使用登录的用户ID作为外键。
如何将Auth用户ID用作特定于用户的数据记录的默认值?
编辑2
商家创建视图 views.py
class BusinessCreate(CreateView):
model = Business
fields = ['name', 'business_type']
def get_context_data(self, **kwargs):
data = super(
BusinessCreate,
self
).get_context_data(**kwargs)
if self.request.POST:
data['business_address'] = BusinessAddressFormSet(self.request.POST)
else:
data['business_address'] = BusinessAddressFormSet()
return data
def form_valid(self, form):
context = self.get_context_data()
business_address = context['business_address']
with transaction.atomic():
self.object = form.save()
if business_address.is_valid():
business_address.instance = self.object
business_address.save()
return super(BusinessCreate, self).form_valid(form)
def get_success_url(self):
messages.success(self.request, 'Business Added Successfully')
return reverse('business:list')
答案 0 :(得分:2)
如果ForeignKey表示该字段为non nullable
,则需要提供默认用户。
user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
评论后更新
def form_valid(self, form):
form.instance.user = self.request.user
return super(BusinessCreate, self).form_valid(form)
答案 1 :(得分:1)
没有办法做到这一点。当前用户仅在http请求的上下文中有意义。迁移不能依赖于该上下文。在视图函数中创建新的Business
实例时,必须显式传递当前用户。