无法使用viewname解析超链接关系的URL

时间:2015-07-14 12:49:16

标签: django-rest-framework

models.py:

from django.db import models
from pygments.lexers import get_all_lexers
from pygments.formatters.html import HtmlFormatter
from pygments import highlight


LEXERS = [item for item in get_all_lexers() if item[1]]

class Classname(models.Model):
    class_name = models.CharField(max_length=5)
    owner = models.ForeignKey('auth.User', related_name='fab')
    highlighted = models.TextField()

def save(self, *args, **kwargs):
    lexer = get_lexer_by_name(self.class_name)
    options = self.class_name and {'class': self.class_name} or {}
    formatter = HtmlFormatter(full=True, **options)

    self.highlighted = highlight(self.class_name, lexer, formatter)
    super(Classname, self).save(*args, **kwargs)

serializers.py:

from django.forms import widgets
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Classname

class ClassSerializer(serializers.HyperlinkedModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    highlight = serializers.HyperlinkedIdentityField(view_name='fab-highlight', format='html')
    class Meta:
        model = Classname
        fields = ('id', 'owner', 'class_name', 'highlight',)

class UserSerializer(serializers.ModelSerializer):
    fab = serializers.HyperlinkedRelatedField(many=True, view_name='user-detail', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'fab',)

urls.py:

from django.conf.urls import url, patterns
from rest_framework.urlpatterns import format_suffix_patterns
from . import views


urlpatterns = [
    url(r'^class/$', views.ClassList.as_view()),
    url(r'^class/(?P<pk>[0-9]+)/$', views.ClassDetail.as_view()),
    url(r'^section/$', views.SectionList.as_view()),
    url(r'^section/(?P<pk>\d+)/$', views.SectionDetail.as_view()),
    url(r'^teacher/$', views.TeacherList.as_view()),
    url(r'^teacher/(?P<pk>[0-9]+)/$', views.TeacherDetail.as_view()),
    url(r'^attend/$', views.AttendanceList.as_view()),
    url(r'^attend/(?P<pk>[0-9]+)/$', views.AttendanceDetail.as_view()),
]

当我更改我的serializers.py文件并尝试按照教程添加HyperLinked时,我得到了上述错误,我没有使用ViewSet和路由器。我不知道问题是什么,因为我检查了我的网址,并且看来一切都很好。

我很困惑,请帮我找到并解决问题.... 在此先感谢.....

1 个答案:

答案 0 :(得分:0)

确切的问题是我在url中使用了命名空间,我也在我的项目级别urls.py文件中使用了它。所以在views文件中我必须遵循这样的django-namespacing:

'users': reverse('student:user-list', request=request, format=format),

虽然'student'是我在项目级网址中使用的命名空间,如:

url(r'^stu/', include('app.urls', namespace = 'student'),