null value in column violates not-null constraint

309 views
Skip to first unread message

Ismail Sarenkapic

unread,
May 25, 2017, 7:19:56 AM5/25/17
to Django users
Hi, I'm trying to create a digital marketplace site where users will be able to register and submit their products.
I created the Product model and connected it with User with foreign key.Everything seems  to be alright, but when I submit my product i get the following error:

null value in column violates not-null constraint
 it looks like relation between product and user is not properly configured(regardless of my mixin that is suppose to handle it)
__________________________________________________________________________________________________________________________________
note that I'm using:

database:postgresql

allauth(for user registration)
__________________________________________________________________________________________________________________________________

________
models.py

from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.core.urlresolvers import reverse
from django.utils.text import slugify
# Create your models here.



class Product(models.Model):
   seller = models.ForeignKey(settings.AUTH_USER_MODEL)
   #user = models.OneToOneField(settings.AUTH_USER_MODEL)
   # user = models.ForeignKey(settings.AUTH_USER_MODEL)
   # managers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="managers_products", blank=True)
   title = models.CharField(max_length=30) #owiuerpoajsdlfkjasd;flkiu1p3o4u134123 ewjfa;sd
   slug = models.SlugField(blank=True, unique=True)
   description = models.TextField()
   price = models.DecimalField(max_digits=100, decimal_places=2, default=9.99, null=True,) #100.00


   def __unicode__(self): #def __unicode__(self):
      return self.title
_______
views.py


from django.views import View
from django.views.generic import (
                CreateView,
                )

from .forms import ProductModelForm
from .mixins import FormUserNeededMixin
# Create your views here.


class ProductCreateView(FormUserNeededMixin, CreateView):
    form_class = ProductModelForm
    template_name = 'create_view.html'
_______
forms.py

from django import forms

from django.utils.text import slugify

from .models import Product


class ProductModelForm(forms.ModelForm):
   class Meta:
      model = Product
      fields = [
         "title",
         "description",
         "price",
      ]
________
mixins.py

from django import forms
from django.forms.utils import ErrorList

class FormUserNeededMixin(object):

     def form_valid(self, form):
        if self.request.user.is_authenticated():
            form.instance.user = self.request.user
            return super(FormUserNeededMixin, self).form_valid(form)
        else:
            form._errors[forms.forms.NON_FIELD_ERRORS] = ErrorList(["User must be logged in to continue."])
            return self.form_invalid(form)






Melvyn Sopacua

unread,
May 25, 2017, 1:13:39 PM5/25/17
to django...@googlegroups.com

On Thursday 25 May 2017 04:19:56 Ismail Sarenkapic wrote:

> Hi, I'm trying to create a digital marketplace site where users will

> be able to register and submit their products.

> I created the Product model and connected it with User with foreign

> key.Everything seems to be alright, but when I submit my product i

> get the following error:

>

> null value in column violates not-null constraint

> it looks like relation between product and user is not properly

> configured(regardless of my mixin that is suppose to handle it)

 

> class Product(models.Model):

> seller = models.ForeignKey(settings.AUTH_USER_MODEL)

> #user = models.OneToOneField(settings.AUTH_USER_MODEL)

> # user = models.ForeignKey(settings.AUTH_USER_MODEL)

> # managers = models.ManyToManyField(settings.AUTH_USER_MODEL,

> related_name="managers_products", blank=True) title =

> models.CharField(max_length=30)

> #owiuerpoajsdlfkjasd;flkiu1p3o4u134123 ewjfa;sd slug =

> models.SlugField(blank=True, unique=True)

> description = models.TextField()

> price = models.DecimalField(max_digits=100, decimal_places=2,

> default=9.99, null=True,) #100.00

 

 

> class ProductModelForm(forms.ModelForm):

> class Meta:

> model = Product

> fields = [

> "title",

> "description",

> "price",

> ]

 

seller is not in the model form and FormUserNeededMixin doesn't change that. The user field is commented out in your model so this error and the quoted code are not in sync.

 

But it could also be the slug. Without more of the error message it's hard to tell.

--

Melvyn Sopacua

Muhammad M

unread,
May 25, 2017, 2:00:08 PM5/25/17
to django...@googlegroups.com
Ismail,

You don't seem to be handling the value for Product.slug anywhere, either in the model or the view. 

You can fix the slug issue by overriding the Product model's save () method like this: 

def save (self, *args, **kwargs):
     if not self.slug:
        self.slug = slugify(self.title)
    super(Product, self).save (*args, **kwargs)

This way, you can automatically generate the value of the slug field when a valid form is submitted. 

If you are still having problems, please, do let us know.

All the best.

Sincerely,
Muhammad 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0d2d44eb-a2df-4f00-8d60-3f163ed72c9b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ismail Sarenkapic

unread,
May 25, 2017, 4:53:20 PM5/25/17
to Django users
Tnx ,
I know that i can manually select the user, but i want it to be automatic-with current user to add the product

Ismail Sarenkapic

unread,
May 25, 2017, 4:55:00 PM5/25/17
to Django users
Tnx.
The slug is not important here.
The main question is how do I add product  with current user!
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

Vijay Khemlani

unread,
May 25, 2017, 5:19:11 PM5/25/17
to django...@googlegroups.com
"form.instance.user"

should be

"form.instance.seller"

But the "null value in column" error could also apply to any of the
non-nullable fields in your Product model that are not set by the time
you save the instance.

On 5/25/17, Ismail Sarenkapic <ismai...@gmail.com> wrote:
> Tnx.
> The slug is not important here.
> The main question is how do I add product with current user!
>
> On Thursday, May 25, 2017 at 8:00:08 PM UTC+2, Muhammad wrote:
>>
>> Ismail,
>>
>> You don't seem to be handling the value for Product.slug anywhere, either
>>
>> in the model or the view.
>>
>> You can fix the slug issue by overriding the Product model's save ()
>> method like this:
>>
>> def save (self, *args, **kwargs):
>> if not self.slug:
>> self.slug = slugify(self.title)
>> super(Product, self).save (*args, **kwargs)
>>
>> This way, you can automatically generate the value of the slug field when
>>
>> a valid form is submitted.
>>
>> If you are still having problems, please, do let us know.
>>
>> All the best.
>>
>> Sincerely,
>> Muhammad
>>
>> On May 25, 2017 7:20 AM, "Ismail Sarenkapic" <ismai...@gmail.com
>> email to django-users...@googlegroups.com <javascript:>.
>> To post to this group, send email to django...@googlegroups.com
>> <javascript:>.
>> <https://groups.google.com/d/msgid/django-users/0d2d44eb-a2df-4f00-8d60-3f163ed72c9b%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>>
>>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/b1e017fa-d150-47ac-a2ee-886cb06e0a2a%40googlegroups.com.

Melvyn Sopacua

unread,
May 25, 2017, 5:44:08 PM5/25/17
to django...@googlegroups.com

Let me spell it out:

If the error message complains about the user field

And the code you provided is correct

Then your database is out of sync with your model definition

 

 

On Thursday 25 May 2017 13:53:19 Ismail Sarenkapic wrote:

> Tnx ,

> I know that i can manually select the user, but i want it to be

> automatic-with current user to add the product

>

> > > class Product(models.Model):

> > > seller = models.ForeignKey(settings.AUTH_USER_MODEL)

^^^^^^^^^ Here is the seller field

 

> > >

> > > #user = models.OneToOneField(settings.AUTH_USER_MODEL)

^^^^^^^ There is no user field. form.instance.user = 'foo' does not translate to anything useful.

The FormUserNeededMixin sets Product.user, which simply adds an instance variable, that is not picked up by the ORM, because 'user' is not a field in Product.fields.

 

The error should actually be about a field called 'seller', but because it is not in the form, it is not passed to the ORM and the old table complains about the user field, as it is the one that it still has.

 

--

Melvyn Sopacua

Ismail Sarenkapic

unread,
May 26, 2017, 2:51:54 AM5/26/17
to Django users
Man this solved my problem, I can't believe that is spend few hours not seeing this....
But now that I am able to create products with my current user, i have another problem:

When I login with admin while I am logged in with my current user, and then create product,
product is being added as by admin not as by current user as it should be.
otherwise when I am not logged in with admin(but only with current user) everything seems to work fine.
Can you help me maybe with this one?
Thanks.

Ismail Sarenkapic

unread,
May 26, 2017, 2:53:10 AM5/26/17
to Django users
Thanks for answering man!
Reply all
Reply to author
Forward
0 new messages