1

我被困在用户注册上,我实际上打算拥有不同的个人资料类型。注册时,我无法在创建用户时设置 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',)

帐户/模型.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']

视图.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'

我在 settings.py 中的个人资料身份验证

AUTH_PROFILE_MODULE='accounts.UserProfile'

这是我在查看其他地方后使用的文件 profile.py: from accounts.models import UserProfile from accounts.forms import UserProfileForm from person.models import Person from 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 上看到了其他解决方案,但没有找到任何解决我的问题的方法。因此,请告诉您是否发现任何对我有帮助的东西。这似乎不是一个大问题,但由于我是新手,所以这对我来说是个问题。

4

1 回答 1

2

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

编辑:

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

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
于 2012-04-29T18:45:05.913 回答