Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango - Pass model name as parameter to generic view
    primarykey
    data
    text
    <p>Let's say I have some Models that inherit from a base class, Animal. I can use generic views and route Cat/12 to a detail view and Dod/10 to the same detail view with a different context. But I would like to get the Model name from the url so that I dont have to define a route.</p> <p>I have something like this:</p> <pre><code>url(r'^cat/(?P&lt;slug&gt;[-\w]+)/$', DetailView.as_view( queryset=Cat.objects.filter(), model=Cat, context_object_name='animal', template_name='animal/detail.html'), name='detail'), url(r'^dog/(?P&lt;slug&gt;[-\w]+)/$', DetailView.as_view( queryset=Dog.objects.filter(), model=Dog, context_object_name='animal', template_name='animal/detail.html'), name='detail'), ... </code></pre> <p>Obviously, this is too much repetitive code. I would rather do something like this:</p> <pre><code>url(r'^?P&lt;my_animal&gt;\w+/(?P&lt;slug&gt;[-\w]+)/$', DetailView.as_view( queryset=my_animal.objects.filter(), model=my_animal, context_object_name='animal', template_name='animal/detail.html'), name='detail'), ... </code></pre> <p>Can I do this?</p> <p><strong>EDIT</strong></p> <p>Here's what I ended up with, thanks to Darwin's help. It avoids the if/else to get the Model name:</p> <pre><code>class AnimalDetailView(DetailView): context_object_name='animal' template_name='animals/detail.html' def dispatch(self, request, *args, **kwargs): my_animal = kwargs.get('my_animal', None) self.model = get_model('animals',my_animal.capitalize()) try: ret = super(AnimalDetailView, self).dispatch(request, *args, **kwargs) except AttributeError: raise Http404 return ret def get_queryset(self): return self.model.objects.filter() </code></pre> <p>Next time I have a question about Inheritance, I'll consult Darwin! LoL</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload