2014-11-02 81 views
0

我有我的項目一個用戶註冊系統,並配置文件系統同時,問題是,當我創建一個註冊的用戶也不會同時創建一個配置文件,由於這個原因,當我創建一個新的用戶試圖進入其自己的空間,我得到這個錯誤:創建配置文件與登記

用戶沒有用戶配置文件。

這是我的配置:

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 = '[email protected]' 
      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,'[email protected]',[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 

和我的網址.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'), 

我可以進入並從只有當我創建從管理面板輪廓

我的問題是用戶inteface編輯配置文件;我應該在我的配置中更改哪些內容以允許我在從用戶界面註冊新用戶的同時創建新配置文件?

我知道我可以與其他metods像「AbstractUser」註冊創建配置文件,但我更喜歡延長「用戶」,保留儘可能多的我的實際結構。

謝謝!!!

+0

?或者你想添加用戶配置文件字段到用戶模型(擴展'用戶'模型)? – 2014-11-02 12:03:29

+0

好吧,mi問題是當我創建一個用戶,我必須建立一個從管理員的配置文件,以後可以從用戶界面進行編輯。如果我創建管理面板配置文件,我可以編輯它,但如果我不從管理員爲每個用戶創建個人資料,我不能編輯我的個人資料,如用戶,我相信這是更好的,每個至少應使用默認信息自動生成的配置文件稍後每個用戶可以編輯他們自己的配置文件。 – Jhonny 2014-11-02 12:11:40

回答

1

變化photouserProfile這樣的:

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)) 
要創建`用戶profile`當寄存器用戶
+0

再次感謝您哈桑= d,我有一個cuestion,當你把'user_profile = USERPROFILE(名稱= FIRST_NAME,用戶=用戶,電子郵件=電子郵件)' 「用戶」 在我的情況 「usuario」?或者是另一個有價值的輸入? – Jhonny 2014-11-02 13:07:10

+0

對不起老兄。用戶是變量'u'。我編輯我的答案。 – 2014-11-02 13:17:25

+0

謝謝你的男人,完美運行,當我同時創建一個新用戶顯示其相應的配置文件,當我使用新的用戶,我可以進入並查看配置文件登錄。但是,如果我決定放一些照片或編輯(如用戶),例如usr電子郵件顯示'用戶配置文件與此用戶已存在。我怎麼能解決這個問題? – Jhonny 2014-11-02 13:46:15