1

So what I'm trying to do is pass another model object (Question) to my view.The view currently returns a get_queryset of another model (Post). So this is the context I want to pass through so I can render it in my polls.html:

question = get_object_or_404(Question, id=1)
context = {'question': question})

urls.py

BV = BoxesView.as_view()

urlpatterns = [
    url(r'^$', BV, name='news')
]

view.py

class BoxesView(ListView):
    template_name = 'polls.html'

    def get_queryset(self):
        queryset_list = Post.objects.all().filter(category=1).order_by('-date')
        return queryset_list

polls.html

{% extends 'parent.html' %}

{% block polls %}

<p>question goes here</p> #this shows up
{{ question.question_text }} #this doesn't show up


{% endblock %}

parent.html

{% extends 'base.html' %}

{% block content %}

        {% for post in post_list %}

            {% block polls %}

            {% endblock %}

        {% endfor %}

{% endblock %}

models.py

class Post(models.Model):
    title = models.TextField(max_length=70)

class Question(models.Model):
    question_text = models.CharField(max_length=70)
Zorgan
  • 8,227
  • 23
  • 106
  • 207
  • as i understand i have to do like this on your view `from myapp.models import Questions`. So you just need to import from another app your model – Zagorodniy Olexiy Nov 12 '16 at 03:48
  • Ok so I just did that: from .models import Question, question = get_object_or_404(Question, id=1) - Now how do I pass it through as context? – Zorgan Nov 12 '16 at 09:37

2 Answers2

0

You have to import it into your view. from myapp.models import Questions. Then you can use it, for example:

question = Questions.objects.get(pk=1)

If you have the same name of the model you can import like this: from myapp.models import Questions as Question1

Zagorodniy Olexiy
  • 2,132
  • 3
  • 22
  • 47
  • Ok so I've done that now, but that's just making the variable. How do I pass it through as context? Right now it's doing nothing. – Zorgan Nov 12 '16 at 09:41
0

You need to override the get_context_data() method:

class BoxesView(ListView):
    ...

    def get_context_data(self, **kwargs):
        context = super(BoxesView, self).get_context_data(**kwargs)
        question = get_object_or_404(Question, id=1)
        context['question'] = question
        return context

Here you can find similar example and other useful stuff.

Stonecold
  • 348
  • 1
  • 2
  • 10
  • Thankyou very much, this works. Do you mind explaining this line of code and how it's working? I'm not too familiar with super() so i'd like some clarification: context = super(BoxesView, self).get_context_data(**kwargs) – Zorgan Nov 12 '16 at 09:50
  • There you can find some cool answers: [link](http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods) – Stonecold Nov 12 '16 at 13:22