Setting user_id while saving to view - Django

I need to install the user creating the message in the add window:

@login_required def add(request): if request.method == 'POST': form = BusinessForm(request.POST) form.user_id = request.user.id if form.is_valid(): form.save() return HttpResponseRedirect(reverse('listing.views.detail'), args=(f.id)) else: form = BusinessForm() return render_to_response('business/add.html', {'form':form}, context_instance=RequestContext(request)) 

I assign the user ID form.user_id = request.user.id , but when saving it still gives me the error Column user_id cannot be null

Am I doing something wrong? Thanks

EDIT:

I exclude the user from the form in the model:

 class BusinessForm(ModelForm): class Meta: model = Business exclude = ('user',) 

Could this be the cause of the problem? How can I get around this?

EDIT 2:

Edited the BusinessForm () class, as suggested, but did not work:

 class BusinessForm(ModelForm): class Meta: model = Business exclude = ('user',) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) return super(BusinessForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): kwargs['commit']=False obj = super(BusinessForm, self).save(*args, **kwargs) if self.request: obj.user = self.request.user obj.save() 

Business model

 class Business(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User, unique=False) description = models.TextField() category = models.ForeignKey(Category) address = models.CharField(max_length=200) phone_number = models.CharField(max_length=10) website = models.URLField() image = models.ImageField(upload_to='business_pictures',blank=True) 
+4
source share
2 answers

You do not need to use init or save overrides.

You simply set an attribute in your form, and the form does nothing with it. It does not magically behave like an instance of a model (your form will not have the user_id attribute).

Since your form is ModelForm , you can simply call it with commit=False to get an unsaved instance, set the user, then call save on the instance.

  if request.method == 'POST': form = BusinessForm(request.POST) if form.is_valid(): business = form.save(commit=False) business.user = request.user business.save() 
+11
source

this seems to be exactly what you are looking for.

0
source

Source: https://habr.com/ru/post/1387969/


All Articles