5👍
✅
You don’t need to override get_object()
method. You can simply use slug_url_kwarg
and slug_field
. Like this:
class CarDetailView(generic.DetailView):
model = CarInstance
template_name = 'car_detail'
slug_field = 'title'
slug_url_kwarg = 'car_model'
More information can be found in get_object()
documentation.
1👍
Although this is too late.However, someone could find it helpful.You can modify your modules as below:
Your models.py:
import uuid as uuid_lib
class CarInstance(models.Model):
manufacturer = models.ForeignKey('Manufacturer', on_delete=models.SET_NULL, null=True)
car_model = models.CharField('Model', max_length=50, null=True)
uuid = models.UUIDField(
db_index=True,
default=uuid_lib.uuid4,
editable=False,
unique=True,)
urls.py:
path('car/<uuid:uuid>/', views.CarDetailView.as_view(), name='car-detail'),
Lastly your views.py:
class CarDetailView(generic.DetailView):
model = CarInstance
template_name = 'car_detail'
slug_field = 'uuid'
slug_url_kwarg = 'uuid'
- [Django]-Connect to a PostgreSQL database on a Docker container
- [Django]-Accessing MultipleChoiceField choices values
0👍
- Create get_absolute_url() in models.py:
def get_absolute_url(self):
return reverse('car-detail', args=[str(self.<yourUUIDFieldName>)]) # self.car_model
- Set URL in urls.py:
urlpatterns = [
path('car/<uuid:yourUUIDFieldName>/', # 'car:<uuid:car_model'>
views.CarDetailView.as_view(), name='car-detail'),
]
- Try to change the views:
class CarDetailView(DetailView):
model = CarInstance
slug_field = '<uuid:yourUUIDFieldName>' # -> 'car_model'
slug_url_kwarg = '<uuid:yourUUIDFieldName>' # -> 'car_model'
template_name = 'car_detail.html'
- In addition try this if you like:
import uuid
car_model = models.UUIDField(default=uuid.uuid4, unique=True)
Replace yourUUIDFieldName
with car_model
check if this works,
in my way, i have no idea, i’m just a beginner like others, hope u get something out of it
- [Django]-Using Django CreateView to handle formset – It doesnt validate
- [Django]-How to get parameters from current url
Source:stackexchange.com