Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malero/659142 to your computer and use it in GitHub Desktop.
Save malero/659142 to your computer and use it in GitHub Desktop.
Django URLs
from django.conf.urls.defaults import *
from shoppingcart import views
urlpatterns = patterns('shoppingcart.views',
url(r'^products/(?P<slug>[^\/]+)/$',
view=views.product,
name='shoppingcart-product'),
url(r'^\.php\?pid=(?P<slug>[0-9]+)$',
view=views.product,
name='shopping-cart-old'),
)
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponsePermanentRedirect
from django.core.urlresolvers import reverse
def product(request, slug):
# Product ID where we start 301 Redirects
redirect_before = 15
# If slug is numeric, find the product from Product.id
if slug.isdigit():
product = get_object_or_404(Product, id=int(slug))
# If the slug isn't numeric, we find the product from Product.slug
else:
product = get_object_or_404(Product, slug=slug)
# If the Product.id is equal to or less than redirect_before,
# we 301 Redirect to our new URL
if product.id <= redirect_before:
return HttpResponsePermanentRedirect(reverse('shoppingcart-product', args=[product.slug,]))
return render_to_response('shoppingcart/product.html', {'product':product})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment