在自定义用户的配置文件中找到不需要的随机值

时间:2018-08-21 05:40:50

标签: python django

我正在关注https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#a-full-example,以使用电子邮件作为用户名来创建用户。

我还将使用profile表创建一对一的关系。 profile表包含一个API密钥列

我查看user表和profile表。他们两个看起来都很好。如果我在user表中有3条记录,那么我在profile表中将只有3条记录,因为它们是一对一的关系。


但是,当我看到登录到管理页面时。事情听起来不对。每个用户都与2个API密钥相关联。第一个API密钥似乎是一个随机生成的值,另一个API密钥是来自数据库的有效API密钥。

enter image description here

这是当前数据库。

snapweb=# select * from accounts_myuser;
 id | password                   |          last_login           |          email           | is_active | is_admin
----+--------------------------------------------------------------------------------+-------------------------------+
  2 | pbkdf2_sha256$120000$w7OlH |                               | yccheok@yahoo.com        | t         | f
  1 | pbkdf2_sha256$120000$tWA6Y | 2018-08-21 05:07:28.391689+00 | root@root.com            | t         | t
  3 | pbkdf2_sha256$120000$TkKAE |                               | yancheng.cheok@gmail.com | t         | f
(3 rows)

snapweb=# select * from accounts_profile;
 id |               api_key                | user_id
----+--------------------------------------+---------
  1 | d6ee9b31-6847-4b7d-8151-98b133f21c42 |       1
  2 | c6f3718e-41ee-4759-984a-63c405b32fc4 |       2
  3 | 10c64d48-416f-4fd7-b01d-4328d2536ea2 |       3
(3 rows)

现在,管理页面中显示的值为

API KEY: 6cb1b77f-6ab0-464d-9176-d0ed20402b8c: API KEY: 10c64d48-416f-4fd7-b01d-4328d2536ea2 

刷新页面时,它将更改为

API KEY: b4a07773-a3e0-4fcc-bf5c-245935cd0687: API KEY: 10c64d48-416f-4fd7-b01d-4328d2536ea2 

您知道为什么会发生这种奇怪的行为吗?

这是代码

models.py

import uuid
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

class MyUserManager(BaseUserManager):
    def create_user(self, email, password=None):
        """
        Creates and saves a User with the given email and 
        password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        """
        Creates and saves a superuser with the given email and 
        password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user


class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin


class Profile(models.Model):
    user = models.OneToOneField(MyUser, on_delete=models.CASCADE)
    api_key = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)

    def __str__(self):
        return 'API KEY: ' + str(self.api_key)


@receiver(post_save, sender=MyUser)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
        instance.profile.save()        

admin.py

from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from accounts.models import MyUser
from accounts.models import Profile

class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = MyUser
        fields = ('email',)

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = MyUser
        fields = ('email', 'password', 'is_active', 'is_admin')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]


class MyCustomUserInline(admin.StackedInline):
    model = Profile
    can_delete = True
    verbose_name = Profile


class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Permissions', {'fields': ('is_admin',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2')}
        ),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()

    inlines = (MyCustomUserInline, )

# Now register the new UserAdmin...
admin.site.register(MyUser, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)

更新

更改代码后

class Profile(models.Model):
    user = models.OneToOneField(MyUser, on_delete=models.CASCADE)
    api_key = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)

    def __str__(self):
        return 'API KEY: ' + str(self.api_key)

class Profile(models.Model):
    user = models.OneToOneField(MyUser, on_delete=models.CASCADE)
    api_key = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)

    def __str__(self):
        if hasattr(self, 'user'):
            return 'API KEY -> ' + str(self.api_key)
        else:
            return ''

我知道如何部分地“消除”该问题(不确定为什么还有双冒号:

enter image description here

现在,问题又回到了为什么为什么要首先创建一个Profile却没有创建MyUser的对象?我如何才能彻底解决问题? (甚至不显示双冒号:

2 个答案:

答案 0 :(得分:1)

您必须在#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "ControllerCreator.h" int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; ControllerCreator controllerCreator; engine.rootContext()->setContextProperty("creator", &controllerCreator); engine.load(QUrl(QLatin1String("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); } 中更改属性import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.3 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Hello World") Column{ anchors.fill: parent Text{ text: creator.propertyCreator() color: "blue" } Text{ text: creator.propertyCreator() color: "red" } Text{ text: creator.propertyCreator() color: "green" } } } ,并使用 string 编辑:此外,您应该像以前一样使用函数verbose_name = Profile

InlineModelAdmin

这样,结果应该是:

__str__

为什么您的钥匙被随机复制?

对于class MyCustomUserInline(admin.StackedInline): model = Profile can_delete = True verbose_name = "profile" def __str__(self): return 'API KEY: ' + str(self.api_key) ,Django将Profile: API KEY: 10c64d48-416f-4fd7-b01d-4328d2536ea2 类用作行名。预填充属性为verbose_name = Profile的字段。在这种情况下,Profile与:default

答案 1 :(得分:1)

p4 fetch 更改为 verbose_name ,而不是 STRING

Model Class

为什么显示 class MyCustomUserInline(admin.StackedInline): model = Profile can_delete = True verbose_name = "PROFILE" # Change is here <<<<< API KEY?

如果您使用的是random,它将使用模型的 verbose_name = Profile 方法。不幸的是,没有这样的 instance (实例),因此它使用了 __str__ ,因此返回了 随机UUID

证明

案例1

default
class Profile(models.Model):
    user = models.OneToOneField(MyUser, on_delete=models.CASCADE)
    api_key = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)

    def __str__(self):
        return 'API KEY: ' + str(self.api_key)