Reputation: 3
I have two application with two model. I would like to generate the following url structure: http://example.com/company/'companyslug'/worker/'workerslug'
In the url above the 'companyslug' and 'workerslug' are variables.
I already run over a many of posts but I didn't find any solution for it. The main problem is that, if the system generates link the value evaluated both times as an attribute of Worker model.
Do you have any idea, how can I generate a link as it looks like above?
Many thanks!
app1/models.py
class Company(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150, unique=True)
app2/models.py
class Worker(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
rel_company_worker = models.ForeignKey('app1.Company', on_delete = models.CASCADE, null=True,related_name='workers')
first_name = models.CharField(,max_length= 50, blank=True )
last_name = models.CharField(,max_length= 50, blank=True )
slug = models.SlugField(max_length=100, null=True)
I have 3 urls file: urls.py
urlpatterns = [
path("company/", include('app1.urls')),
]
app1/urls.py
urlpatterns = [
path('<slug:slug>/worker/',include('app2.urls')),
]
app2/urls.py
urlpatterns = [
path('<slug:slug>',views.WorkerDetailView.as_view(), name ='worker-detail-view'),
]
app2.views.py
class WorkerDetailView(generic.DetailView):
model = Worker
If I run the code it genearates the following link:
http://example.com/company/**'workerslug'**/worker/**'workerslug'**
Upvotes: 0
Views: 38
Reputation: 309069
You need to rename one of slugs, for example:
urlpatterns = [
path('<slug:company_slug>/worker/', include('app2.urls')),
]
Then override the queryset in the detail view to only include workers from the company.
class WorkerDetailView(DetailView):
def get_queryset(self):
queryset = super(WorkerDetailView, self).get_queryset()
return queryset.filter(rel_company_worker__slug=self.kwargs['company_slug'])
As an aside, your nested includes makes your urls hard to undertand. I would consider getting rid of the second include and changing it to:
urlpatterns = [
path('<slug:company_slug>/worker/<slug:slug>', views.WorkerDetailView.as_view(), name ='worker-detail-view'),
]
I would also consider renaming the foreign key to the Company
model to company
:
class Worker(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
company = models.ForeignKey('app1.Company', on_delete = models.CASCADE, null=True, related_name='workers')
...
Upvotes: 1