出现错误:django.db.utils.IntegrityError:唯一约束失败:auth_user.username ||我是一个尝试在 Djnago 保存的初学者

问题描述 投票:0回答:1

我正在尝试学习 django。刚刚开始一个项目。 目前已有 2 个应用程序。

  1. 员工
  2. 民意调查

我正在尝试通过 CMD 来完成此操作。它显示了以下问题。实际上,我正在尝试遵循 django 项目的教程。我查了一下,代码中没有使用UNIQUE关键字。我什至尝试删除然后保存但没有解决。


    Employee :--

**models.py (employee) : **

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

# Create your models here.
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    designation = models.CharField(max_length=20, null=False, blank=False)
    salary = models.IntegerField(null=True,blank=True)

    class Meta:
        ordering = ('-salary',) #minus sign indicates that we need the result in decending
          order

    def __str__(self):
        return "{0} {1}". format(self.user.first_name, self.user.last_name)


@receiver(post_save, sender=User) 
def user_is_created(sender, instance, created, **kwargs):
    if created:
        Profile.object.create (user=instance.)
    else:
        instance.profile.save()

Poll :--

**models.py (poll)**

from django.db import models
from django.contrib.auth.models import User

# Create your models here.`

`class Question(models.Model): # models.Model is the base model. we just need to extend it.
    #All the class varibales will be considered as the columns of the table.  
    title = models.TextField(null=True, blank = True)
    status = models.CharField(default = 'inactive', max_length=10) #if we don't pass anything it
         will take 'inactive' as default
    created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)

    start_date = models.DateTimeField(null=True, blank=True)
    end_date = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True) # done only once
    updated_at = models.DateTimeField(auto_now=True)  #Updated every time. If we want to track 
 when the object was modified last

    def __str__(self):
        return self.title

class Choice(models.Model):
    question = models.ForeignKey('poll.Question', on_delete=models.CASCADE) #Quesion is 
    available in the model itself
    text = models.TextField(null=True, blank=True)

    created_at = models.DateTimeField(auto_now_add=True) # done only once
    updated_at = models.DateTimeField(auto_now=True)  #Updated every time. If we want to track
      when the object was modified last

    def __str__(self):
        return self.text` ----------------------------------------------------------------------------------------------

**Error in commnad prompt :**

>>> u = User()
>>> u.save()
Traceback (most recent call last):
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in 
     execute
    return super().execute(query, params)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.IntegrityError: UNIQUE constraint failed: auth_user.username

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

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\kanha\V3.11\Lib\site-packages\django\contrib\auth\base_user.py", line 76, in save
    super().save(*args, **kwargs)
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\models\base.py", line 814, in save
    self.save_base(
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\models\base.py", line 877, in save_base
    updated = self._save_table(
            ^^^^^^^^^^^^^^^^^
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\models\base.py", line 1020, in _save_table
    results = self._do_insert(
            ^^^^^^^^^^^^^^^^
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\models\base.py", line 1061, in _do_insert
    return manager._insert(
        ^^^^^^^^^^^^^^^^
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\models\manager.py", line 87, in 
    manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\models\query.py", line 1805, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\models\sql\compiler.py", line 1822, in 
    execute_sql
    cursor.execute(sql, params)
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\backends\utils.py", line 102, in execute
    return super().execute(sql, params)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\backends\utils.py", line 67, in execute
    return self._execute_with_wrappers(
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\backends\utils.py", line 80, in 
     _execute_with_wrappers
    return executor(sql, params, many, context)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    with self.db.wrap_database_errors:
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kanha\V3.11\Lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in
    execute
    return super().execute(query, params)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
django.db.ut`ils.IntegrityError: UNIQUE constraint failed: auth_user.username

我尝试了很多谷歌搜索,但无法解决这个问题。

django django-models django-forms
1个回答
0
投票

主要问题是您已经创建了空的用户字段

User()
现在再次运行命令,它将显示用户已经在数据库中退出,但有异常-

django.db.ut`ils.IntegrityError:唯一约束失败:auth_user.username

所以,尝试创建一个带有字段的用户对象

u = User(email='[email protected]' password='password123' other fields...)
© www.soinside.com 2019 - 2024. All rights reserved.