【问题标题】:DJANGO createsuperuser not working...TypeError: create_superuser() missing 1 required positional argument: 'username'DJANGO createsuperuser 不工作...类型错误:create_superuser() 缺少 1 个必需的位置参数:“用户名”
【发布时间】:2019-10-17 13:18:18
【问题描述】:

我正在尝试使用 Django 和 DRF 创建一个 RESTful API。我有一个扩展 AbstractUser 的用户模型。我既不能创建普通用户也不能创建超级用户。出于某种原因,它说

当我跑步时:

python manage.py createsuperuser

我收到以下错误:

“类型错误:create_superuser() 缺少 1 个必需的位置参数:‘用户名’”

这是 models.py 文件:

import uuid
from django.db import models
from django.conf import settings
from django.dispatch import receiver
from django.contrib.auth.models import AbstractUser
from django.utils.encoding import python_2_unicode_compatible
from django.db.models.signals import post_save
from rest_framework.authtoken.models import Token
from api.fileupload.models import File


@python_2_unicode_compatible
class User(AbstractUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    profile_picture = models.ForeignKey(File, on_delete=models.DO_NOTHING, null=True, blank=True)
    email = models.EmailField('Email address', unique=True)
    name = models.CharField('Name', default='', max_length=255)
    phone_no = models.CharField('Phone Number', max_length=255, unique=True)
    company_name = models.CharField('Company Name', default='', max_length=255)
    address = models.CharField('Address', default='', max_length=255)
    address_coordinates = models.CharField('Address Coordinates', default='', max_length=255)
    country = models.CharField('Country', default='', max_length=255)
    pincode = models.CharField('Pincode', default='', max_length=255)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create_user(user=instance)

serializers.py 文件:

from django.contrib.auth.password_validation import validate_password
from rest_framework import serializers

from .models import User
from api.fileupload.serializers import FileSerializer


class UserSerializer(serializers.ModelSerializer):
    profile_picture = FileSerializer()

    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        return user

    def update(self, instance, validated_data):
        instance.name = validated_data.get('name', instance.name)
        instance.company_name = validated_data.get('company_name', instance.company_name)
        instance.address = validated_data.get('address', instance.address)
        instance.country = validated_data.get('country', instance.country)
        instance.pincode = validated_data.get('pincode', instance.pincode)
        instance.phone_no = validated_data.get('phone_no', instance.phone_no)
        instance.email = validated_data.get('email', instance.email)
        instance.profile_picture = validated_data.get('profile_picture', instance.profile_picture)
        instance.save()
        return instance

    class Meta:
        unique_together = ('email',)
        model = User
        fields = (
            'id', 'password', 'email', 'name', 'phone_no', 'company_name', 'address', 'country', 'pincode', 'profile_picture',
        )
        extra_kwargs = {'password': {'write_only': True}}

views.py 文件:

from rest_framework import viewsets, mixins
from .models import User
from .serializers import UserSerializer
class UserViewSet(mixins.RetrieveModelMixin,
                  mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  viewsets.GenericViewSet):
    queryset = User.objects.all()
    permission_classes = (AllowAny,)
    serializer_class = UserSerializer

【问题讨论】:

  • 请提供导致错误的命令。
  • python manage.py createsuperuser

标签: django django-models django-rest-framework


【解决方案1】:

当你使用createsuperuser命令时,它会要求你输入一些必填字段,USERNAME_FIELD是必填字段,REQUIRED_FIELDS里面的所有字段。你的代码集REQUIRED_FIELDS=[]所以没有必填字段,只需要添加emailpassword即可。

但是当createsuperuser被调用时,它会调用create_superuser方法,需要username字段:

def create_superuser(self, username, email=None, password=None, **extra_fields):

这样您的输入数据不足以将数据传递给create_superuser 方法。

要解决这个问题,您只需将username 添加到REQUIRED_FIELDS

REQUIRED_FIELDS = ['username']

然后createsuperuser 将要求您为create_superuser 方法添加username 字段。

希望对您有所帮助。

【讨论】:

  • 谢谢!这确实有效......但 create_user() 仍然无法正常工作,它给出了以下错误:{"non_field_errors":["Unable to log in with provided credentials."]}
  • 我认为这与create_user 无关。该消息与错误的凭据、错误的密码有关..
  • 但是我正在尝试创建一个新用户..所以会有错误的凭据
  • 是的,我也很好奇。你怎么称呼create_user方法@GoutamBSeervi?通过视图还是通过命令?
  • 在序列化程序中创建方法
猜你喜欢
  • 2020-04-06
  • 2018-09-03
  • 2022-06-28
  • 2022-01-10
  • 2019-09-22
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 2019-08-09
相关资源
最近更新 更多