1

I'm using Django 1.11

I have a business model.

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

When I run python3 manage.py makemigration business It gives

You are trying to add a non-nullable field 'user' to business without a default;

I want to set this field to use the logged in user id as foreign key by default.

How to use Auth user id as default for user specific data record?

Edit 2

Business create view 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')
Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

2 Answers2

3

You need to provide the default user in case of ForeignKey coz that field is non nullable.

user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)

Update After Comment

def form_valid(self, form):
    form.instance.user = self.request.user
    return super(BusinessCreate, self).form_valid(form)
Astik Anand
  • 12,757
  • 9
  • 41
  • 51
1

There's no way to do that. The current user only makes sense in the context of a http request. Migrations cannot rely on that context. You must instead pass the current user explicitly when creating new Business instances in a view function.

Håken Lid
  • 22,318
  • 9
  • 52
  • 67