Note that there are some explanatory texts on larger screens.

plurals
  1. POManually get response from class-based generic view
    text
    copied!<p>I'm trying to write a test that validates HTML returned from a generic class-based view. Let's say I have this function-based view that simply renders a template:</p> <pre><code># views.py from django.shortcuts import render def simple_view(request, template='template.html'): return render(request, template) </code></pre> <p>With that, during testing I can just do:</p> <pre><code># tests.py from django.http import HttpRequest from .views import simple_view request = HttpRequest() response = simple_view(request) </code></pre> <p>and then do the validation on the <code>response</code>. Now I would like to convert the above to a class-based view inheriting from TemplateView:</p> <pre><code># views.py from django.views.generic import TemplateView class SimpleView(TemplateView): template_name = 'template.html' </code></pre> <p>Now essentially the same testing method fails:</p> <pre><code># tests.py from django.http import HttpRequest from .views import SimpleView request = HttpRequest() view_func = SimpleView.as_view() response = view_func(request).render() </code></pre> <p>results in</p> <pre><code>Traceback (most recent call last): File "tests.py", line 30, in test_home_page_returns_correct_html response = view_func(request).render() File "lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "lib/python2.7/site-packages/django/views/generic/base.py", line 82, in dispatch if request.method.lower() in self.http_method_names: AttributeError: 'NoneType' object has no attribute 'lower' </code></pre> <p>I've tried setting <code>request.method</code> manually to <code>GET</code>, but that just brings up another error complaining about <code>session</code> not being in <code>request</code>.</p> <p>Is there a way of getting a response from TemplateView with "empty" request?</p>
 

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