@David138

Как настроить в django rest api используя две модели?

привет. столкнулся с такой проблемой при работе с django rest:
[04/Jan/2024 05:17:56] "GET /admin/women/women/add/ HTTP/1.1" 200 26479
[04/Jan/2024 05:17:56] "GET /admin/jsi18n/ HTTP/1.1" 200 17546
Internal Server Error: /admin/women/women/add/
Traceback (most recent call last):
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 105, in _execute
    return self.cursor.execute(sql, params)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
    return super().execute(query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: women_women.owner_id

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

Traceback (most recent call last):
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/contrib/admin/options.py", line 714, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/utils/decorators.py", line 188, in _view_wrapper
    result = _process_exception(request, e)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/utils/decorators.py", line 186, in _view_wrapper
    response = view_func(request, *args, **kwargs)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/views/decorators/cache.py", line 80, in _view_wrapper
    response = view_func(request, *args, **kwargs)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 240, in inner
    return view(request, *args, **kwargs)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1941, in add_view
    return self.changeform_view(request, None, form_url, extra_context)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/utils/decorators.py", line 48, in _wrapper
    return bound_method(*args, **kwargs)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/utils/decorators.py", line 188, in _view_wrapper
    result = _process_exception(request, e)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/utils/decorators.py", line 186, in _view_wrapper
    response = view_func(request, *args, **kwargs)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1802, in changeform_view
    return self._changeform_view(request, object_id, form_url, extra_context)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1853, in _changeform_view
    self.save_model(request, new_object, form, not add)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1257, in save_model
    obj.save()
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/models/base.py", line 822, in save
    self.save_base(
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/models/base.py", line 909, in save_base
    updated = self._save_table(
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/models/base.py", line 1067, in _save_table
    results = self._do_insert(
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/models/base.py", line 1108, in _do_insert
    return manager._insert(
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/models/manager.py", line 87, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1845, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1823, in execute_sql
    cursor.execute(sql, params)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/debug_toolbar/panels/sql/tracking.py", line 252, in execute
    return self._record(super().execute, sql, params)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/debug_toolbar/panels/sql/tracking.py", line 177, in _record
    return method(sql, params)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 122, in execute
    return super().execute(sql, params)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 79, in execute
    return self._execute_with_wrappers(
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 92, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 100, in _execute
    with self.db.wrap_database_errors:
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 105, in _execute
    return self.cursor.execute(sql, params)
  File "/home/tuser/Projects/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
    return super().execute(query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: women_women.owner_id
[04/Jan/2024 05:18:24] "POST /admin/women/women/add/ HTTP/1.1" 500 231583
[04/Jan/2024 05:18:48] "GET /admin/women/women/add/ HTTP/1.1" 200 26479

у меня уже есть готовый проект с django https://github.com/David138it/MyPortfolio/tree/mai...
захотел подучить Django Rest Api для этого нашел статью https://pythonru.com/uroki/django-rest-api и остановился на том когда нужно было настроить Сериализатор Post. Вместо post у меня Women. проект запускается, но когда я добавляю новый пост, выдает ошибку выше.
Что я делаю не так?
Вот код, который я добавил:
from django.db import models
from django.urls import reverse
# Create your models here.
class Women(models.Model):
	"""docstring for Women"""
	title=models.CharField(max_length=255, verbose_name="Заголовок")
	slug=models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL")
	content=models.TextField(blank=True, verbose_name="Текст статьи")
	photo=models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Фото")
	time_create=models.DateTimeField(auto_now_add=True, verbose_name="Время создания")
	time_update=models.DateTimeField(auto_now=True, verbose_name="Время изменения")
	is_published=models.BooleanField(default=True, verbose_name="Публикация")
	#cat=models.ForeignKey('Category', on_delete=models.PROTECT, null=True, verbose_name="Категории")
	cat=models.ForeignKey('Category', on_delete=models.PROTECT, verbose_name="Категории")
	owner = models.ForeignKey('auth.User', related_name='womens', on_delete=models.CASCADE)
	def __str__(self):
		return self.title
	def get_absolute_url(self):
		return reverse('post', kwargs={'post_slug':self.slug})
	class Meta:
		verbose_name='Известные женщины'
		verbose_name_plural='Известные женщины'
		#ordering=['time_create','title']
		#ordering=['-time_create','title']
		ordering=['id']
class Category(models.Model):
	name=models.CharField(max_length=100, db_index=True, verbose_name="Категория")
	slug=models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL")
	def __str__(self):
		return self.name
	def get_absolute_url(self):
		#return reverse('category', kwargs={'cat_id':self.pk})
		return reverse('category', kwargs={'cat_slug':self.slug})
	class Meta:
		verbose_name='Категория'
		verbose_name_plural='Категории'
		ordering=['id']

и код serials:
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Women
class WomenSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    class Meta:
        model = Women
        fields = ['id', 'title', 'content', 'owner']
class UserSerializer(serializers.ModelSerializer):
    womens = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    class Meta:
        model = User
        fields = ['id', 'username', 'womens']
  • Вопрос задан
  • 117 просмотров
Пригласить эксперта
Ответы на вопрос 1
@Everything_is_bad
Проблема не в DRF, а в том что ты из админки создаешь Women без owner, учись читать traceback'и
Ответ написан
Комментировать
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы