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')

2 Answers 2

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)
4
  • 2
    if user with pk=1 is not exists?
    – user8060120
    Sep 21, 2017 at 12:00
  • 1
    I want to set default to user id who is logged in
    – Anuj TBE
    Sep 21, 2017 at 12:02
  • You can not do that, for that you need request variable which can be accessed in model. Sep 21, 2017 at 12:05
  • @AnujTBE, Feel privileged to help you. Thanks a lot. Sep 21, 2017 at 12:29
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.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.