使用Django-Registration扩展用户模型 [英] Extending the user model with Django-Registration

查看:128
本文介绍了使用Django-Registration扩展用户模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django版本:4.0.2
Django注册版本:0.8
应用名称:userAccounts



PROBLEM:
我尝试创建扩展用户模型的名为professor的用户类型。我可以完成注册过程,问题是只有用户被保存在DB上,教授表保持空。所以我认为问题可能在保存方法。一些关于可能是什么问题的线索?



SETTINGS.PY

  AUTH_PROFILE_MODULE =userAccounts.Professor

MODELS.PY -
这里我创建模型从django.db导入模型
从django.contrib.auth.models从用户和示例字段

 导入用户

class教授(models.Model):
user = models.ForeignKey(User,unique = True)
exampleField = models.CharField(max_length = 100)

FORMS.PY -
保存用户时,我将一个new_profile保存在教授表中。

 从django导入表单
from registration.forms import RegistrationForm
从模型导入教授
从registration.models import RegistrationProfile

class CustomRegistrationForm(RegistrationForm):
exampleField = forms.CharField()

def save(self,profile_callback = None):
new_u ser = RegistrationProfile.objects.create_inactive_user(
username = self.cleaned_data ['username'],
password = self.cleaned_data ['password1'],
email = self.cleaned_data ['email '])
new_professor = Professor(
user = new_user,
exampleField = self.cleaned_data ['exampleField'])
new_professor.save()
return new_user

注意:我遵循这篇文章:配置文件字段的注册表格

解决方案

问题解决 - 解决方案



已经有几天了,但我得到了! :D
i发现这个帖子从shacker:
Django-Registration& Django-Profile,使用您自己的自定义表单



显然在django-registration中0.8 save()方法不能被覆盖。
所以,其他两个选项是:
使用信号或重写后端。



两个解决方案都在我链接的帖子中解释。如果有人有同样的问题,我会尝试帮助评论:)



注意:使用信号工作正常,但从表单中获取值时有一些问题。所以我实现后端方法,一切顺利。我强烈推荐你阅读shacker的帖子,但如果你真的很吝啬,我的代码:



我的forms.py

  class RegistrationForm(forms.Form):
username = forms.RegexField(regex = r'^ \w + $',
max_length = 30,
widget = forms.TextInput(attrs = attrs_dict),
label = _(Username),
error_messages = {'invalid':_必须只包含字母,数字和下划线。)
email = forms.EmailField(widget = forms.TextInput(attrs = dict(attrs_dict,
maxlength = 75)),
标签= _(电子邮件地址))
password1 = forms.CharField(widget = forms.PasswordInput(attrs = attrs_dict,render_value = False),
label = _(Password))
password2 = forms.CharField(widget = fo rms.PasswordInput(attrs = attrs_dict,render_value = False),
label = _(Password(again)))

#ADITIONAL FIELDS
#they被传递给后端作为kwargs,并保存
nombre = forms.CharField(widget = forms.TextInput(attrs = attrs_dict),
label = _(Nombre))

__ init__.py(app / user_backend / __ init __。py)

  class DefaultBackend(object):
def register(self,request,** kwargs):
username,email,password,nombre = kwargs [ 'username'],kwargs ['email'],kwargs ['password1'],kwargs ['nombre']
如果Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
new_user = RegistrationProfile.objects.create_inactive_user(用户名,电子邮件,
密码,网站)
signals.user_registered.send(sender = self .__ class__,
user = new_user,
request = request)

usuario(user = User。 objects.get(username = new_user.username),nombre = nombre).save()
return new_user

根URLS.PY 之前这行 - > url(r'profiles /',include('profiles.urls')),

  url(r'^ accounts / registrar_usuario / $',
'registration.views.register',
{'backend':'Hesperides.apps。 accounts.user_regbackend.DefaultBackend','form_class':user_RegistrationForm},
name ='registration_register'
),

谢谢



mattsnider为您的耐心和显示我非常非常有用的pdb。从西班牙问候。
和:shacker和dmitko显示方式


Django version: 4.0.2 Django-Registration version: 0.8 App name: userAccounts

PROBLEM: Im trying to create a user type called professor extending the user model. I can complete the registration process, the problem is that only the user is saved on the DB, the professor table keep empty. So i think the problem could be in the save method. Some clue about what could be the problem?

SETTINGS.PY

AUTH_PROFILE_MODULE = "userAccounts.Professor"

MODELS.PY - Here i create the model that extending from user and a example field

from django.db import models
from django.contrib.auth.models import User

class Professor(models.Model):
  user = models.ForeignKey(User, unique=True)
  exampleField = models.CharField(max_length=100)

FORMS.PY - When a user is saved, i save a new_profile in the professor table.

from django import forms
from registration.forms import RegistrationForm
from models import Professor
from registration.models import RegistrationProfile

class CustomRegistrationForm(RegistrationForm):
  exampleField = forms.CharField()

  def save(self, profile_callback=None):
    new_user = RegistrationProfile.objects.create_inactive_user(
        username=self.cleaned_data['username'],
        password=self.cleaned_data['password1'],
        email = self.cleaned_data['email'])
    new_professor = Professor(
        user=new_user, 
        exampleField=self.cleaned_data['exampleField'])
    new_professor.save()
    return new_user

NOTE: Im following this post: Registration form with profile's field

解决方案

PROBLEM SOLVED - SOLUTION

Have been some days but i got it! :D i found this post from shacker: Django-Registration & Django-Profile, using your own custom form

apparently in django-registration 0.8 save() method can't be override. so, the other two options are: Use signals or Rewrite the backend.

both solutions are explained in the post i linked. If someone have the same problem i'll try to help in the comments :)

NOTE: Using signals worked fine but i had some problems taking the values from the form. So i implemented the backend method and everything went ok. I strongly recomend you read shacker's post but, if you are really desesperate, theres my code:

my forms.py

class RegistrationForm(forms.Form):
    username = forms.RegexField(regex=r'^\w+$',
                            max_length=30,
                            widget=forms.TextInput(attrs=attrs_dict),
                            label=_("Username"),
                            error_messages={'invalid': _("This value must contain only letters, numbers and underscores.")})
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
                                                           maxlength=75)),
                         label=_("Email address"))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
                            label=_("Password"))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
                            label=_("Password (again)"))

    #ADITIONAL FIELDS
    #they are passed to the backend as kwargs and there they are saved
    nombre = forms.CharField(widget=forms.TextInput(attrs=attrs_dict),
                            label=_("Nombre"))

__init__.py (app/user_backend/__init__.py)

class DefaultBackend(object):
def register(self, request, **kwargs):
        username, email, password, nombre = kwargs['username'], kwargs['email'], kwargs['password1'], kwargs['nombre']
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        new_user = RegistrationProfile.objects.create_inactive_user(username, email,
                                                                password, site)
        signals.user_registered.send(sender=self.__class__,
                                 user=new_user,
                                 request=request)

        usuario(user = User.objects.get(username=new_user.username), nombre=nombre).save()
        return new_user

root URLS.PY before this line -> url(r'profiles/', include('profiles.urls')),

    url(r'^accounts/registrar_usuario/$',
'registration.views.register',
{'backend': 'Hesperides.apps.accounts.user_regbackend.DefaultBackend','form_class':user_RegistrationForm},        
name='registration_register'
),

Thanks

mattsnider for your patience and for show me the very, very usefull pdb. Regards from spain. and: shacker and dmitko for show me the way

这篇关于使用Django-Registration扩展用户模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆