【问题标题】:Extending the user model with Django-Registration使用 Django-Registration 扩展用户模型
【发布时间】:2013-01-23 17:27:53
【问题描述】:

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

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

SETTINGS.PY

AUTH_PROFILE_MODULE = "userAccounts.Professor"

模型.PY - 在这里,我创建了从用户和示例字段扩展的模型

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 - 保存用户后,我会在教授表中保存一个 new_profile。

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

注意:我关注这个帖子:Registration form with profile's field

【问题讨论】:

  • 仅供参考,Professor 模型没有扩展 User 模型,它正在创建对 User 模型的外键引用。
  • 另外,Django 抛出的错误是什么?
  • 没有错误,我可以完成注册过程。问题是 MySQL 中 userAccounts_profile 表为空,而用户添加正确。
  • 您在哪里定义 Profile 模型?上面的代码应该出错,因为 Profile 没有在任何地方定义/包含。如果您将 Profile 替换为 Professor,它应该保存到 userAccount_professor 表中。
  • 感谢您的帮助!配置文件模型来自先前的尝试。我修复了它,遗憾的是问题仍然存在。我更新了代码。

标签: django model extend django-registration


【解决方案1】:

问题已解决 - 解决方案

已经有几天了,但我明白了! :D 我从 shacker 找到了这篇文章: Django-Registration & Django-Profile, using your own custom form

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

这两种解决方案都在我链接的帖子中进行了解释。如果有人有同样的问题,我会尽力帮助 cmets :)

注意:使用信号效果很好,但我在从表单中获取值时遇到了一些问题。所以我实现了后端方法,一切顺利。我强烈建议您阅读 shacker 的帖子,但是,如果您真的绝望,那就是我的代码:

我的表单.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 在此行之前 -> 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 给我指路

【讨论】:

    猜你喜欢
    • 2012-07-18
    • 2016-10-12
    • 2011-02-28
    • 2013-12-06
    • 2018-01-21
    • 2018-04-24
    • 2017-03-02
    相关资源
    最近更新 更多