H
H
Horizone012020-01-20 00:27:59
Django
Horizone01, 2020-01-20 00:27:59

How to save user's posts in Django?

The crux of the matter is that when trying to save a post or form in Django, the following error appears:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
January 20, 2020 - 06:00:48
Django version 3.0.2, using settings 'project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /profile/
Traceback (most recent call last):
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: Main_userpost.author_id

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/user/Desktop/Project/project/project/Main/views.py", line 52, in post
    user_post.save()
  File "/home/user/Desktop/Project/project/project/Main/forms.py", line 59, in save
    user_post = UserPost.objects.create()
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/models/query.py", line 433, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/models/base.py", line 784, in save_base
    force_update, using, update_fields,
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/models/base.py", line 887, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/models/base.py", line 926, in _do_insert
    using=using, raw=raw,
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/models/query.py", line 1204, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1384, in execute_sql
    cursor.execute(sql, params)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/home/user/Desktop/Project/project/env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: Main_userpost.author_id

I tried to find information on the Internet, but I did not find anything similar ..
My files:
models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class UserPost(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
    text = models.CharField(max_length=120)
    date = models.DateTimeField(default=timezone.now)

forms.py
from django import forms
from django.contrib.auth.models import User
from .models import UserPost

class UserPostForm(forms.Form):
    text = forms.CharField(max_length=120)
    class Meta:
        model = UserPost
        fields = ['text']

    def save(self):
        user_post = UserPost.objects.create()
        return user_post

views.py
from django.shortcuts import render, redirect
from django.views.generic import View

from .models import UserPost
from .forms import UserPostForm

class Profile(View):
    def get(self, request):
        model = UserPost
        user_post = UserPostForm()
        data = {
            'user_post': user_post,
            'posts': UserPost.objects.all()
        }
        return render(request, 'Main/profile.html', data)

    def post(self, request):
        user_post = UserPostForm(request.POST)
        if user_post.is_valid():
            user_post.save()
            return redirect('profile')
        else:
            user_post = UserPostForm()

urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('profile/', views.Profile.as_view(), name='profile'),
]

Here are the screenshots of the error:
5e24c7a9e403f069398421.png
5e24c7a17e10d450973720.png

As I understand it, the error is that when trying to save the model, Django does not pass the user id and returns an error, but how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Web Dentist, 2020-01-20
@Horizone01

1. Use ModelForm.
2. You have some kind of meaningless save method. Why is he?
3. When POST, extract the user from request.user and do -

user_post.save(commit=False)
user_post.author = request.user
user_post.save()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question