注册时同时创建配置文件

时间:2014-11-02 11:35:00

标签: python django django-registration user-profile

我的项目和个人资料系统都有一个用户注册系统,问题是当我创建一个注册用户时,它不会同时创建一个配置文件,因此当我创建一个新用户并尝试输入对于自己的个人资料,我收到了这个错误:

用户没有用户配置文件。

这是我的配置:

views.py:

from django.shortcuts import render_to_response
from django.template import RequestContext
from dracoin.apps.synopticup.models import card
from dracoin.apps.home.forms import ContactForm,LoginForm,RegisterForm,userProfileForm
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth.models import User
from dracoin.settings import URL_LOGIN
from django.contrib.auth import login,logout,authenticate
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.contrib.auth.decorators import login_required



def index(request):
    return render_to_response('home/index.html',context_instance=RequestContext(request))

@login_required(login_url=URL_LOGIN)
def landing(request):
    return render_to_response('home/landing.html',context_instance=RequestContext(request))

@login_required(login_url=URL_LOGIN)
def shop(request,pagina):
    lista_tarj = card.objects.filter(status=True)
    paginator = Paginator(lista_tarj,5)
    try:
        page = int(pagina)
    except:
        page = 1
    try:
        tarjetas = paginator.page(page)
    except (EmptyPage,InvalidPage):
        tarjetas = paginator.page(paginator.num_pages)
    ctx = {'tarjetas':tarjetas}
    return render_to_response('home/shop.html',ctx,context_instance=RequestContext(request))

@login_required(login_url=URL_LOGIN)
def singleCard(request,id_tarj):    
    tarj = card.objects.get(id=id_tarj) 
    ctx = {'card':tarj}
    return render_to_response('home/singleCard.html',ctx,context_instance=RequestContext(request))  

@login_required(login_url=URL_LOGIN)
def contacto(request):
    info_enviado = False # Define si se envio la informacion o no
    email = ""
    titulo = ""
    texto = ""
    if request.method == "POST":
        formulario = ContactForm(request.POST)
        if formulario.is_valid():
            info_enviado = True
            email = formulario.cleaned_data['Email']
            titulo = formulario.cleaned_data['Titulo']
            texto = formulario.cleaned_data['Texto']
            # Configuracion de enviado de correos vis hotmail
            to_supp = 'elzipa25@gmail.com'
            html_content = "Informacion recibida<br><br><br>***Mensaje***<br><h3>%s<h3><br><br>%s<br><br>%s"%(titulo,email,texto)
            msg = EmailMultiAlternatives('Correo de Contacto',html_content,'from@server.com',[to_supp])
            msg.attach_alternative(html_content,'text/html') # Contenido definido como html
            msg.send()
    else:
        formulario = ContactForm()                      
    ctx = {'form':formulario,'email':email, 'titulo':titulo, 'texto':texto, 'info_enviado':info_enviado}
    return render_to_response('home/contacto.html',ctx,context_instance=RequestContext(request))

def login_view(request):
    mensaje = ""
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    else:
        if request.method == "POST":
            form = LoginForm(request.POST)
            if form.is_valid():
                next = request.POST['next']             
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']
                usuario = authenticate(username=username,password=password)
                if usuario is not None and usuario.is_active:
                    login(request,usuario)
                    return HttpResponseRedirect(next)
                else:
                    mensaje = "user or password aren't correct"
        next = request.REQUEST.get('next')      
        form = LoginForm()
        ctx = {'form':form,'mensaje':mensaje,'next':next}
        return render_to_response('home/login.html',ctx,context_instance=RequestContext(request))

def logout_view(request):
    logout(request)
    return HttpResponseRedirect('/')

def register_view(request):
    form = RegisterForm()
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']            
            usuario = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password_one = form.cleaned_data['password_one']
            password_two = form.cleaned_data['password_two']

            u = User.objects.create_user(first_name=first_name,username=usuario,email=email,password=password_one)
            u.save()
            return render_to_response('home/thanks_register.html',context_instance=RequestContext(request))
        else:
            ctx = {'form':form}
            return render_to_response('home/register.html',ctx,context_instance=RequestContext(request))
    ctx = {'form':form}
    return render_to_response('home/register.html',ctx,context_instance=RequestContext(request))

def edit_profile(request):
    user = request.user
    user_profile = user.userprofile

    if request.method == 'POST':
        user_profile_form = userProfileForm(request.POST)
        if user_profile_form.is_valid():
            #update user profile
            user_profile.name = request.POST['name']
            user_profile.user = user
            user_profile.email = request.POST['email']
            user_profile.save()
    else:
        user_profile_form = userProfileForm(instance=user_profile)
    variables = RequestContext( request, {
        'user_profile_form': user_profile_form}
    )
    return render_to_response( 'home/edit_profile.html', variables )

forms.py:

from django import forms
from django.contrib.auth.models import User
from dracoin.apps.home.models import userProfile

class ContactForm(forms.Form):
    Email = forms.EmailField(widget=forms.TextInput())
    Titulo = forms.CharField(widget=forms.TextInput())
    Texto = forms.CharField(widget=forms.Textarea())

class LoginForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput())
    password = forms.CharField(widget=forms.PasswordInput(render_value=False))


class RegisterForm(forms.Form):
    username = forms.CharField(label="Nombre de usuario",widget=forms.TextInput())
    first_name = forms.CharField(label="Telefono",widget=forms.TextInput()) 
    email = forms.EmailField(label="Correo Electronico",widget=forms.TextInput())
    password_one = forms.CharField(label="Password",widget=forms.PasswordInput(render_value=False))
    password_two = forms.CharField(label="Confirmar password",widget=forms.PasswordInput(render_value=False))

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            u = User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError('Nombre de usuario ya existe')

    def clean_email(self):
        email = self.cleaned_data['email']
        try:
            u = User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError('Email ya registrado')

    def clean_password_two(self):
        password_one= self.cleaned_data['password_one']
        password_two= self.cleaned_data['password_two']
        if password_one == password_two:
            pass
        else:
            raise forms.ValidationError('passwords no coincidentes')

class userProfileForm(forms.ModelForm):
    class Meta:
        model = userProfile

models.py:

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

def url(self,filename):
    ruta = "MultimediaData/Users/%s/%s"%(self.user.username,filename)
    return ruta

class userProfile(models.Model):    

    name = models.CharField(max_length=30, default='')  
    user = models.OneToOneField(User)
    photo = models.ImageField(upload_to=url)    
    email = models.EmailField(max_length=75)


    def __unicode__(self):
        return self.user.username

和我的urls.py:

from django.conf.urls import patterns, include, url


urlpatterns = patterns('',       

    url(r'^$','dracoin.apps.home.views.index' ,name='vista_principal'),
    url(r'^landing/$','dracoin.apps.home.views.landing' ,name='vista_aterrizaje'),
    url(r'^shop/page/(?P<pagina>.*)/$','dracoin.apps.home.views.shop' ,name='vista_tienda'),
    url(r'^card/(?P<id_tarj>.*)/$','dracoin.apps.home.views.singleCard',name='vista_single_card'),
    url(r'^contacto/$','dracoin.apps.home.views.contacto' ,name='vista_contacto'),
    url(r'^login/$','dracoin.apps.home.views.login_view',name='vista_login'),
    url(r'^logout/$','dracoin.apps.home.views.logout_view',name='vista_logout'),
    url(r'^registro/$','dracoin.apps.home.views.register_view',name='vista_registro'),
    url(r'^edit_profile/$','dracoin.apps.home.views.edit_profile', name='vista_profile'),

只有在我从管理面板

创建配置文件时,才可以从用户界面输入和编辑配置文件

我的问题是;当我从用户界面注册新用户时,我应该在配置中更改哪些内容以允许我同时创建新的配置文件?

我知道我可以使用其他类似“AbstractUser”的注册创建配置文件,但我更喜欢扩展“User”以尽可能地保留我的实际结构。

谢谢!!!

1 个答案:

答案 0 :(得分:1)

更改photo中的userProfile字段,如下所示:

class userProfile(models.Model):    
    name = models.CharField(max_length=30, default='')  
    user = models.OneToOneField(User)
    photo = models.ImageField(blank=True,upload_to=url)    
    email = models.EmailField(max_length=75)

def __unicode__(self):
    return self.user.username

这允许您添加没有照片的userprofile。

在创建新用户时,只需添加userProfile

def register_view(request):
    form = RegisterForm()
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']            
            usuario = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password_one = form.cleaned_data['password_one']
            password_two = form.cleaned_data['password_two']

            u = User.objects.create_user(first_name=first_name,username=usuario,email=email,password=password_one)
            u.save()

            #add user profile
            user_profile = userProfile(name=first_name,user=u,email=email)
            user_profile.save()

            return render_to_response('home/thanks_register.html',context_instance=RequestContext(request))
        else:
            ctx = {'form':form}
            return render_to_response('home/register.html',ctx,context_instance=RequestContext(request))
    ctx = {'form':form}
    return render_to_response('home/register.html',ctx,context_instance=RequestContext(request))