为什么要显示此错误'功能'对象没有属性' as_view'

时间:2016-04-17 18:16:57

标签: python django django-models django-views django-urls

我想更新我的用户个人资料数据。但是在运行时遇到此错误'功能'对象没有属性' as_view'。

我正在使用Django 1.8,python 2.7

我是Django的新手。

urls.py代码:

from django.conf.urls import include, url
from . import views
urlpatterns = [

url(r'^(?P<pk>\d+)/$',
    views.UserProfileDetail.as_view(),
    name='user_profile_detail'),
url(r'^(?P<pk>\d+)/update/$',
    views.UserProfileUpdate.as_view(),
    name='user_profile_edit'),
]

views.py:

from django.shortcuts import render
from blog.models import Post, UserProfile
from blog.forms import UserForm, UserProfileForm, PostForm
from django.contrib.auth.models import User
from django.views.generic import DetailView
from django.views.generic import CreateView, UpdateView
from .models import UserProfile

class UserProfileDetail(DetailView):
    model = UserProfile

@login_required
class UserProfileUpdate(UpdateView):
    model = UserProfile
    fields = ('name', 'website',)

    def get(self, request, *args, **kwargs):
        UserProfile(kwargs['pk'])
        return (super(UserProfileUpdate, self).
                get(self, request, *args, **kwargs))

models.py

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

class UserProfile(models.Model):
    user = models.OneToOneField(User)

    name = models.CharField(max_length=30)
    website = models.URLField(blank=True)

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

HTML:

{% extends 'blog/base.html' %}
{% block content %}
<h2>Edit {{ object.user.username }} Profile</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Update" />
</form>
{% endblock %}

2 个答案:

答案 0 :(得分:0)

您的UserProfileUpdate视图应如下所示:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required


class UserProfileUpdate(UpdateView):
    model = UserProfile
    fields = ('name', 'website',)

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(UserProfileUpdate, self).dispatch(self, request, *args, **kwargs)

答案 1 :(得分:0)

你不能在类这样的类上使用login_required装饰器。您需要使用method_decorator。在Django 1.9+上,你可以装饰这个类:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class UserProfileUpdate(UpdateView):
    model = UserProfile
   fields = ('name', 'website',)

另请查看Django/python: 'function' object has no attribute 'as_view' @Alasdair举例和解释