我正在尝试在django中注册扩展auth
模块的用户。我从这里和那里读到,现在我到处都是,不知道我在做什么。
最初我想要做的是向用户注册信息名称,电子邮件,移动和密码。由于移动不在默认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
表中创建一个条目,在CustomerUserProfile
中创建一个条目,但移动颜色始终为空。
我还想在代码中添加什么?
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)
当我从某个地方复制它时,我想知道它是如何工作的。
谢谢。
答案 0 :(得分:0)
这是一个2岁的问题,但我很惊讶没有正确答案。
移动字段不会保存在您的个人资料中,只是因为您通过post_save信号创建了CustomerUserProfile
,并且移动字段不会通过post_save信号转发。
我建议您在register
函数中处理form.is_valid()时更新MGC <- as.factor(c("1A", "2Y", "1e", "5e"))
firstplace <- function(x) strsplit(as.character(x), "")[[1]][1]
sapply(MGC, firstplace)
。