将XP字段添加到默认用户模型

时间:2019-03-30 21:05:46

标签: python django

因此,在过去的一个小时里,我一直在努力为默认用户模型实现XP字段。我研究了django文档,发现有两种自定义身份验证的方法-扩展用户模型或更改它。

我决定仅对其进行扩展,因为将来只需要再添加两个或三个字段即可。 (我正在尝试仅添加此XP字段rn,以便可以了解应如何操作)

我以为我成功了,直到遇到这个错误: “经理”对象没有属性“创建用户”

据我所知,发生这种情况是因为create_user方法绑定到User,并且我更改了模型。这是产生错误的行:

// Key the rows by their bandnumber:
foreach($coiArray as $row) {
    $hash[$row["bandnumber"]] = $row;
}
foreach($hash as &$row) {
    // Replace children with the corresponding row in the hash
    foreach(["s","d"] as $prop) {
        $child = $row[$prop];
        if (!isset($hash[$child])) continue;
        $row[$prop] =& $hash[$child];
        $children[] = $child; // Keep track of non-root bandnumbers
    }
}
// Only needed when you don't know which bandnumber is the root:
$root = current(array_diff(array_keys($hash), $children, ["s","d"]));

$result = $hash[$root];

所以我做错了。

代码如下: views.py

user = Utilizator.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name)

models.py

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User
from .models import Utilizator
from django.contrib import auth

# Create your views here.
def login(req):
    if req.method == 'POST':
        username = req.POST['username']
        password = req.POST['password']
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            auth.login(req, user)
            messages.success(req, 'Acum eşti logat')
            return redirect('dashboard')
        else:
            messages.error(req, 'Numele de utilizator sau parola sunt greşite')
            return redirect('login')
        return
    else:
        return render(req, "../templates/pagini/login.html")
def register(req):
    if req.method == 'POST':
        first_name = req.POST['first_name']
        last_name = req.POST['last_name']
        username = req.POST['username']
        email = req.POST['email']
        password = req.POST['password']
        password2 = req.POST['password2']

        if password == password2:
            if User.objects.filter(username=username).exists():
                messages.error(req, 'Numele de utilizator deja există')
                return redirect('register')
            else:
                if User.objects.filter(email=email).exists():
                    messages.error(req, 'E-mailul este deja folosit')
                    return redirect('register')
                else:
                    user = Utilizator.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name)
                    user.save()
                    messages.success(req, 'Acum eşti logat')
                    return redirect('login')
        else:
            messages.error(req, 'Parolele diferă')
            return redirect('register')
    else:
        return render(req, "../templates/pagini/register.html")
def dashboard(req):
    return render(req, "../templates/pagini/dashboard.html")

我不知道这是否是正确的方法。我是一个初学者,我想学习应该怎么做。

那么使用这个models.py可以吗?如果是的话,我应该更改为views.py吗?

如果不是,您能教我该怎么做吗?非常感谢。

1 个答案:

答案 0 :(得分:0)

您非常亲密。如您所说,有两种扩展User的主要方法。 1)创建一个新模型并从AbstractUser继承(很复杂),或者2)创建一个具有1对1关系的单独模型(如上所示,更简单)。

基本实现是将User对象扩展为UserProfile,然后在每次调用user.profile时使其可访问/自动生成。

示例:

class UserProfile(models.Model):
    """ Extends the User model with a UserProfile """
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='userprofileAsUser')
    xp = models.IntegerField(default=0)

    uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)

    def __str__(self):
        return '{0}'.format(self.user.username)

    class Meta:
        verbose_name = "user profile"
        verbose_name_plural = "user profiles"

def get_or_create_profile(user):
    profile, created = UserProfile.objects.get_or_create(user=user)
    return profile

User.profile = property(get_or_create_profile)