Reputation: 300
Hi I would like to create a custom url in my django admin.
The default URL when editing an object is.
http://localhost:8000/admin/cart/cart_id/change
In my admin
http://localhost:8000/admin/cart/1/change
I have a field called cart unique id. I want to create a custom url that behaves similar to the edit URL in django admin.
http://localhost:8000/admin/cart/uniq_id/change
http://localhost:8000/admin/cart/H2KPAT/change
Is this implemation possible?
Upvotes: 1
Views: 1413
Reputation: 32244
By default the admin will use the primary key of your model for the admin urls, you could set this unique field as the primary key of the model to achieve this.
your_field = models.TypeOfField(primary_key=True)
If you don't want to do this you could override the get_object
method of your model admin
def get_object(self, request, object_id, from_field=None):
queryset = self.get_queryset(request)
model = queryset.model
# This would usually default to the models pk
field = model._meta.get_field('you_field') if from_field is None else model._meta.get_field(from_field)
try:
object_id = field.to_python(object_id)
return queryset.get(**{field.name: object_id})
except (model.DoesNotExist, ValidationError, ValueError):
return None
Upvotes: 1
Reputation: 657
In your model, if you use a primary key made by yourself instead of the django id it will work.
class Cart(models.Model):
my_key = models.IntegerField(primary_key=True)
# my_key will be show in the url in the admin panel.
Upvotes: 0