1

I'm creating a new object with a form and when I hit the save button I got this error: IntegrityError at /department/add duplicate key value violates unique constraint "feedback_department_pkey" DETAIL: Key (id)=(1) already exists.

Although, I have 18 records in this table in the database, but I can't figure out why is trying to start saving from the first id.

my views.py:

# Add new department
def department_add(request):

    form = DepartmentEditForm()
    if request.method == "POST":
        print('Printing POST', request.POST)
        form = DepartmentEditForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('feedback:department')

    return render(request, 'departmentadd.html', {'form': form}) 

my models.py:

class Department(models.Model):
    name = models.CharField(max_length=100)
    title_bg = models.CharField(max_length=50)
    title_en = models.CharField(max_length=50)
    title_de = models.CharField(max_length=50)

    def __str__(self):
        return self.name

urls.py

path('department/add', views.department_add, name="departmentadd"),

and forms.py:

class DepartmentEditForm(forms.ModelForm):
    class Meta:
        model = Department
        #fields = '__all__'
        fields = [
            'name',
            'title_bg',
            'title_en',
            'title_de',
        ]

        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'title_bg': forms.TextInput(attrs={'class': 'form-control'}),
            'title_en': forms.TextInput(attrs={'class': 'form-control'}),
            'title_de': forms.TextInput(attrs={'class': 'form-control'}),
        }

This is my Traceback:

Traceback (most recent call last):   File "/usr/lib/python3/dist-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)   File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)   File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "/home/stela/feedbacksystem/feedback/views.py", line 119, in department_add
    form.save()   File "/usr/lib/python3/dist-packages/django/forms/models.py", line 458, in save
    self.instance.save()   File "/usr/lib/python3/dist-packages/django/db/models/base.py", line 740, in save
    self.save_base(using=using, force_insert=force_insert,   File "/usr/lib/python3/dist-packages/django/db/models/base.py", line 777, in save_base
    updated = self._save_table(   File "/usr/lib/python3/dist-packages/django/db/models/base.py", line 870, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)   File "/usr/lib/python3/dist-packages/django/db/models/base.py", line 907, in _do_insert
    return manager._insert([self], fields=fields, return_id=update_pk,   File "/usr/lib/python3/dist-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)   File "/usr/lib/python3/dist-packages/django/db/models/query.py", line 1186, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)   File "/usr/lib/python3/dist-packages/django/db/models/sql/compiler.py", line 1375, in execute_sql
    cursor.execute(sql, params)   File "/usr/lib/python3/dist-packages/django/db/backends/utils.py", line 99, in execute
    return super().execute(sql, params)   File "/usr/lib/python3/dist-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)   File "/usr/lib/python3/dist-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)   File "/usr/lib/python3/dist-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)   File "/usr/lib/python3/dist-packages/django/db/utils.py", line 89, in
__exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value   File "/usr/lib/python3/dist-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params) django.db.utils.IntegrityError: duplicate key value violates unique constraint "feedback_department_pkey" DETAIL:  Key (id)=(1) already exists.

Can someone say what I'm missing here? Thanks a lot!

dev
  • 41
  • 8
  • can you share full error log – rahul.m Feb 08 '21 at 14:38
  • @c.grey I just update my question with the full Traceback error message – dev Feb 08 '21 at 14:40
  • 2
    did you runs migrations?? – Anshul Singh Suryan Feb 08 '21 at 14:43
  • try `python manage.py makemigration` then `pyton manage.py migrate` – aviya.developer Feb 08 '21 at 14:45
  • @dev might be a migration issue – rahul.m Feb 08 '21 at 14:45
  • @AnshulSinghSuryan yes but I have No migrations to apply. – dev Feb 08 '21 at 14:46
  • @dev do you mean that you have migrated previously? If not try `python manage.py makemigrations ` I assume appname to be feedback so replace with that. If you have no migrations to make check this [answer by Ad N](https://stackoverflow.com/a/37183998/14991864) – Abdul Aziz Barkat Feb 08 '21 at 14:50
  • When I created the model, I ran the migrations. The error I got was when I tried to add new object to this model. I seed the database manually with sql script at the first time, and now I'm trying to add "add new" option. I checked the answer you suggest, but I'm not sure what I'm achieving with this python3 manage.py sqlsequencereset feedback, I got SELECT setval(pg_get_serial_sequence('"feedback_department"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "feedback_department"; If this can help. – dev Feb 08 '21 at 14:58
  • @dev Copy the output of the above command (SELECT ......). Type `python manage.py dbshell` it will open the shell for your database, paste above query here. run. – Abdul Aziz Barkat Feb 08 '21 at 15:05
  • Ok, I got this. but also when I run this python3 manage.py sqlsequencereset feedback | python manage.py dbshell I got: Exception ignored in: <_io.TextIOWrapper name='' mode='w' encoding='utf-8'> BrokenPipeError: [Errno 32] Broken pipe. What is that mean? – dev Feb 08 '21 at 15:10

0 Answers0