Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting user_id when saving in view - Django

I need to set the user that is creating the post in the add view:

@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 an error Column user_id cannot be null

Am I doing something wrong? Thanks

EDIT:

I am excluding the user from the form in the model:

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

Could that be causing the problem?? How can I work around this?

EDIT 2:

Edited my 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)
like image 734
AlexBrand Avatar asked Dec 17 '22 05:12

AlexBrand


1 Answers

You don't have to use init or save overrides for this.

You're just setting an attribute on your form and the form doesn't do anything with it. It doesn't magically behave like a model instance (your form wouldn't have a user_id attribute).

Since your form is a ModelForm, you can simply call save on it with commit=False to get the 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()
like image 193
Yuji 'Tomita' Tomita Avatar answered Dec 28 '22 07:12

Yuji 'Tomita' Tomita