I would like to get some advice from the community.

I have recenlty started learning Django and have a question regarding the structure of the application.

I have a URL, a DetailView for my Asset model which also has two card blocks that houses data for two other models Tenant and Service. Check the screenshot below.

enter image description here

I am generating the above view from the asset/views.py file. Code as below.

class AssetMultipleDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView):
    model = Asset
    context_object_name = 'asset'
    template_name = 'asset/asset_multiple_detail.html'

    def test_func(self):
        asset_multiple = self.get_object()
        if self.request.user == asset_multiple.owner:
            return True
        return False

    def get_context_data(self, **kwargs):
        context = super(AssetMultipleDetailView, self).get_context_data(**kwargs)
        context['tenants'] = Tenant.objects.filter(asset=context['asset']).order_by('created')
        context['services'] = Service.objects.filter(asset=context['asset']).order_by('created')
        return context

When you click on the Add New Tenant button, I use the below URL in tenant/urls.py

path('new/asset/<int:pk>/', TenantAssetCreateView.as_view(), name='tenant_asset_create'),

This URL generates a CreateView for Tenant. I use the primary key of the asset in the URL to load up only the right asset to the Asset selection field. Please see the image below.

enter image description here

Everything works well.

I would like to know whether is this the best way to achieve this? Will this be easily maintainable as there are more views similar to this upcoming in the application.

Any advice is much appreciated. Thank you in advance.

1 Answers

NKay On Best Solutions

I am not quite sure what your models look like. Does tenant have a manytomany relation to asset (a tenant can be related to any amount of assets)? Or does tenant have a foreign key to asset in your design (a tenant has exactly one related asset)? Based on the screenshot I assume the latter.
Or do you want an asset to only have one tenant (foreign key on asset to tenant)?

Loading the correct asset from the URL is perfectly valid. You should maybe make asset in the form disabled, so it can not be manipulated.

In the CreateView you could override form_valid(self,form) to set self.object.asset to the one you need.