繁体   English   中英

在Django中扩展用户模型

[英]Extending User model in django

我正在尝试在django中注册用户以扩展auth模块。 我从这里到那里阅读,现在到处都是,不知道自己在做什么。 最初,我想做的就是用信息名称电子邮件手机密码注册用户。 由于mobile不在默认的django auth我尝试扩展auth

这是代码。

models.py

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

class CustomerUserProfile(models.Model):  
    mobile = models.CharField(max_length = 20)
    user = models.ForeignKey(User, unique=True)

    def __str__(self):  
          return "%s's profile" % self.user  

def create_user_profile(sender, instance, created, **kwargs):  
    if created:  
       profile, created = CustomerUserProfile.objects.get_or_create(user=instance)


post_save.connect(create_user_profile, sender=User)

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from neededform.models import CustomerUserProfile

class CustomerRegistrationForm(UserCreationForm):
    email = forms.EmailField(required = True)
    mobile = forms.CharField(max_length = 20)


    class Meta:
        model = User
        fields = ('username','email','mobile','password1','password2')

views.py

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from neededform.forms import CustomerRegistrationForm
from neededform.models import CustomerUserProfile
from django.contrib.auth.models import User

def register(request):


    if request.method == 'POST':

        form = CustomerRegistrationForm(request.POST)
        if form.is_valid():
            f = form.save()
        return HttpResponseRedirect('/registered/')

    else:
        args = {}
        args.update(csrf(request))
        args['form'] = CustomerRegistrationForm()

    return render_to_response('User_Registration.html', args ,context_instance = RequestContext(request))

该代码在执行时在auth_user表中创建一个条目,并在CustomerUserProfileauth_user一个条目,但移动对话框始终为空。
我还想在代码中添加什么?

PS。 请有人可以解释一下这段代码在做什么

def create_user_profile(sender, instance, created, **kwargs):  
        if created:  
           profile, created = CustomerUserProfile.objects.get_or_create(user=instance)


post_save.connect(create_user_profile, sender=User)

当我从某个地方复制它时,我想知道它是如何工作的。

谢谢。

这是一个已有2年历史的问题,但我很惊讶没有正确的答案。 仅由于您通过post_save信号创建了CustomerUserProfile ,而移动字段未保存在您的配置文件中,而post_save信号未转发移动字段。

我建议您在register函数中处理form.is_valid()时,只需更新CustomerUserProfile

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM