[英]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
表中創建一個條目,並在CustomerUserProfile
中auth_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.