Home > front end >  How to pass data (specific fiiled) from views.py to models.py
How to pass data (specific fiiled) from views.py to models.py

Time:11-02

I have a problem. How can i pass the data (def maybe) from models.py I need this for filter by category in future

class Tag(models.Model):
.......
    category = models.ForeignKey(Category, null=True, on_delete=models.PROTECT, related_name='category', verbose_name='Tag category')
......

def get_category(self):
return self.category

To views.py. This is it doesn't work

class GetDetailTag(DetailView):
model = Tag
template_name = 'main/catalog.html'
context_object_name = 'tag'
category = Tag.get_category



def get_context_data(self, *, object_list=None, **kwargs):
    context = super().get_context_data(**kwargs,)
    context['pansion_in_tag_list'] = Pansions.objects.filter(tags__slug=self.kwargs['slug'])
    context['tags_in_category'] = Tag.objects.filter(category__slug = '...INSERT THE DATA FROM MODEL HERE...')
    return context

I was trying to call the 'def'(get_category) in views.py

Anyway? How i can to do that?

CodePudding user response:

You can just obtain this from the tag, so:

{{ tag.category }}

or in the DetailView:

class TagDetailView(DetailView):
    model = Tag
    template_name = 'main/catalog.html'
    context_object_name = 'tag'

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        context['pansion_in_tag_list'] = Pansions.objects.filter(
            tags__slug=self.kwargs['slug']
        )
        context['tags_in_category'] = Tag.objects.filter(
            category_id=self.object.category_id
        )
        # category = self.object.category (obtain the category)
        return context
  • Related