0

I'm using a custom user model. I don't know for some reason it's not saving the user in the post table. (The user is actually the author of the blog)

Here is the error trace:

Request Method: POST
Request URL: http://127.0.0.1:8000/post/create/

Django Version: 2.2.4
Python Version: 3.7.4
Installed Applications:
['authentica.apps.AuthenticaConfig',
 'post.apps.PostConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  383.         return Database.Cursor.execute(self, query, params)

The above exception (NOT NULL constraint failed: post_posts.user_id) was the direct cause of the following exception:

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in dispatch
  97.         return handler(request, *args, **kwargs)

File "D:\authen\post\views.py" in post
  27.                 form.save()

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py" in save
  458.             self.instance.save()

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in save
  741.                        force_update=force_update, update_fields=update_fields)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in save_base
  779.                 force_update, using, update_fields,

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in _save_table
  870.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in _do_insert
  908.                                using=using, raw=raw)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py" in _insert
  1186.         return query.get_compiler(using=using).execute_sql(return_id)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  1335.                 cursor.execute(sql, params)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py" in execute
  99.             return super().execute(sql, params)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py" in execute
  67.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers
  76.         return executor(sql, params, many, context)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  383.         return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /post/create/
Exception Value: NOT NULL constraint failed: post_posts.user_id

Here are the files:

models.py

class Posts(models.Model):
    user= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    published_time= models.DateTimeField(auto_now_add=True, blank=True)
    title= models.CharField(blank=False, editable=True, max_length=255)
    myslug= models.SlugField(max_length=255, blank= True, null= True)
    updated= models.DateTimeField(auto_now=True, blank= True)
    content= models.CharField(default=False, max_length=255,editable=True)

NOTE: I've already tried putting default and null=True. But it sets Null or default in either cases in the user column. I'll also provide the custom user model, just in case.

models.py (Custom User)

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self,email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(
            email=email
            )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    # def create_superuser(self, email, password, **extra_fields):
    #     extra_fields.setdefault('is_superuser', True)

    #     if extra_fields.get('is_superuser') is not True:
    #         raise ValueError('Superuser must have is_superuser=True.')

    #     return self._create_user(email, password, **extra_fields)

    def create_staffuser(self, email, password):
        """
        Creates and saves a staff user with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.admin = True
        user.save(using=self._db)
        return user


class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    objects = UserManager()
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False) # a admin user; non super-user
    admin = models.BooleanField(default=False) # a superuser
    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')


    def email_user(self, subject, message, from_email=None, **kwargs):
        '''
        Sends an email to this User.
        '''
        send_mail(subject, message, from_email, [self.email], **kwargs)


    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        return self.staff
    @property
    def is_active(self):
        "Is the user active?"
        return self.active
    @property
    def is_admin(self):
        "Is the user a admin member?"
        return self.admin

forms.py

class PostForm(forms.ModelForm):
    content= forms.CharField(widget= forms.Textarea)
    title= forms.CharField(label= None, widget=forms.TextInput())
    class Meta:
        model= Posts
        fields= ('content', 'title',)

views.py

class PostView(TemplateView):
    template_name= 'post/bloginput.html'
    def get(self, request):
        if not request.user.is_authenticated:
            return redirect('login')
        else:
            form= PostForm()
            return render(request, self.template_name, {'form':form})
    def post(self, request):
        if request.POST:
            form= PostForm(request.POST)
            if form.is_valid():
                content= form.cleaned_data.get('content')
                title= form.cleaned_data.get('title')
                print(content, title)
                form.save()
                return redirect('home')
        else:
            form= PostForm()

        return render(request, self.template_name, {'form':form})
cyberhawk
  • 11
  • 5

1 Answers1

0

The error is raised because your Post model requires a mandatory user and your PostForm does not provide this. If you want to add the current user and do not want to add this field to your form you need to add the User before finally saving your model. You could do the following

# Your other code

if form.is_valid():
    post = fom.save(commit=False)
    post.user = request.user
    post.save()

# more code

You can read more about this in the docs or in this SO post

Chris
  • 2,162
  • 1
  • 6
  • 17