【问题标题】:'BlogPostResource' object has no attribute 'request'“BlogPostResource”对象没有“请求”属性
【发布时间】:2012-08-22 07:29:19
【问题描述】:

我正在学习 Django REST Framework 并正在研究这个示例;

http://django-rest-framework.org/examples/blogpost.html

但是当我尝试打开 http://localhost:8000/blog-post/ 时出现此错误

AttributeError at /blog-post/
'BlogPostResource' object has no attribute 'request'
Request Method: POST
Request URL:    http://localhost:8000/blog-post/
Django Version: 1.4.1
Exception Type: AttributeError
Exception Value:    
'BlogPostResource' object has no attribute 'request'
Exception Location: /Users/wolfiem/PycharmProjects/TestRestApi/TestApp/resources.py in url, line 16
Python Executable:  /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.2
Python Path:    
['/Users/wolfiem/PycharmProjects/TestRestApi',
 '/Library/Python/2.7/site-packages/pexpect-2.4-py2.7.egg',
 '/Library/Python/2.7/site-packages/pythondialog-2.7-py2.7.egg',
 '/Library/Python/2.7/site-packages/pymongo-2.2.1-py2.7-macosx-10.7-intel.egg',
 '/Library/Python/2.7/site-packages/riak-1.4.1-py2.7.egg',
 '/Library/Python/2.7/site-packages/pip-1.1-py2.7.egg',
 '/Library/Python/2.7/site-packages/MySQL_python-1.2.3-py2.7-macosx-10.8-intel.egg',
 '/usr/local/lib/python2.7/site-packages',
 '/opt/local/bin',
 '/Library/Python/2.7/site-packages',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC']

这些是我在示例中的文件:

resources.py

from djangorestframework.resources import ModelResource
from djangorestframework.resources import reverse
from TestApp.models import BlogPost,Comment

class BlogPostResource(ModelResource):
    """
    A Blog Post has a *title* and *content*, and can be associated with zero or more comments.
    """
    model = BlogPost
    fields = ('created','title','slug','content','url','comments')
    ordering = ('-created',)

    def url(self, instance):
        return reverse('blog-post',
                        kwargs = {'key':instance.key},
                        request=self.request)

    def comments(self, instance):
        return reverse('comments',
                        kwargs = {'blogpost':instance.key},
                        request=self.request)

class CommentResource(ModelResource):
    """
    A Comment is associated with a given Blog Post and has a *username* and *comment*, and optionally a *rating*.
    """
    model = Comment
    fields = ('username','comment','created','rating','url','blogpost')
    ordering = ('-created',)

    def blogpost(self, instance):
        return reverse('blog-post',
                        kwargs={'key':instance.blogpost.key},
                        request=self.request)

models.py

from django.db import models
from django.template.defaultfilters import slugify
import uuid

def uuid_str():
    return str(uuid.uuid1())

# Create your models here.

RATING_CHOICES = ((0, 'Awful'),
    (1, 'Poor'),
    (2, 'OK'),
    (3, 'Good'),
    (4, 'Excellent'))

MAX_POSTS = 10

class BlogPost(models.Model):
    key = models.CharField(primary_key=True, max_length=64, default=uuid_str(), editable=False)
    title = models.CharField(max_length=128)
    content = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(editable=False,default='')

    def encode(self):
        return self.encode('utf8')

    def save(self, force_insert=False, force_update=False, using=None):
        """
        Save
        """
        self.slug = slugify(self.title)
        super(self.__class__,self).save()
        for obj in self.__class__.objects.order_by('-created')[MAX_POSTS:]:
            obj.delete()

class Comment(models.Model):
    blogpost = models.ForeignKey(BlogPost,editable=False,related_name='comments')
    username = models.CharField(max_length=128)
    comment = models.TextField()
    rating = models.IntegerField(blank=True,null=True,choices=RATING_CHOICES,help_text='How did you rate this post?')
    created = models.DateTimeField(auto_now_add=True)

urls.py

from django.conf.urls import patterns, url
from djangorestframework.views import ListOrCreateModelView,InstanceModelView
from TestApp.resources import BlogPostResource,CommentResource

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'TestRestApi.views.home', name='home'),
    # url(r'^TestRestApi/', include('TestRestApi.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
#    url(r'^restframework', include('djangorestframework.urls', namespace='djangorestframework')),
    url(r'^$', ListOrCreateModelView.as_view(resource=BlogPostResource), name='blog-post-root'),
    url(r'^(?P<key>[^/]+)/$', InstanceModelView.as_view(resource=BlogPostResource), name='blog-post'),
    url(r'^(?P<blogpost>[^/]+)/comments/$',ListOrCreateModelView.as_view(resource=CommentResource), name='comments'),
    url(r'^(?P<blogpost>[^/]+)/comments/(?P<id>[^/]+)/$', InstanceModelView.as_view(resource=CommentResource)),
)

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    我发现了问题。我已经编辑了如下几行。

    def url(self, instance): 
    

    作为

    def url(self,request,instance):
    

    【讨论】:

      猜你喜欢
      • 2014-06-26
      • 2015-08-17
      • 2023-03-26
      • 2018-06-20
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多