Меню

Django ошибка повторяющееся значение ключа нарушает ограничение уникальности

I have a Django model SessionType which is defined similar to the following:

from django import models


class SessionType(models.Model):
    class Meta:
        ordering = ['title']
    title = models.CharField(max_length=255, unique=True)

At first, the unique=True constraint was not there; I’ve just added it, and run python manage.py makemigrations. This resulted in the following migration (0163_auto_20180627_1309.py):

# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-06-27 20:09
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('lucy_web', '0162_merge_20180531_0009'),
    ]

    operations = [
        migrations.AlterField(
            model_name='sessiontype',
            name='title',
            field=models.CharField(max_length=255, unique=True),
        ),
    ]

However, when I try to python manage.py migrate, I get the following error:

django.db.utils.IntegrityError: duplicate key value violates unique constraint «django_migrations_pkey»
DETAIL: Key (id)=(326) already exists.

Here are the commands and the full traceback:

(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py makemigrations
Migrations for 'lucy_web':
  lucy_web/migrations/0163_auto_20180627_1309.py
    - Alter field title on sessiontype
(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auditlog, auth, contenttypes, defender, lucy_web, oauth2_provider, otp_static, otp_totp, sessions, two_factor
Running migrations:
  Applying lucy_web.0163_auto_20180627_1309...Traceback (most recent call last):
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey"
DETAIL:  Key (id)=(326) already exists.


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

Traceback (most recent call last):
  File "manage.py", line 28, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 250, in apply_migration
    self.recorder.record_applied(migration.app_label, migration.name)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 73, in record_applied
    self.migration_qs.create(app=app, name=name)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create
    obj.save(force_insert=True, using=self.db)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/models/base.py", line 808, in save
    force_update=force_update, update_fields=update_fields)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/models/base.py", line 838, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/models/base.py", line 924, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/models/base.py", line 963, in _do_insert
    using=using, raw=raw)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1076, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1112, in execute_sql
    cursor.execute(sql, params)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey"
DETAIL:  Key (id)=(326) already exists.

Looking at the database, I see there is another migration with this primary key of 326:

enter image description here

That migration, 0161_auto_20180530_2140.py, also contains AlterField operations on the SessionType model:

# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-05-31 04:40
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('lucy_web', '0160_merge_20180524_1507'),
    ]

    operations = [
        migrations.AlterField(
            model_name='sessiontype',
            name='description',
            field=models.TextField(blank=True),
        ),
        migrations.AlterField(
            model_name='sessiontype',
            name='short_description',
            field=models.TextField(blank=True),
        ),
    ]

Following django db migration failed with postgres, I’ve tried to run the command

ALTER SEQUENCE django_migrations_id_seq RESTART WITH 329;

like so:

enter image description here

However, now when I try to migrate I run into another error that a certain unique constraint already exists:

(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auditlog, auth, contenttypes, defender, lucy_web, oauth2_provider, otp_static, otp_totp, sessions, two_factor
Running migrations:
  Applying lucy_web.0163_auto_20180627_1309...Traceback (most recent call last):
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "lucy_web_sessiontype_title_c207e4f8_uniq" already exists


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

Traceback (most recent call last):
  File "manage.py", line 28, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 221, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 515, in alter_field
    old_db_params, new_db_params, strict)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field
    new_db_params, strict,
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 719, in _alter_field
    self.execute(self._create_unique_sql(model, [new_field.column]))
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 120, in execute
    cursor.execute(sql, params)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "lucy_web_sessiontype_title_c207e4f8_uniq" already exists

How shall I solve this? Should I just delete that unique constraint and re-run migrations?

I’m following up in regards to a question that I asked earlier in which I sought to seek a conversion from a goofy/poorly written mysql query to postgresql. I believe I succeeded with that. Anyways, I’m using data that was manually moved from a mysql database to a postgres database. I’m using a query that looks like so:

  UPDATE krypdos_coderound cru

  set is_correct = case 
      when t.kv_values1 = t.kv_values2 then True 
      else False 
      end

  from 
  
  (select cr.id, 
    array_agg(
    case when kv1.code_round_id = cr.id 
    then kv1.option_id 
    else null end 
    ) as kv_values1,

    array_agg(
    case when kv2.code_round_id = cr_m.id 
    then kv2.option_id 
    else null end 
    ) as kv_values2

    from krypdos_coderound cr
     join krypdos_value kv1 on kv1.code_round_id = cr.id
     join krypdos_coderound cr_m 
       on cr_m.object_id=cr.object_id 
       and cr_m.content_type_id =cr.content_type_id 
     join krypdos_value kv2 on kv2.code_round_id = cr_m.id

   WHERE
     cr.is_master= False
     AND cr_m.is_master= True 
     AND cr.object_id=%s 
     AND cr.content_type_id=%s 

   GROUP BY cr.id  
  ) t

where t.id = cru.id
    """ % ( self.object_id, self.content_type.id)
  )

I have reason to believe that this works well. However, this has lead to a new issue. When trying to submit, I get an error from django that states:

IntegrityError at (some url): 
duplicate key value violates unique constraint "krypdos_value_pkey"

I’ve looked at several of the responses posted on here and I haven’t quite found the solution to my problem (although the related questions have made for some interesting reading). I see this in my logs, which is interesting because I never explicitly call insert- django must handle it:

   STATEMENT:  INSERT INTO "krypdos_value" ("code_round_id", "variable_id", "option_id", "confidence", "freetext")
   VALUES (1105935, 11, 55, NULL, E'') 
   RETURNING "krypdos_value"."id"

However, trying to run that results in the duplicate key error. The actual error is thrown in the code below.

# Delete current coding
CodeRound.objects.filter(
    object_id=o.id, content_type=object_type, is_master=True
).delete()
code_round = CodeRound(
    object_id=o.id, 
    content_type=object_type, 
    coded_by=request.user, comments=request.POST.get('_comments',None), 
    is_master=True,
)
code_round.save()
for key in request.POST.keys():
    if key[0] != '_' or key != 'csrfmiddlewaretoken':
        options = request.POST.getlist(key)
        for option in options:
            Value(
                code_round=code_round, 
                variable_id=key, 
                option_id=option,
                confidence=request.POST.get('_confidence_'+key, None),
            ).save()  #This is where it dies
# Resave to set is_correct
code_round.save()
o.status = '3' 
o.save()

I’ve checked the sequences and such and they seem to be in order. At this point I’m not sure what to do- I assume it’s something on django’s end but I’m not sure. Any feedback would be much appreciated!

I’m following up in regards to a question that I asked earlier in which I sought to seek a conversion from a goofy/poorly written mysql query to postgresql. I believe I succeeded with that. Anyways, I’m using data that was manually moved from a mysql database to a postgres database. I’m using a query that looks like so:

  UPDATE krypdos_coderound cru

  set is_correct = case 
      when t.kv_values1 = t.kv_values2 then True 
      else False 
      end

  from 
  
  (select cr.id, 
    array_agg(
    case when kv1.code_round_id = cr.id 
    then kv1.option_id 
    else null end 
    ) as kv_values1,

    array_agg(
    case when kv2.code_round_id = cr_m.id 
    then kv2.option_id 
    else null end 
    ) as kv_values2

    from krypdos_coderound cr
     join krypdos_value kv1 on kv1.code_round_id = cr.id
     join krypdos_coderound cr_m 
       on cr_m.object_id=cr.object_id 
       and cr_m.content_type_id =cr.content_type_id 
     join krypdos_value kv2 on kv2.code_round_id = cr_m.id

   WHERE
     cr.is_master= False
     AND cr_m.is_master= True 
     AND cr.object_id=%s 
     AND cr.content_type_id=%s 

   GROUP BY cr.id  
  ) t

where t.id = cru.id
    """ % ( self.object_id, self.content_type.id)
  )

I have reason to believe that this works well. However, this has lead to a new issue. When trying to submit, I get an error from django that states:

IntegrityError at (some url): 
duplicate key value violates unique constraint "krypdos_value_pkey"

I’ve looked at several of the responses posted on here and I haven’t quite found the solution to my problem (although the related questions have made for some interesting reading). I see this in my logs, which is interesting because I never explicitly call insert- django must handle it:

   STATEMENT:  INSERT INTO "krypdos_value" ("code_round_id", "variable_id", "option_id", "confidence", "freetext")
   VALUES (1105935, 11, 55, NULL, E'') 
   RETURNING "krypdos_value"."id"

However, trying to run that results in the duplicate key error. The actual error is thrown in the code below.

# Delete current coding
CodeRound.objects.filter(
    object_id=o.id, content_type=object_type, is_master=True
).delete()
code_round = CodeRound(
    object_id=o.id, 
    content_type=object_type, 
    coded_by=request.user, comments=request.POST.get('_comments',None), 
    is_master=True,
)
code_round.save()
for key in request.POST.keys():
    if key[0] != '_' or key != 'csrfmiddlewaretoken':
        options = request.POST.getlist(key)
        for option in options:
            Value(
                code_round=code_round, 
                variable_id=key, 
                option_id=option,
                confidence=request.POST.get('_confidence_'+key, None),
            ).save()  #This is where it dies
# Resave to set is_correct
code_round.save()
o.status = '3' 
o.save()

I’ve checked the sequences and such and they seem to be in order. At this point I’m not sure what to do- I assume it’s something on django’s end but I’m not sure. Any feedback would be much appreciated!

I had this problem when I try to save a new entry into a table called ‘config’,

class Config(models.Model):
    ident = models.CharField(max_length=uuidLength, null=True, editable=False)
    scanner = models.ForeignKey('Scanner')
    name = models.CharField(max_length=64)
   ''' some other fields '''

and postgres gave such error(the app is called «pegasus» so the table name that django gives is actually «pegasus_config»):

IntegrityError: duplicate key value violates unique constraint "pegasus_config_scanner_id_name_key"
DETAIL:  Key (scanner_id, name)=(2, ) already exists.

I searched in stackoverflow and found this solution, the problem is that I don’t know which table should I reset the index.
I did the following according to the answer:

SELECT setval('pegasus_config_id_seq', (SELECT MAX(id) FROM pegasus_config)+1)

but the problem still exists. I also went into database and found that «pegasus_config_scanner_id_name_key» is actually an index. So I’m confused about which index to reset? Please help. Thanks.

I had this problem when I try to save a new entry into a table called ‘config’,

class Config(models.Model):
    ident = models.CharField(max_length=uuidLength, null=True, editable=False)
    scanner = models.ForeignKey('Scanner')
    name = models.CharField(max_length=64)
   ''' some other fields '''

and postgres gave such error(the app is called «pegasus» so the table name that django gives is actually «pegasus_config»):

IntegrityError: duplicate key value violates unique constraint "pegasus_config_scanner_id_name_key"
DETAIL:  Key (scanner_id, name)=(2, ) already exists.

I searched in stackoverflow and found this solution, the problem is that I don’t know which table should I reset the index.
I did the following according to the answer:

SELECT setval('pegasus_config_id_seq', (SELECT MAX(id) FROM pegasus_config)+1)

but the problem still exists. I also went into database and found that «pegasus_config_scanner_id_name_key» is actually an index. So I’m confused about which index to reset? Please help. Thanks.

Я слежу за вопрос, который я задавал ранее в котором я пытался найти преобразование из глупого/плохо написанного запроса mysql в postgresql. Я считаю, что мне это удалось. В любом случае, я использую данные, которые были вручную перемещены из базы данных mysql в базу данных postgres. Я использую запрос, который выглядит так:

  UPDATE krypdos_coderound cru

  set is_correct = case 
      when t.kv_values1 = t.kv_values2 then True 
      else False 
      end

  from 
  
  (select cr.id, 
    array_agg(
    case when kv1.code_round_id = cr.id 
    then kv1.option_id 
    else null end 
    ) as kv_values1,

    array_agg(
    case when kv2.code_round_id = cr_m.id 
    then kv2.option_id 
    else null end 
    ) as kv_values2

    from krypdos_coderound cr
     join krypdos_value kv1 on kv1.code_round_id = cr.id
     join krypdos_coderound cr_m 
       on cr_m.object_id=cr.object_id 
       and cr_m.content_type_id =cr.content_type_id 
     join krypdos_value kv2 on kv2.code_round_id = cr_m.id

   WHERE
     cr.is_master= False
     AND cr_m.is_master= True 
     AND cr.object_id=%s 
     AND cr.content_type_id=%s 

   GROUP BY cr.id  
  ) t

where t.id = cru.id
    """ % ( self.object_id, self.content_type.id)
  )

У меня есть основания полагать, что это работает хорошо. Однако это привело к новой проблеме. При попытке отправить я получаю сообщение об ошибке от django, в котором говорится:

IntegrityError at (some url): 
duplicate key value violates unique constraint "krypdos_value_pkey"

Я просмотрел несколько ответов, размещенных здесь, и я не совсем нашел решение своей проблемы (хотя связанные вопросы сделали для некоторых интересное чтение). Я вижу это в своих журналах, что интересно, потому что я никогда не вызываю вставку явно — django должен это обработать:

   STATEMENT:  INSERT INTO "krypdos_value" ("code_round_id", "variable_id", "option_id", "confidence", "freetext")
   VALUES (1105935, 11, 55, NULL, E'') 
   RETURNING "krypdos_value"."id"

Однако попытка запустить это приводит к ошибке дублирования ключа. Фактическая ошибка возникает в приведенном ниже коде.

 # Delete current coding         CodeRound.objects.filter(object_id=o.id,content_type=object_type,is_master=True).delete()
  code_round = CodeRound(object_id=o.id,content_type=object_type,coded_by=request.user,comments=request.POST.get('_comments',None),is_master=True)
  code_round.save()
  for key in request.POST.keys():
    if key[0] != '_' or key != 'csrfmiddlewaretoken':
      options = request.POST.getlist(key)
      for option in options:
        Value(code_round=code_round,variable_id=key,option_id=option,confidence=request.POST.get('_confidence_'+key, None)).save()  #This is where it dies
  # Resave to set is_correct
  code_round.save()
  o.status = '3' 
  o.save(

Я проверил последовательности и тому подобное, и они, кажется, в порядке. На данный момент я не уверен, что делать — я предполагаю, что это что-то на стороне django, но я не уверен. Любая обратная связь будет высоко оценена!

Всем привет. Делаю сайт, конкретно форму добавления постов. При попытке сохранить пост появляется вот такая ошибка:

IntegrityError at /form ОШИБКА: повторяющееся значение ключа нарушает ограничение уникальности "sitelogic_post_post_slug_key" DETAIL: Ключ "(post_slug)=()" уже существует.

База данных — PostgreSQL

Пожалуйста, помогите разобраться в чем проблема. Искал ответ в большом количестве источников, нигде не нашел решения

Models.py:

class Post(models.Model):
    post_title = models.CharField(max_length=250, verbose_name='Заголовок')
    post_slug = models.SlugField(max_length=250, unique=True, verbose_name='URL')
    post_content = models.TextField(max_length=450000, verbose_name='Содержание')
    post_time_create = models.DateTimeField(auto_now_add=True, verbose_name='Время создания')
    post_time_update = models.DateTimeField(auto_now=True, verbose_name='Время обновления')
    post_media = models.ImageField(upload_to='%Y/%m/%d/', default='default.png', blank=True, verbose_name='Медиа')
    cat = models.ForeignKey('PostCategory', on_delete=models.PROTECT, null=True, verbose_name='Категория')

    def __str__(self):
        return self.post_title

    def get_absolute_url(self):
        return reverse('show_post', kwargs={'post_title_slug': self.post_title, 'post_id_slug': self.id})

    class Meta:
        verbose_name = 'Пост'
        verbose_name_plural = 'Посты'

        ordering = ['post_title', 'post_content']

class PostCategory(models.Model):
    category_name = models.CharField(max_length=100, db_index=True)
    slug = models.SlugField(max_length=100, unique=True, verbose_name='URL')

    class Meta:
        verbose_name = 'Категория'
        verbose_name_plural = 'Категории'

        ordering = ['pk']

    def __str__(self):
        return self.category_name

    def get_absolute_url(self):
        return reverse('cat_posts', kwargs={'cat_slug': self.slug})

Forms.py:

class PostForm(forms.ModelForm):
captcha = CaptchaField()

class Meta:
    model = Post
    fields = ['post_title', 'post_content', 'post_media', 'cat']

def clean_post_title(self):
    post_title = self.cleaned_data['post_title']
    if len(post_title) >= 250:
        raise ValidationError('Длина превышает 200 символов')

    return post_title

Views.py:

class FormAdd(View):

    def get(self, request):
        form = PostForm
        return render(request, 'sitelogic/addpost.html', context={'form': form})

    def post(self, request):
        request_keep = PostForm(request.POST)
        if request_keep.is_valid():
            request_keep.save()
            return redirect('home_page')
        return render(request, 'sitelogic/addpost.html', context={'form': request_keep})

Urls.py:

urlpatterns = [
              path('', homepage, name='home_page'),
              path('about', About.as_view(), name='about_site'),
              path('post/<slug:post_title_slug>/<int:post_id_slug>/', ShowPost, name='show_post'),
              path('forums/<slug:cat_slug>', ShowCategory.as_view(), name='cat_posts'),
              path('form', FormAdd.as_view(), name='add_post'),
              path('cabinet', Cabinet.as_view(), name='cabinet'),
              path('auth/', include('djoser.urls')),
              path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
              path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
              path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
              path('testapi', Base.as_view())
          ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 
          + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Addpost.html:

{% extends 'sitelogic/base.html' %}

{% block body %}
<form action="{% url 'add_post' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">добавить</button>
</form>
{% endblock %}

У тебя есть обязательные поля, которые ты не отображаешь в форме.
Тебе надо либо их выводить в форму и заполнять вручную, либо заполнять программно в функции post(self, request) как-то так:

def post(self, request, *args, **kwargs):
    request_keep = PostForm(request.POST)
    if request_keep.is_valid():
        request_keep.save(commit=False)
        request_keep.post_slug = "some value"
        request_keep.post_time_create = "some value"
        request_keep.post_time_update = "some value"
        request_keep.save()
        return redirect('home_page')
    return render(request, 'sitelogic/addpost.html', context={'form': request_keep})


Back to Top

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Django ошибка доступа 403 ошибка проверки csrf запрос отклонен
  • Django обработка ошибок формы