django - 使用 Django-Registration 扩展用户模型

标签 django model extend django-registration

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

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

设置.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)

表格.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

最佳答案

问题已解决 - 解决方案

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

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

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

注意:使用信号效果很好,但我在从表单中获取值时遇到了一些问题。所以我实现了后端方法,一切正常。我强烈建议您阅读 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 为我指路

关于django - 使用 Django-Registration 扩展用户模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14764248/

相关文章:

c# - 接口(interface)中的静态

uml - <extend> UML 中的依赖

c++ - 在 C++ 中扩展数组

python - 如何将一个列表添加到另一个列表

python - AttributeError at/'tuple' 对象没有属性 '_meta'

django - 为两个可选参数设置 Django url 格式的最佳方法是什么?

python - 在modelForm中访问request.user

mysql - 如果我使用 Django South 运行迁移并且崩溃了,我的数据库是否已损坏?

java - MVC模型中的一对多关系

django - 如何使用带有外键字段的 'get' 方法?