Задать вопрос
@Horizone01

Как сделать сохранение постов пользователя в Django?

Суть вопроса - при попытке сохранения поста или же формы в Django появляется такая ошибка:
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


Пробовал найти информацию в интернете, но ничего похожего не нашёл..

Мои файлы:
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'),
]


Вот скриншоты ошибки:
5e24c7a9e403f069398421.png
5e24c7a17e10d450973720.png

Как я понял ошибка заключается в том, что при попытке сохранения модели Django не передаёт id пользователя и возвращает ошибку, но как её исправить?
  • Вопрос задан
  • 659 просмотров
Подписаться 1 Простой Комментировать
Решения вопроса 1
kgb_zor
@kgb_zor
I need your traceback.
1. Используйте ModelForm.
2. У вас какой-то бессмысленный метод save. Зачем он?
3. При POST извлейкайте юзера из request.user и делайте -

user_post.save(commit=False)
user_post.author = request.user
user_post.save()
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы