django配置文件创建,在使用多个配置文件类型时设置用户配置文件

时间:2012-04-29 17:05:37

标签: django django-models django-forms django-users django-profiles

我在用户注册时遇到困难,我实际上打算使用不同的配置文件类型。注册时我无法在创建用户时设置UserProfile。我正在使用UserCreationForm。我的文件中的代码如下。

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 in settings.py

AUTH_PROFILE_MODULE='accounts.UserProfile'

这是我在查看其他地方后使用的文件profile.py:         来自accounts.models导入UserProfile     来自accounts.forms导入UserProfileForm     来自person.models import Person     来自company.models import Company

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上看到了其他解决方案,但没有找到我的问题的任何解决方案。所以请告诉我你是否找到了对我有用的东西。它似乎不是一个大问题,但因为我是新手,所以对我来说这是一个问题。

1 个答案:

答案 0 :(得分:2)

多个配置文件类型不适用于Django配置文件机制所需的OneToOne关系。我建议您保留一个包含所有配置文件类型通用数据的配置文件类,并将类型特定数据存储在使用generic relation链接到配置文件类的单独一组类中。

修改

感谢您的澄清。今天再次查看您的代码,您似乎确实能够完成您尝试使用模型继承所做的事情。我认为问题出在save()的{​​{1}}方法中。尝试这样的事情:

UserRegistrationForm