【问题标题】:I am unable to create a new custom user in Django我无法在 Django 中创建新的自定义用户
【发布时间】:2020-11-04 16:05:35
【问题描述】:

我尝试创建一个新用户,但没有成功,我尝试调试它,但没有解决这个问题。我有一个用户模型,但想尝试创建不同的用户类型,例如学生、教师等,它们都将在用户用户模型及其各种用户模型中。

查看.py

def AddCustomerManager(request):
    if request.method == "POST":
        email = request.POST.get('email')
        username = request.POST.get('username')
        password = request.POST.get('password')

        try:
            user = User.objects.create_user(email=email, username=username, password=password, user_type=2)
            user.save()
            messages.success(request, "Customer Manager Added Successfully")
        except:
            messages.error(request, "Failed to Add Customer Manager")

    return render(request, "pusheat_admin/addcm.html")

models.py

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    user_type_choice = ((1, "SuperUser"), (2, "CustomerManager"))
    user_type = models.CharField(default=1, choices=user_type_choice, max_length=10)
    objects = UserManager()

class CustomerManager(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    fullname = models.CharField(max_length=50, blank=False)
    email = models.EmailField()
    password = models.CharField(max_length=32)

addcm.html

<form role="form" method="POST">
    {% csrf_token %}
    <div class="card-header"><h4>Add Customer Manager</h4></div>
    <div class="card-body">
        <div class="form-group">
            <label>Email address</label>
            <input type="email" class="form-control" name="email" placeholder="Enter email">
        </div>
        <div class="form-group">
            <label>Username</label>
            <input type="text" class="form-control" name="username" placeholder="Username">
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" class="form-control" name="password" placeholder="Password">
        </div>
    </div>
    <div class="card-footer">
    <button type="submit" class="btn btn-primary">Add Customer Manager</button>
    </div>
</form>

【问题讨论】:

    标签: django django-models django-views django-forms django-templates


    【解决方案1】:

    models.py中更改这一行:

     user_type = models.CharField(default=1, choices=user_type_choice, max_length=10)
    

    到:

     user_type = models.PositiveSmallIntegerField(default=1, choices=user_type_choice, max_length=10)
    

    【讨论】:

    • 请问有什么区别
    • CharField 通常用于文本字符串,PositiveSmallIntegerField 用于从 0 到 32767 的整数值,如您的情况 user_type_choice 值为 1 和 2。更改是否有效?
    猜你喜欢
    • 2021-03-17
    • 2019-03-31
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    相关资源
    最近更新 更多