1

我被困在用戶註冊,我其實打算有不同的配置文件類型。註冊時,我無法在創建用戶時設置UserProfile。我正在使用UserCreationForm。我的文件中的代碼如下。django個人資料創建,設置用戶配置文件,同時使用多個配置文件類型

from django.contrib.auth.forms import UserCreationForm 
from registration.forms import RegistrationForm 
from django import forms 
from django.contrib.auth.models import User 
from accounts.models import UserProfile 
from django.utils.translation import ugettext_lazy as _ 
from person.models import Person 
from pprint import pprint 


class UserRegistrationForm(UserCreationForm): 
    #email = forms.EmailField(label = "Email") 
    fullname = forms.CharField(label = "Full name") 

    class Meta: 
     model = User 
     fields = ("email","fullname","password1","password2") 

    def __init__(self, *args, **kwargs): 
     super(UserRegistrationForm, self).__init__(*args, **kwargs) 
     del self.fields['username'] 

    def clean_email(self): 
     """ 
     Validate that the supplied email address is unique for the 
     site. 

     """ 
     if User.objects.filter(email__iexact=self.cleaned_data['email']): 
      raise forms.ValidationError(_("This email address is already in use. Please supply a different email address.")) 
     return self.cleaned_data['email'] 

    def save(self, commit=True): 
     user = super(UserRegistrationForm, self).save(commit=False) 
     #user_profile=user.set_profile(profile_type="Person") 

     UserProfile.profile.person.full_name = self.cleaned_data["fullname"] 
     user.email = self.cleaned_data["email"] 
     if commit: 
      user.save() 
     return user 

class CompanyRegistrationForm(UserCreationForm): 
    email=forms.EmailField(label="Email") 

class UserProfileForm(forms.ModelForm): 
    class Meta: 
     model=UserProfile 
     exclude=('user',) 

賬戶/ models.py

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


class UserProfile(models.Model): 
    user=models.OneToOneField(User) 
    meta_keywords=models.CharField("Meta Keywords",max_length=255, 
      help_text="Comma delimited set of keywords of meta tag") 
    meta_description=models.CharField("Meta Description",max_length=255, 
      help_text='Content for description meta tag') 

    def __unicode__(self): 
     return "User Profile for: "+self.username 

    class Meta: 
     ordering=['-id'] 

views.py

from django.contrib.auth.forms import UserCreationForm 
from django.template import RequestContext 
from django.shortcuts import render_to_response,get_object_or_404 
from django.core import urlresolvers 
from django.http import HttpResponseRedirect 
from django.contrib.auth.decorators import login_required 
from accounts.forms import UserRegistrationForm, UserProfileForm 
#from accounts.forms import UserProfile 

def register(request,template_name="account/register.html"): 
    if request.method=='POST': 
     postdata=request.POST.copy() 
     form=UserRegistrationForm(postdata) 
     user_profile=UserProfileForm(postdata) 
     if form.is_valid(): 
      form.save() 
      un=postdata.get('username','') 
      pw=postdata.get('password','') 
      from django.contrib.auth import login,authenticate 
      new_user=authenticate(username=un,password=pw) 
      if new_user and new_user.is_active: 
       login(request,new_user) 
       url=urlresolvers.reverse('dashboard') 
       return HttpResponseRedirect(url)  
    else: 
     form=UserRegistrationForm() 
    page_title="User Registration" 
    return render_to_response(template_name,locals(),context_instance=RequestContext(request)) 


@login_required 
def dashboard(request): 
    pass 

@login_required 
def settings(request): 
    pass 

正如我使用多個配置文件,以便以下是這些配置文件models.py中的一個的代碼:

from django.db import models 
from django.contrib.auth.models import User 
from accounts.models import UserProfile 

class Person(UserProfile): 
    skills=models.CharField(max_length=100) 
    fullname=models.CharField(max_length=50) 
    short_description=models.CharField(max_length=255) 
    is_online=models.BooleanField(default=False) 
    tags=models.CharField(max_length=50) 
    profile_pic=models.ImageField(upload_to="person_profile_images/") 
    profile_url=models.URLField() 
    date_of_birth=models.DateField() 
    is_student=models.BooleanField(default=False) 
    current_designation=models.CharField(max_length=50) 
    is_active_jobseeker=models.BooleanField(default=True) 
    current_education=models.BooleanField(default=True) 


    class Meta: 
     db_table='person' 

我的資料auth i ñsettings.py

AUTH_PROFILE_MODULE='accounts.UserProfile' 

這裏是也是我之後看一些其他地方,profile.py使用的文件: 從accounts.models導入用戶配置 從accounts.forms進口量從person.models進口UserProfileForm 人 從company.models進口公司

def retrieve(request,profile_type): 
    try: 
     profile=request.user.get_profile() 
    except UserProfile.DoesNotExist: 
     if profile_type=='Person': 
      profile=Person.objects.create(user=request.user) 
     else: 
      profile=Company.objects.create(user=request.user) 
     profile.save() 
    return profile 

def set(request,profile_type): 
    profile=retrieve(request,profile_type) 
    profile_form=UserProfileForm(request.POST,instance=profile) 
    profile_form.save() 

我是新和迷惑,看到的文檔也。也看到了stackoverflow.com的其他解決方案,但沒有找到我的問題的任何解決方案。所以請告訴你是否找到對我有用的東西。這似乎不是一個大問題,但由於我對它很陌生,所以對我來說這是一個問題。

回答

2

多個配置文件類型不能用於Django配置文件機制所需的OneToOne關係。我建議您保留一個包含所有配置文件類型通用數據的配置文件類,並將類型特定的數據存儲在單獨的一組類中,並使用generic relation鏈接到您的配置文件類。

編輯:

感謝您的澄清。今天再看看你的代碼,似乎你可能確實能夠完成你對模型繼承的嘗試。我認爲這個問題出現在UserRegistrationFormsave()方法中。嘗試這樣的:

def save(self, commit=True): 
    user = super(UserRegistrationForm, self).save(commit=False) 
    user.email = self.cleaned_data["email"] 
    if commit: 
     user.save() 
     person = Person(user=user) 
     person.full_name = self.cleaned_data["fullname"] 
     person.save() 
    return user 
+0

如果我用戶Foreignkey與唯一= True?我將如何連接它呢?因爲模型明智,我已經完成了研發工作,所以目前我在連接配置文件時遇到了問題,而用戶的註冊是我之前沒有做過的。所以我不知道如何連接,無論是父類是USerProfile和2個不同的人和公司繼承。 – Hafiz

+0

所以'Person(user = user)'將連接到Person,並更新'UserProfile'和'Person'表中的數據?那麼Django會通過這個陳述理解所有這些關係嗎?對不起愚蠢的問題,但我是新的,所以只是想了解,真的很感謝你的時間再次看它 – Hafiz

+0

我認爲它應該工作。雖然沒有測試過。你試過了嗎?任何問題特別是? –

相關問題