Django:使用slug而不是pk

时间:2018-09-01 18:30:51

标签: python django

使用pk的代码如下:

views.py

class CreatorUpdate(LoginRequiredMixin, UpdateView):
    model = Creator
    fields = ['first_name', 'last_name', 'location', 'country']
    success_url = reverse_lazy('index')

    # these two methods only give access to the users own profile but not the others (prevents url hacking)
    def user_passes_test(self, request):
        if request.user.is_authenticated:
            self.object = self.get_object()
            return self.object.user == request.user
        return False

    def dispatch(self, request, *args, **kwargs):
        if not self.user_passes_test(request):
            return redirect_to_login(request.get_full_path())
        return super(CreatorUpdate, self).dispatch(request, *args, **kwargs)

urls.py

path('creator/<int:pk>/update/', views.CreatorUpdate.as_view(), name='creator-update')

HTML片段以调用URL:

<a href="{% url 'creator-update' user.pk %}">{{ user.get_username }}</a>

现在,我想使用子弹(用户名)而不是pk来访问UpdateView。我可以成功将用户名传递给URL:

<a href="{% url 'creator-update' user.get_username %}">{{ user.get_username }}</a>

但似乎无法在 urls.py

中进行匹配
path('creator/<slug:slug>/update/', views.CreatorUpdate.as_view(), name='creator-update')

具有相同的逻辑。我还尝试在我的Creator模型中设置SlugField,如下所示:

from django.template.defaultfilters import slugify
class Creator(models.Model):
    ...
    username = models.CharField(max_length=100)
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.username)
        super(Creator, self).save(*args, **kwargs)

    ...

在UpdateView中设置slug_field = 'slug'也不会得到它。

这些修改导致404错误:由catalog.views.CreatorUpdate: No creator found matching the query引发

将HTML部分调整为<a href="{% url 'creator-update' user.creator.slug %}">{{ user.get_username }}</a>时,出现NoReverseMatch错误Reverse for 'creator-update' with arguments '('',)' not found

使用子弹访问视图的逻辑是什么?

2 个答案:

答案 0 :(得分:2)

错误是用户对象没有属性段。 Creator模型具有“ slug”字段。创建创建者模型的ListView,然后检查每个创建者对象是否有一个段。

答案 1 :(得分:1)

更正 models.py

class Creator(models.Model):
    ...
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.user)
        super(Creator, self).save(*args, **kwargs)