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

标签 python django django-views user-profile

我在我的网站上放置了一个部分来填写名为 profile.html 的用户配置文件表单。我现在有这个 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,并且缺少配置文件的 url)

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 View )

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- 将其添加到urls.py:

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

2- 在 views.py 中创建 formuser_profile View :

# 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>

关于python - 在我的项目中添加 profile.html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26689253/

相关文章:

python - 如何获取张量的类型?

python - 如何从 Django 中的不同模型生成 feed?

python - (Django) DetailView 模板不显示信息

java - WEKA 库 M5P 返回 Java 异常

python - 使用 python3(linux) 设置 selenium 时遇到问题

python - 从 pandas 中的列列表创建新列

django,尝试操作查询集并返回模板

python - Django:手动获取一个URL对应的 View

javascript - 在 django 模板中嵌入 javascript 代码

python - 在 Django 中使用方法 ="get"创建表单