0

我有一个 QR 码指向我网站中不存在的 URL。我不想只为那个二维码创建一个页面,而只是将用户重定向到主页。我目前使用的是 Django 1.4.5,我确信必须有一个简单的解决方案。

我确实发现的一件事是我将其放入我的 urls.py 文件中:

from django.views.generic import RedirectView
urlpatterns = patterns('',
    (r'^bad-QR-url/not-here$', RedirectView.as_view(url='/')),

但是,这似乎不起作用。这是 Django 1.5 的代码吗?无论如何,任何帮助都会很棒。

谢谢!

4

1 回答 1

1

编写您自己的 404 处理程序或通过覆盖 get_object 函数来更改 QR 视图行为。

class QRView(DetailView):
    def get_object(self, queryset=None):
        """
        Returns the object the view is displaying.

        By default this requires `self.queryset` and a `pk` or `slug` argument
        in the URLconf, but subclasses can override this to return any object.
        """
        # Use a custom queryset if provided; this is required for subclasses
        # like DateDetailView
        if queryset is None:
            queryset = self.get_queryset()

        # Next, try looking up by primary key.
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        slug = self.kwargs.get(self.slug_url_kwarg, None)
        if pk is not None:
            queryset = queryset.filter(pk=pk)

        # Next, try looking up by slug.
        elif slug is not None:
            slug_field = self.get_slug_field()
            queryset = queryset.filter(**{slug_field: slug})

        # If none of those are defined, it's an error.
        else:
            raise AttributeError(u"Generic detail view %s must be called with "
                                 u"either an object pk or a slug."
                                 % self.__class__.__name__)

        try:
            obj = queryset.get()
        except ObjectDoesNotExist:
            # REDIRECT GOES HERE.
        return obj
于 2013-09-30T09:20:44.097 回答