Nov 29, 2012

URL Design using base36

http://pydanny.com/case-study-url-design-for-petcheatsheetscom.html

/<pet_id:base_36_encoded>/<pet_name:not_required>/
class Pet(models.Model):
    name = models.CharField(_("Pet's name"), max_length=100)
    identifier = models.CharField(_("identifier"), max_length=50,
        null=True, blank=True, db_index=True)
class PetCreateView(LoginRequiredMixin, CreateView):
    model = Pet
    form_class = PetForm

    def form_valid(self, form):
        pet = form.save()
        pet.identifier = base36.encode(pet.pk)
        pet.owner = self.request.user
        # Save again - it's not taking THAT many server cycles AND we needed
        #    the pet.pk in advance to generate the pet.identifier
        pet.save()
        return super(PetCreateView, self).form_valid(form)
urlpatterns = patterns("",

    url(
        regex=r"^(?P[\w\d]+)/(?P[\w\d\-\_]+)/$",
        view=views.PetDetailView.as_view(),
        name="pet_detail",
    ),
)

No comments: