Get_Slug_Field() example for multiple slugs in Django 2.1?

Get_Slug_Field() example for multiple slugs in Django 2.1?



I want to find a way to add multiple slugs from different models to one view.



Either with get_slug_field and get_object; or other ways are appreciated as well..



But please, take into consideration that this is Generic View in which I am looking for the solution.




1 Answer
1



If your generic view is of type View, then you could declare it with the ContextMixin and then def get_context_data(**kwargs) on the view. If your view is a TemplateView, ListView, DetailView, etc., then you can do def get_context_data(**kwargs) without having to use a mixin.


View


def get_context_data(**kwargs)


TemplateView


ListView


DetailView


def get_context_data(**kwargs)



Example using plain View and ContextMixin (you would need to do proper importing where necessary):


View


ContextMixin



models.py:


class ModelOne(models.Model):
slug = models.SlugField(default='', max_length=75)


class ModelTwo(models.Model):
slug = models.SlugField(default='', max_length=75)



Note: max_length defaults to 50; the 75 is arbitrary



views.py


class MyView(View, ContextMixin):

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['slug_from_model_one'] = ModelOne.objects.get(...define your lookup...).slug
context['slug_from_model_two'] = ModelTwo.objects.get(...define your lookup...).slug
return context






Dear @Dan Swain, could you please show an example of code. I am trying to add two slugs into one Generic Detail View. I hope get_slug_field will help but I don't know how to write the code because I am a beginner.

– Ulvi Damirli
Sep 14 '18 at 17:56






Error: AttributeError at /study/corporate-finance/ Generic detail view SubjectDetailView must be called with either an object pk or a slug in the URLconf. I'm sure that I don't have a problem in my urlconf.

– Ulvi Damirli
Sep 14 '18 at 19:02







Because I have to add two different slugs, I have named them as subjectslug and studylevel slug.

– Ulvi Damirli
Sep 14 '18 at 19:04






Please post your url

– Dan Swain
Sep 14 '18 at 19:41






path('study/<slug:subjectslug>/', views.SubjectDetailView.as_view(), name='subject-detail'),

– Ulvi Damirli
Sep 14 '18 at 19:42




Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)