在我的项目中添加profile.html页面

时间:2014-11-01 12:21:20

标签: python django django-views user-profile

我在我的网站上放了一个部分来填充一个名为profile.html的userprofile表单。我现在有这个models.py在我的管理面板上显示这些信息:

from 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

我想在每个用户的个人资料中启用编辑此信息的可能性,因此我可以在我的管理面板(localhost:8000 / admin)中审核每个用户的用户个人资料信息。创建相应的好形式是什么查看它和网址?

这实际上是我的urls.py(这不是主要的urls.py,对我的应用来说是一个特殊的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'),

这是我的个人资料的models.py:

from 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

我的views.py(缺少userProfile视图)

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
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 = userProfile(request-POST)
        if user_profile_form.is_valid():
            update user profile
    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)

1 个答案:

答案 0 :(得分:1)

试试这个:

1-将此添加到urls.py

url(r'^edit_profile/$', 'dracoin.apps.home.views.edit_profile', name='edit_profile'),

2-在form中创建user_profileviews.py视图:

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

#view
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( 'edit_profile.html', variables )

3-添加edit_profile.html模板:

<div> 
    <form  method="POST" action="."> 
        {% csrf_token %} 
            {{ user_profile_form.as_p }} 
        <input type="submit" name="edit_profile" value="Done"> 
    </form>        
</div>