在将restframework用于现有项目后,Django返回404

时间:2017-03-13 11:26:07

标签: python django django-views

我已经准备好了工作项目,我在为URL添加API之后为APIViews添加了REST API以获得类似的功能它正在提供404

Views.py

class PostLikeAPIToggle(APIView):
authentication_classes = (authentication.SessionAuthentication,)
permission_classes = (permissions.IsAuthenticated,)

def get(self, request, id=None, format=None):
    obj = get_object_or_404(Post, id=id)
    url_ = obj.get_absolute_url() 
    user = self.request.user
    updated = False
    liked = False

    if user.is_authenticated():
        if user in obj.likes.all():
            liked = False
            obj.likes.remove(user)
        else:
            liked = True
            obj.likes.add(user)
        updated = True
    data = {
        "updated" : updated,
        "liked" : liked
    }
    return Response(data)

urls.py

from django.conf.urls import url
from django.contrib import admin
from posts import views
from rest_framework import routers
app_name = 'posts'
urlpatterns = [
url(r'^$', views.post_list, name='list'),
url(r'^create/$', views.post_create, name='create_post'),
url(r'^(?P<id>[\w-]+)/$', views.post_detail, name='detail'),
url(r'^(?P<id>[\w-]+)/edit/$', views.post_update, name='post_update'),
url(r'^api/(?P<id>[\w-]+)/like/$', views.PostLikeAPIToggle.as_view(), name='like-api-toggle'),
url(r'^(?P<id>[\w-]+)/like/$', views.PostLikeToggle.as_view(), name='like-toggle'),
url(r'^(?P<id>[\w-]+)/delete/$', views.post_delete),]

models.py

class Post(models.Model):
    user = models.ForeignKey(User,default=0)
    title = models.CharField(max_length=140)
    image = models.ImageField(upload_to = upload_location,
                    null=True,
                    blank=True, 
                    height_field="height_field", 
                    width_field = "width_field")
    likes = models.ManyToManyField(User,blank=True, related_name = 'post_likes')
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    content = models.TextField()
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

def __unicode__(self):
    return self.title

def get_absolute_url(self):
    return reverse("posts:detail", kwargs={"id": self.id})

def get_api_like_url(self):
    return reverse("posts:like-api-toggle", kwargs={"id": self.id})

def get_like_url(self):
    return reverse("posts:like-toggle", kwargs={"id": self.id})



class Meta:
    ordering = ["-timestamp" , "-updated" ]

我正在重定向 http://127.0.0.1:8000/api/posts/1/like

它给我404请帮助

1 个答案:

答案 0 :(得分:1)

根据上述评论,您的身边会出现错误的硬编码网址。

而不是访问http://127.0.0.1:8000/api/posts/1/like,您应该访问http://127.0.0.1:8000/posts/api/1/like

请注意,您的根urls.py内有这个:

url(r'^posts/', include("posts.urls", namespace='posts'))

并在posts.urls内:

url(r'^api/(?P<id>[\w-]+)/like/$', views.PostLikeAPIToggle.as_view(), name='like-api-toggle')

因此,URL的正确结构是:

[--- from root urls.py ----] [--from posts urls--]
http://127.0.0.1:8000/posts/      api/1/like/

你也可以像这样确定网址:

> ./manage.py shell

from django.urls import reverse

print(reverse('posts:like-api-toggle', kwargs={'id': 1}))

注意:您还可以从app_name = 'posts' app中删除urls.py。您正在定义根namespaceurls.py

中的include("posts.urls", namespace='posts')

希望能帮到你!