django配置文件创建,使用多个配置文件类型时设置用户配置文件 [英] django profile creation, set User profile while using multiple profile types

查看:158
本文介绍了django配置文件创建,使用多个配置文件类型时设置用户配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在用户注册,我实际上打算有不同的个人资料类型。注册时,创建用户时无法设置UserProfile。我正在使用UserCreationForm。我的文件中的代码如下。

 从django.contrib.auth.forms导入UserCreationForm 
from registration.forms导入RegistrationForm
从django导入表单
从django.contrib.auth.models import用户
从accounts.models import UserProfile
从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 =全名)

class Meta:
model =用户
fields =(email,fullname ,password1,password2)

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

def clean_email(self):

验证提供的电子邮件地址是否nique为
网站。


如果User.objects.filter(email__iexact = self.cleaned_data ['email']):
raise forms.ValidationError(_(此电子邮件地址为已经在使用,请提供不同的电子邮件地址。)
返回self.cleaned_data ['email']

def save(self,commit = True):
用户= 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]
如果提交:
user.save()
返回用户

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

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

accounts / models.py


$ b django.contrib.auth.models导入的$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ .Model):
user = models.OneToOneField(User)
meta_keywords = models.CharField(Meta关键字,max_length = 255,
help_text =元标记的逗号分隔的关键字集)
meta_description = models.CharField(Meta描述,max_length = 255,
help_text ='描述元标记的内容)

def __unicode __(self):
返回用户个人资料:+ self.username

class Meta:
order = [' - id']
pre>

views.py

  from django.contrib.auth。从django.template导入UserCreationForm 
导入RequestContext
从django.shortcuts import render_to_response,get_object_or_404
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from django.contrib.a uth.decorators import account_required
from accounts.forms import UserRegistrationForm,UserProfileForm
#from accounts.forms import UserProfile

def register(request,template_name =account / register.html )
如果request.method =='POST':
postdata = request.POST.copy()
form = UserRegistrationForm(postdata)
user_profile = UserProfileForm(postdata)
如果form.is_valid():
form.save()
un = postdata.get('username','')
pw = postdata.get('password' '')
从django.contrib.auth导入登录,验证
new_user = authenticate(username = un,password = pw)
如果new_user和new_user.is_active:
login( request,new_user)
url = urlresolvers.reverse('dashboard')
返回HttpResponseRedirect(url)
else:
form = UserRegistrationForm()
pa ge_title =用户注册
返回render_to_response(template_name,locals(),context_instance = RequestContext(request))


@login_required
def dashboard(request)
pass

@login_required
def设置(请求):
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 = False)
tags = models.CharField(max_length = 50)
profile_pic = models.ImageField(upload_to =person_profile_images /)
profile_url = models.URLField()
date_of_birth = models.Date Field()
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公司



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
b b b b b b b b b b b b b b b b b b b b b $ b如果profile_type =='Person':
profile = Perso n.objects.create(user = request.user)
else:
profile = Company.objects.create(user = request.user)
profile.save()
return个人资料

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

我是新的和困惑,也看过文档。还在stackoverflow.com看到其他解决方案,但没有找到任何解决我的问题。所以请告诉你是否找到有用的东西。这似乎不是一个大问题,但是我是新手,所以这对我来说是个问题。

解决方案

多个配置文件类型将无法与Django配置文件机制所需的OneToOne关系一起使用。我建议您保留包含所有配置文件类型共有的数据的单个配置文件类,并将类型特定的数据存储在使用通用关系



编辑:



感谢您的澄清。再次看看您的代码,似乎您可能确实能够完成您对模型继承的尝试。我认为问题在 save()方法 UserRegistrationForm 中。尝试这样的东西:

  def save(self,commit = True):
user = super(UserRegistrationForm,self ).save(commit = False)
user.email = self.cleaned_data [email]
如果提交:
user.save()
person = Person(user =用户)
person.full_name = self.cleaned_data [fullname]
person.save()
返回用户


I am stuck at user registration, I actually intends to have different profile types. While registration I am unable to set UserProfile while creating a user. I am using UserCreationForm. code in my files are as following.

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',)

accounts/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

As I am using multiple profiles so following is code of one of those profiles' 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'

My profile auth in settings.py

AUTH_PROFILE_MODULE='accounts.UserProfile'

Here is a file that also I used after looking at some other place, 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()

I am new and confuse, have seen documentation also. Also saw other solutions at stackoverflow.com but didn't find any solution of my problem. So please tell if you find anything helpful for me. It doesn't seems to be a big problem but as I am new to it so it is a problem for me.

解决方案

Multiple profile types won't work with the OneToOne relation that is required by Django profile mechanism. I suggest you keep a single profile class containing data common to all profile types and you store type-specific data in a separate set of classes that you link to your profile class using a generic relation.

EDIT:

Thanks for the clarification. Looking at your code again today it seems that you might indeed be able to accomplish what your trying to do with model inheritance. I think the problem is in the save() method of UserRegistrationForm. Try something like this:

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

这篇关于django配置文件创建,使用多个配置文件类型时设置用户配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆