1

I'm using this to generate my primary keys as I don't want them to be simple numbers easy to guess (found it in this post):

def make_uuid():
return base64.b64encode(uuid.uuid4().bytes).replace('=', '')

Here is my model:

class Shipment(models.Model):
    trackid = models.CharField(max_length=36, primary_key=True, default=make_uuid, editable=False)

How can I make my DetailView view work when I use the url myapp.com/detail/trackid_goes_here? I've tried everything that I saw here and I still can't make it work.

Also, is there a better way to get unique primary keys than using uuid?

Thanks!

UPDATE:

It now shows the template using this in my views.py:

class ShipmentDetailView(DetailView):
    template_name = 'shipments/detail.html'
    context_object_name = 'shipment'

    def get_object(self):
        model = Shipment.objects.get(pk=self.kwargs['trackid'])

And urls.py:

url(r'app/detail/(?P<trackid>[\w\d-]+)/$', coreviews.ShipmentDetailView.as_view(), name='shipment'),

BUT the "tags" used on the template ( {{ shipment.trackid }} ) are not working...

Community
  • 1
  • 1
alexherce
  • 13
  • 4

2 Answers2

0

Why not just encrypt the normal sequential ids instead? To someone who doesn't know the encryption key, the ids will seem just as random. You can write a wrapper that automatically decrypts the ID on the way to the DB, and encrypts it on the way from the DB. I think this is a good way to solve your problem, and only you know the encrypt or the decrypts algorithm.

tolerious
  • 144
  • 1
  • 10
0

The reason your template tags are not working is because you need to actually return the instance in get_object():

def get_object(self):
    return Shipment.objects.get(pk=self.kwargs['trackid'])

If you don't return anything, the method returns None (its the default return value); and thus your templates have nothing to show.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • Crap... thanks it worked! I used `model = get_object_or_404(Shipment, pk=self.kwargs['trackid']) return model` to get the 404 if there is no valid trackid in the url. – alexherce Apr 29 '15 at 05:04