CreateView and get_context_data()

942 views
Skip to first unread message

Timothy W. Cook

unread,
Nov 22, 2013, 6:12:54 AM11/22/13
to django...@googlegroups.com
I am trying to setup some context variable for use in a template when
I execute a create view.

class ReviewTitleCreateView(CreateView):
model = Review
form_class = ReviewTitleCreateForm
template_name = 'papers/review_title.html'

def get_context_data(self, **kwargs):
context = super(ReviewTitleCreateView, self).get_context_data(**kwargs)
context['title'] = self.paper__title
print('Title: ',self.paper__title)
return context


def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})

def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
# <process form cleaned data>
form.save()
return HttpResponseRedirect('#')

return render(request, self.template_name, {'form': form})

The 'Title: ' isn't even printed in the terminal nor is it available
in the template. Well, it is available I suppose (there is no error)
but empty.

The Review model:
class Review(models.Model):
"""
A review at a specific stage of one paper.
"""
INCLUDE_CHOICES = [(True,'Include'),(False,'Exclude')]
STAGES = [('Selection by Title','Selection by Title'),('Selection
by Abstract','Selection by Abstract'), ('Selection by Full
Text','Selection by Full Text')]

paper = models.ForeignKey(Paper, verbose_name=_('Paper'),
related_name="%(app_label)s_%(class)s_related", null=False,
blank=False, help_text=_("The reviewed paper."))

include = models.NullBooleanField("Choice",
choices=INCLUDE_CHOICES, default=True, null=False, blank=False,
help_text="Select Include or Exclude for this stage of review.")

exclusion_choice = models.ForeignKey(Exclusion, null=True,
blank=True, related_name="%(app_label)s_%(class)s_related")

exclusion_text = models.TextField(null=True, blank=True)

def __str__(self):
return self.paper.title

===================================

Thoughts?






--
MLHIM VIP Signup: http://goo.gl/22B0U
============================================
Timothy Cook, MSc +55 21 94711995
MLHIM http://www.mlhim.org
Like Us on FB: https://www.facebook.com/mlhim2
Circle us on G+: http://goo.gl/44EV5
Google Scholar: http://goo.gl/MMZ1o
LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook

Lucas Magnum

unread,
Nov 22, 2013, 6:58:24 AM11/22/13
to django...@googlegroups.com
Timothy,
The "get_context_data" is called in get method, once you override it "get_context_data" isn't called anymore.








[]'s

Lucas Magnum.


2013/11/22 Timothy W. Cook <t...@mlhim.org>
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2B%3DOU3UmCCE-Dd%3DdjdVgCUpwG8N7DL37zXx_C3hWZCrbeV2C7Q%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.

Timothy W. Cook

unread,
Nov 22, 2013, 8:13:46 AM11/22/13
to django...@googlegroups.com
Lucas,

On Fri, Nov 22, 2013 at 9:58 AM, Lucas Magnum <lucasm...@gmail.com> wrote:
> Timothy,
> The "get_context_data" is called in get method, once you override it
> "get_context_data" isn't called anymore.
>

Right. So my thought process was that if I override it and place
additional information there it would be available in the template.
Obviously my thinking is incorrect, but where?

So how do I add variables to the context so that I can display their
value in the template?

In this case I want to get the title of the paper and display it in
the template. If I do this in get():

def get(self, request, *args, **kwargs):
paper = Paper.objects.filter(id=kwargs['pk'])
kwargs['title'] = paper[0].title
print('Title: ',kwargs['title'])
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})

IT prints it to the terminal okay. But (using DjDT) I do not see
where 'title' was added to kwargs. Not do I see it in the template
context.

Any idea what I am missing or how to do this?

Thanks,
Tim

Daniel Roseman

unread,
Nov 22, 2013, 8:38:48 AM11/22/13
to django...@googlegroups.com
On Friday, 22 November 2013 13:13:46 UTC, Timothy W. Cook wrote:
Lucas,

On Fri, Nov 22, 2013 at 9:58 AM, Lucas Magnum <lucasm...@gmail.com> wrote:
> Timothy,
> The "get_context_data" is called in get method, once you override it
> "get_context_data" isn't called anymore.
>

Right.  So my thought process was that if I override it and place
additional information there it would be available in the template.
Obviously my thinking is incorrect, but where?

Lucas means that by overriding get(), you've removed the place where `get_context_data` is originally called. You could certainly do it within your own `get()` function, simply with `context = self.get_context_data()`, but you might as well keep it within `get()` as you do below.

 
So how do I add variables to the context so that I can display their
value in the template?

In this case I want to get the title of the paper and display it in
the template.  If I do this in get():

    def get(self, request, *args, **kwargs):
        paper = Paper.objects.filter(id=kwargs['pk'])
        kwargs['title'] = paper[0].title
        print('Title: ',kwargs['title'])
        form = self.form_class(initial=self.initial)
        return render(request, self.template_name, {'form': form})

IT prints it to the terminal okay.  But (using DjDT) I do not see
where 'title' was added to kwargs.  Not do I see it in the template
context.

Any idea what I am missing or how to do this?


You've added it to kwargs, but you haven't passed kwargs as the template context - you've simply hard-coded that to `{'form': form}`. 
--
DR. 

Timothy W. Cook

unread,
Nov 22, 2013, 8:45:54 AM11/22/13
to django...@googlegroups.com
THanks Lucas and Daniel,
I 'think' I am starting to understand better.

def get(self, request, *args, **kwargs):
paper = Paper.objects.filter(id=kwargs['pk'])
kwargs['title'] = paper[0].title
kwargs['form'] = self.form_class(initial=self.initial)
return render(request, self.template_name, kwargs)

This works. However, what is the preferred/best practices way to do
this, using get_context_data() or just overriding get(). Does it
really matter?

Thanks,
Tim
Reply all
Reply to author
Forward
0 new messages