ValidationError:不是Django中的有效UUID

时间:2018-01-04 19:03:13

标签: django django-urls django-2.0

我正在使用Django 2.0

我有一个Note表和StarredNotes表。

最初,没有id字段,因为Django默认添加integer数据类型。

现在我已将模型

中的id的数据类型更改为UUID

model.py

class Starred(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    note = models.ForeignKey(Note, on_delete=models.CASCADE)

    objects = StarredManager()

class ColorLabels(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=100, unique=True)
    value = models.CharField(max_length=100)
    default = models.BooleanField(default=False)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title + '(' + self.value + ')'

views.py

class StarredNotes(ListView):
    template_name = 'notes/starred.html'
    model = Starred
    context_object_name = 'starred_notes'

    def get_queryset(self):
        starred_notes = Starred.objects.filter(user=self.request.user).order_by('-updated')
        return starred_notes

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

urls.py

app_name = 'notes'
urlpatterns = [
    url(r'^$', MyNotes.as_view()),
    url(r'^my/$', MyNotes.as_view(), name='my'),
    path('<pk>/', NoteUpdate.as_view(), name='update'),
    path('share-public/<pk>/', ShareNotePublic.as_view(), name='share-public'),
    path('starred-notes/', StarredNotes.as_view(), name='starred'),
    path('shared-notes/', SharedNotes.as_view(), name='shared'),
    path('delete/<pk>/', DeleteNote.as_view(), name='delete'),
    path('new/', NewNote.as_view(), name='new'),
    path('<pk>/public/', PublicNoteView.as_view(), name='public-view'),
]

但是当我使用

访问视图时
http://127.0.0.1:1234/notes/starred-notes/

它会出错

ValidationError at /notes/starred-notes/

["'starred-notes' is not a valid UUID."]

1 个答案:

答案 0 :(得分:2)

您的path('<pk>/', NoteUpdate.as_view(), name='update'),模式过于常见,并且会拦截星号注释网址。您需要将其移至列表底部或更好地添加uuid转换器path('<uuid:pk>/', NoteUpdate.as_view(), name='update')