我想在Django中向用户添加权限?

时间:2019-11-02 08:06:36

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

我想添加用户个人资料部分,例如超级用户和simple_user,以便我可以添加权限

但是当我提交注册表格时,我得到了这个错误:

AttributeError at /register/
'User' object has no attribute 'register'

如何修复和保存用户个人资料名称?

这是我的 Views.py

from django.shortcuts import render , get_object_or_404,redirect
from django.utils import timezone
from blog.models import *
from blog.forms import *
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
                                    DetailView,CreateView,
                                    UpdateView,DeleteView)
# Create your views here.

def user_register(request):
    if request.method == "POST":
        reg = register(request.POST or None)
        if reg.is_valid():
            user = reg.save()
            user.profile = "simple_user"
            user.set_password(user.password)
            user.save()
        else:
            print(register.errors)
    else:
        reg = register()

    return render(request,"registration/register.html",{'reg':reg})

这是我的 Models.py

class register(models.Model):
    user = models.OneToOneField(User,on_delete="Cascade", related_name="profile")

这是我的 Forms.py

class register(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'input-field'}))
    class Meta():
        model = User
        fields = ('username','email','password')

这是错误图片:

enter image description here

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

尝试

user = reg.save()
p1 = register(user=user, #other colums if have)  # register model
p1.save()
# user.profile = "simple_user"
user.set_password(user.password)
user.save()

希望有帮助