shortcuts.rst 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. =========================
  2. Misago Shortcut Functions
  3. =========================
  4. Just like `Django <https://docs.djangoproject.com/en/dev/topics/http/shortcuts/>`_, Misago defines shortcuts module that reduce some procedures to single functions.
  5. This module lives in :py:mod:`misago.views.shortcuts` and in addition to Misago-native shortcut functions, it imports whole of :py:mod:`django.shortcuts`, so you don't have to import it separately in your views.
  6. validate_slug
  7. -------------
  8. .. function:: validate_slug(model, slug)
  9. This function compares model instance's "slug" attribute against user-friendly slug that was passed as link parameter. If model's slug attribute is different this function, :py:class:`misago.views.OutdatedSlug` is raised. This exception is then captured by Misago's exception handler which makes Misago return permanent (http 301) redirect to client with valid link.
  10. Example of view that first fetches object form database and then makes sure user or spider that reaches page has been let known of up-to-date link::
  11. from misago.views.shortcuts import validate_slug, get_object_or_404
  12. from myapp.models import Cake
  13. def cake_fans(request, cake_id, cake_slug):
  14. # first get cake model from DB
  15. cake = get_object_or_404(Cake, pk=cake_id)
  16. # issue redirect if cake slug is invalid
  17. validate_slug(cake, cacke_slug)
  18. .. note::
  19. You may have noticed that there's no exception handling for either Http404 exception raised by ``get_object_or_404``, nor ``OutdatedSlug`` exception raised by ``validate_slug``. This is by design. Both exceptions are handled by Misago for you so you don't have to spend time writing exception handling boiler plate on every view that fetches objects from database and validates their links.
  20. Naturally if you need to, you can still handle them yourself.
  21. .. note::
  22. Your links should use "slug" parameters only when they are supporting GET requests. For same reason you should call ``validate_slug`` only when request method is GET or HEAD.