Master_yugi
Master_yugi

Reputation: 45

Generic view for different models in django

To summarize the project, I am working on a website that categorizes electronic devices. Each electronic device has a category (Phone, Tablet, Computer, etc...), a manufacturer (Apple, Samsung, Dell, etc...) and the device itself (iPhone 6, iPhone X, Samsung S21, etc...).

I have a single template for the 3 different models (Category, Manufacture, Device) and I am looking to simplify the views which are currently just a copy and paste.

Here is the current code:

@login_required(login_url="/login/")
def show_category(request):
    groups = Category.objects.all()
    return render(request, "groups/group.html", {'group': 'Category', 'groups': groups})


@login_required(login_url="/login/")
def show_manufacturer(request):
    groups = Manufacturer.objects.all()
    return render(request, "groups/group.html", {'group': 'Manufacturer', 'groups': groups})


@login_required(login_url="/login/")
def show_device(request):
    groups = Device.objects.all()
    return render(request, "groups/group.html", {'group': 'Device', 'groups': groups})

Additionally, I have some POST functions which are also copy pastes of the same function for the different models to the same template.

I have been able to find examples where multiple models are used at the same time for one template, but I cannot for the life of me seem to find an example of using different models for the same template.

Can someone link me to an example or the docs that explains how to accomplish this ?

I feel like I have missed something from reading the docs, or maybe I simply don't quite grasp the whole models, views, templates way of doing it in Django as I feel this is supposed to be the whole concept of Django, simplifying the code in such ways using powerful views and templates.

Thank you !

Upvotes: 1

Views: 115

Answers (1)

Tim Nyborg
Tim Nyborg

Reputation: 1649

This is the sort of case where Class-based Views shine, because of the ability to inherit. Though this might be overkill if you're only doing three views

class GroupListView(LoginRequiredMixin, ListView):
    template_file = 'groups/group.html'

    def get_context_data(self, *args, **kwargs):
        data = super().get_context_data(*args, **kwargs)
        data['group'] = self.model._meta.verbose_name
        return data

class ShowCategory(GroupListView):
    model = Category

class ShowManufacturer(GroupListView):
    model = Manufacturer

class ShowDevice(GroupListView):
    model = Device

Upvotes: 1

Related Questions