Preview Exception on Wagatil: Couldn't create request mock object - request middleware

320 views
Skip to first unread message

sachit adhikari

unread,
Aug 22, 2014, 3:43:19 AM8/22/14
to wag...@googlegroups.com
Hi,

I am getting the following exception in the preview:

Exception at /admin/pages/106/edit/preview/ Couldn't create request mock object - request middleware returned a response Request Method: POST Request URL
raise Exception("Couldn't create request mock object - " Exception Type: Exception at /admin/pages/106/edit/preview/ Exception Value: Couldn't create request mock object - request middleware returned a response Request information: GET: No GET data POST: body = u'



I haven't modified serve method. What is the cause of this?

Karl Hobley

unread,
Aug 22, 2014, 4:01:47 AM8/22/14
to wag...@googlegroups.com
Hi,

What do you have set in your MIDDLEWARE_CLASSES setting?

A traceback would be really useful for helping us find where the problem is.

Thanks,

Karl

sachit adhikari

unread,
Aug 22, 2014, 1:20:51 PM8/22/14
to wag...@googlegroups.com

Full Traceback:

Exception at /admin/pages/128/edit/preview/ Couldn't create request mock object - request middleware returned a response Request Method: POST Request URL: http://54.54.23.45/admin/pages/128/edit/preview/ Django Version: 1.6.5 Python Executable: /app/.heroku/python/bin/python Python Version: 2.7.8 Python Path: ['/app', '/app/.heroku/python/lib/python2.7/site-packages/setuptools-5.4.1-py2.7.egg', '/app/.heroku/python/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg', '/app', '/app/.heroku/python/lib/python27.zip', '/app/.heroku/python/lib/python2.7', '/app/.heroku/python/lib/python2.7/plat-linux2', '/app/.heroku/python/lib/python2.7/lib-tk', '/app/.heroku/python/lib/python2.7/lib-old', '/app/.heroku/python/lib/python2.7/lib-dynload', '/app/.heroku/python/lib/python2.7/site-packages', '/app/.heroku/python/lib/python2.7/site-packages/newrelic-2.22.1.20', './libs'] Server time: Fri, 22 Aug 2014 17:18:13 +0000 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.flatpages', 'sorl.thumbnail', 'django_markdown', 'django_gravatar', 'annoying', 'django_extensions', 'raven.contrib.django.raven_compat', 'crispy_forms', 'storages', 'bootstrap_pagination', 'south', 'compressor', 'taggit', 'modelcluster', 'django.contrib.admin', 'gunicorn', 'huffpsst', 'wagtail.wagtailcore', 'wagtail.wagtailadmin', 'wagtail.wagtaildocs', 'wagtail.wagtailsnippets', 'wagtail.wagtailusers', 'wagtail.wagtailimages', 'wagtail.wagtailembeds', 'wagtail.wagtailsearch', 'wagtail.wagtailredirects', 'wagtail.wagtailforms', 'category', 'author', 'article', 'comment', 'advert', 'video', 'homepage'] Installed Middleware: ('huffpsst.middleware.BasicAuthMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', 'wagtail.wagtailcore.middleware.SiteMiddleware', 'wagtail.wagtailredirects.middleware.RedirectMiddleware') Traceback: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 112. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 22. return view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/wagtail/wagtailadmin/views/pages.py" in preview_on_edit 465. response = get_preview_response(page, preview_mode) File "/app/.heroku/python/lib/python2.7/site-packages/wagtail/wagtailadmin/views/pages.py" in get_preview_response 448. return page.serve_preview(page.dummy_request(), preview_mode) File "/app/.heroku/python/lib/python2.7/site-packages/wagtail/wagtailcore/models.py" in dummy_request 715. raise Exception("Couldn't create request mock object - " Exception Type: Exception at /admin/pages/128/edit/preview/ Exception Value: Couldn't create request mock object - request middleware returned a response Request information: GET: No GET data POST: is_top_post = u'on' related_comments-INITIAL_FORMS = u'0' body = u'

In a public statement made several years ago today, the past version of yourself, as of your being eight years of age, spoke out against the political views you currently hold regarding drone strikes. The miniature version of you strongly opposed your tentative belief that, while you aren\u2019t necessarily against drones across the board or anything, they should be used only when it seems completely necessary.


\u201cIf there\u2019s one thing I know for sure in this life, it\u2019s that robots, especially the deadly, flying kind seen in cartoons such as Transformers, are completely, ridiculously awesome,\u201d said the younger, more innocent version of you, the reader.


\u201cYet now I learn that I\u2019ve apparently gone completely insane in the period between being eight and however old I am in the future, since I somehow seem to have reached the conclusion that airborne, remotely operated killing machines capable of raining devastating missile barrages nearly anywhere on earth are anything other than the coolest thing ever invented by man. This is simply wrong.\u201d


\u201cNow, I\u2019m hearing a lot of stuff from current-day me about \u2018extra-judicial killings\u2019 and military adventurism,\u201d eight-year-old you continued. \u201cTo be honest, none of those things make a lot of sense to me, mostly because I am eight years old. However, what I do understand both angers and disappoints me, which, considering that I am well rested and have just had my snack, is serious indeed.\u201d


\u201cWhy on earth would future me want wars to be fought by boring army men?\u201d Added you circa approximately third grade. \u201cIn most circumstances they can neither fly nor shoot missiles. Frankly, if the America of future me\u2019s time has a problem, it seems like it\u2019s that they don\u2019t have enough drones.\u201d


Eight-year-old you tempered the statement by conceding that your greater age and experience may somehow explain your differing beliefs: \u201cit\u2019s true that, given that it\u2019s fairly likely that 9/11 has not actually happened yet, I may not fully understand the post-9/11 geopolitical climate. However, I still have a hard time respecting the wisdom of a person who cares so much about gross, dumb stuff like smooching.\u201d As of press time, eight-year-old you\u2019s spirits had been raised by the knowledge that Michael Bay had made four movies out of Transformers. ' custom_redirect_url = u'' related_comments-MAX_NUM_FORMS = u'1000' search_description = u'' tags = u'' featured_image = u'147' author = u'66' seo_title = u'' csrfmiddlewaretoken = u'gGjIx36fuJopYRJKW04kOOzfK4M7qkkT' related_comments-TOTAL_FORMS = u'0' expire_at = u'' title = u'8-Year-Old You Disappointed In Your Opinion On Drones' slug = u'8-year-old-you-disappointed-your-opinion-drones' go_live_at = u'' FILES: No FILES data COOKIES: __utmz = '63436470.1408375450.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)' cc_disable = '1' __utmv = '63436470.|3=User=A=1^4=JoinedOn=0=1' s_pers = '%20s_fid%3D3B2F0D3F04578AFB-3213BF6270DBADD4%7C1471855789462%3B%20s_getnr%3D1408697389469-Repeat%7C1471769389469%3B%20s_nrgvo%3DRepeat%7C1471769389473%3B' __cfduid = 'd0f625b7dcbd369ccb151dafb8f52fc4a1408015236364' csrftoken = 'gGjIx36fuJopYRJKW04kOOzfK4M7qkkT' LiveBall = 'uid=81&uky=2ZW9SRF7&rid=598&tgt=embed' sessionid = 'fr9tbav868ts3pnuzfsuj9n9u8237tlx' __utma = '63436470.1016890474.1408375450.1408499405.1408691662.7' META: wsgi.input = wsgi.multiprocess = False HTTP_X_FORWARDED_FOR = '27.34.31.182, 108.162.208.228' HTTP_X_REQUEST_START = '1408727893775' HTTP_X_FORWARDED_PORT = '80' CSRF_COOKIE = u'gGjIx36fuJopYRJKW04kOOzfK4M7qkkT' REMOTE_PORT = '56461' HTTP_REFERER = 'http://www.huffingtonpsst.com/admin/pages/128/edit/' wsgi.errors = SERVER_SOFTWARE = 'gunicorn/19.1.0' REMOTE_ADDR = '10.164.68.147' wsgi.file_wrapper = '' HTTP_CF_CONNECTING_IP = '27.34.31.182' HTTP_PRAGMA = 'no-cache' HTTP_CF_IPCOUNTRY = 'NP' HTTP_CF_VISITOR = '{"scheme":"http"}' wsgi.multithread = False HTTP_CF_RAY = '15e0ba77574201cc-SIN' REQUEST_METHOD = 'POST' HTTP_VIA = '1.1 vegur' RAW_URI = '/admin/pages/128/edit/preview/' CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=UTF-8' wsgi.url_scheme = 'http' HTTP_TOTAL_ROUTE_TIME = '0' HTTP_HOST = 'www.huffingtonpsst.com' gunicorn.socket = HTTP_ACCEPT_LANGUAGE = 'en-US,en;q=0.5' HTTP_CONNECTION = 'close' wsgi.version = HTTP_CACHE_CONTROL = 'no-cache' HTTP_COOKIE = '__cfduid=d0f625b7dcbd369ccb151dafb8f52fc4a1408015236364; csrftoken=gGjIx36fuJopYRJKW04kOOzfK4M7qkkT; sessionid=fr9tbav868ts3pnuzfsuj9n9u8237tlx; __utma=63436470.1016890474.1408375450.1408499405.1408691662.7; __utmz=63436470.1408375450.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmv=63436470.|3=User=A=1^4=JoinedOn=0=1; s_pers=%20s_fid%3D3B2F0D3F04578AFB-3213BF6270DBADD4%7C1471855789462%3B%20s_getnr%3D1408697389469-Repeat%7C1471769389469%3B%20s_nrgvo%3DRepeat%7C1471769389473%3B; cc_disable=1; LiveBall=uid=81&uky=2ZW9SRF7&rid=598&tgt=embed' HTTP_USER_AGENT = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0' CONTENT_LENGTH = '3154' SCRIPT_NAME = u'' HTTP_AUTHORIZATION = 'Basic aHVmZnBzc3Q6YXdlc29tZQ==' HTTP_X_FORWARDED_PROTO = 'http' HTTP_ACCEPT_ENCODING = 'gzip' wsgi.run_once = False HTTP_ACCEPT = '*/*' SERVER_NAME = '0.0.0.0' SERVER_PROTOCOL = 'HTTP/1.1' QUERY_STRING = '' SERVER_PORT = '16565' HTTP_TRUE_CLIENT_IP = '0' HTTP_CONNECT_TIME = '2' PATH_INFO = u'/admin/pages/128/edit/preview/' HTTP_X_REQUESTED_WITH = 'XMLHttpRequest' HTTP_X_REQUEST_ID = '3ce9ed53-b8d1-4f78-a727-8cc94b60e504' Settings: Using settings module huffpsst.settings DATE_INPUT_FORMATS = STATICFILES_FINDERS = EMAIL_HOST_PASSWORD = u'********************' TIME_INPUT_FORMATS = COMPRESS_DEBUG_TOGGLE = None USE_I18N = True COMPRESS_JS_FILTERS = [u'compressor.filters.jsmin.JSMinFilter'] DEFAULT_INDEX_TABLESPACE = '' STATIC_URL = 'https://huffpsst-prod.s3.amazonaws.com/static/' BASICAUTH_PASSWORD = u'********************' FILE_UPLOAD_PERMISSIONS = None USE_TZ = True INSTALLED_APPS = ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.flatpages', 'sorl.thumbnail', 'django_markdown', 'django_gravatar', 'annoying', 'django_extensions', 'raven.contrib.django.raven_compat', 'crispy_forms', 'storages', 'bootstrap_pagination', 'south', 'compressor', 'taggit', 'modelcluster', 'django.contrib.admin', 'gunicorn', 'huffpsst', 'wagtail.wagtailcore', 'wagtail.wagtailadmin', 'wagtail.wagtaildocs', 'wagtail.wagtailsnippets', 'wagtail.wagtailusers', 'wagtail.wagtailimages', 'wagtail.wagtailembeds', 'wagtail.wagtailsearch', 'wagtail.wagtailredirects', 'wagtail.wagtailforms', 'category', 'author', 'article', 'comment', 'advert', 'video', 'homepage'] COMPRESS_STORAGE = 'herokuify.storage.CachedS3StaticStorage' FIXTURE_DIRS = SECRET_KEY = u'********************' CSRF_COOKIE_DOMAIN = None CRISPY_TEMPLATE_PACK = 'bootstrap3' TEMPLATE_STRING_IF_INVALID = '' DEBUG_PROPAGATE_EXCEPTIONS = False MANDRILL_API_KEY = u'********************' TEMPLATED_EMAIL_TEMPLATE_DIR = '' DATABASES = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'PASSWORD': u'********************', 'NAME': 'dav58e6f2g7rsq', 'PORT': 5502, 'HOST': 'ec2-54-243-126-26.compute-1.amazonaws.com', 'USER': 'u5f0i0tuit47tm'}} INTERNAL_IPS = AWS_URL = 'http://s3.amazonaws.com/' CSRF_COOKIE_SECURE = False LOGOUT_URL = '/accounts/logout/' PREPEND_WWW = False ALLOWED_INCLUDE_ROOTS = SESSION_ENGINE = 'django.contrib.sessions.backends.db' DISALLOWED_USER_AGENTS = CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure' AUTHENTICATION_BACKENDS = 'django.contrib.auth.backends.ModelBackend' LOGGING_CONFIG = 'django.utils.log.dictConfig' COMPRESS_PRECOMPILERS = ('text/x-scss', 'django_libsass.SassCompiler') TEMPLATE_CONTEXT_PROCESSORS = SIGNING_BACKEND = 'django.core.signing.TimestampSigner' WAGTAIL_SITE_NAME = 'Huffpsst' COMPRESS_ROOT = '/app/static' COMPRESS_YUI_JS_ARGUMENTS = u'' AWS_S3_FILE_OVERWRITE = True COMPRESS_CSS_HASHING_METHOD = u'mtime' APPEND_SLASH = True AUTH_USER_MODEL = 'auth.User' FORCE_SCRIPT_NAME = None LOCALE_PATHS = USE_L10N = True COMPRESS_REBUILD_TIMEOUT = 2592000 ENVIRONMENT = 'PROD' EMAIL_USE_TLS = True COMPRESS_CACHE_BACKEND = u'default' ALLOWED_HOSTS = ['*'] REDACTOR_UPLOAD = 'uploads/' COMPRESS_YUGLIFY_JS_ARGUMENTS = u'--terminal' COMPRESS_YUGLIFY_BINARY = u'yuglify' PASSWORD_HASHERS = u'********************' EMAIL_PORT = 587 THOUSAND_SEPARATOR = ',' SETTINGS_MODULE = 'huffpsst.settings' SSL_URLS = CSRF_COOKIE_HTTPONLY = False COMPRESS_YUI_BINARY = u'java -jar yuicompressor.jar' USE_ETAGS = False TIME_ZONE = 'UTC' EMAIL_HOST = 'smtp.mandrillapp.com' COMPRESS_JS_COMPRESSOR = u'compressor.js.JsCompressor' COMPRESS_CSSTIDY_BINARY = u'csstidy' DEBUG = True TEMPLATE_DIRS = '/app/huffpsst/../templates/' SECURE_PROXY_SSL_HEADER = COMPRESS_YUI_CSS_ARGUMENTS = u'' COMPRESS_URL = 'https://huffpsst-prod.s3.amazonaws.com/static/' EMAIL_SUBJECT_PREFIX = '[Django] ' FILE_CHARSET = 'utf-8' FORMAT_MODULE_PATH = None SERVER_EMAIL = 'he...@huffpsst.com' COMPRESS_JINJA2_GET_ENVIRONMENT = None EMAIL_HOST_USER = 'app28...@heroku.com' CACHES = {'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}} CACHE_MIDDLEWARE_ALIAS = 'default' AWS_HEADERS = {'Expires': u'Sat, 22 Aug 2015 13:24:06 GMT', 'Cache-Control': ':public, max-age=31536000'} COMPRESS_TEMPLATE_FILTER_CONTEXT = {u'STATIC_URL': 'https://huffpsst-prod.s3.amazonaws.com/static/'} COMPRESS_CSS_FILTERS = ['compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter'] ROOT_URLCONF = 'huffpsst.urls' LANGUAGE_COOKIE_NAME = 'django_language' COMPRESS_VERBOSE = False DECIMAL_SEPARATOR = '.' COMPRESS_PARSER = u'compressor.parser.AutoSelectParser' STATIC_ROOT = '/app/huffpsst/../static/' SEND_BROKEN_LINK_EMAILS = False MEDIA_ROOT = '/app/huffpsst/../media/' SESSION_COOKIE_PATH = '/' LOGIN_REDIRECT_URL = 'wagtailadmin_home' COMPRESS_OFFLINE_TIMEOUT = 31536000 AWS_QUERYSTRING_AUTH = False FIRST_DAY_OF_WEEK = 0 COMPRESS_CLOSURE_COMPILER_BINARY = u'java -jar compiler.jar' FILE_UPLOAD_TEMP_DIR = None USE_THOUSAND_SEPARATOR = False BASICAUTH_USERNAME = 'huffpsst' REDACTOR_OPTIONS = {'lang': 'en'} TRANSACTIONS_MANAGED = False DEFAULT_CHARSET = 'utf-8' SESSION_SAVE_EVERY_REQUEST = False WSGI_APPLICATION = 'huffpsst.wsgi.application' X_FRAME_OPTIONS = 'SAMEORIGIN' ADMIN_FOR = MONTH_DAY_FORMAT = 'F j' SESSION_COOKIE_NAME = 'sessionid' EMAIL_BACKEND = 'djrill.mail.backends.djrill.DjrillBackend' DATE_FORMAT = 'N j, Y' MANAGERS = ('Asim Hussain', 'jaw...@gmail.com') COMPRESS_CLOSURE_COMPILER_ARGUMENTS = u'' COMPRESS_YUGLIFY_CSS_ARGUMENTS = u'--terminal' LOGGING = {'loggers': {'django.request': {'handlers': ['mail_admins'], 'propagate': True, 'level': 'ERROR'}, 'huffpsst': {'handlers': ['console'], 'propagate': True, 'level': 'DEBUG'}, 'root': {'handlers': ['console'], 'propagate': True, 'level': 'DEBUG'}}, 'version': 1, 'handlers': {'heroku': {'class': 'logging.StreamHandler', 'level': 'DEBUG', 'formatter': 'verbose'}, 'mail_admins': {'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', 'level': 'ERROR'}, 'bugsnag': {'class': 'bugsnag.handlers.BugsnagHandler', 'level': 'ERROR'}, 'console': {'class': 'logging.StreamHandler', 'level': 'DEBUG', 'formatter': 'simple'}}, 'filters': {'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}}, 'disable_existing_loggers': False, 'formatters': {'simple': {'format': '%(levelname)s %(module)s :: %(message)s'}, 'verbose': {'format': '%(levelname)s %(asctime)s %(filename)s:%(lineno)d %(process)d %(thread)d %(message)s'}}} ABSOLUTE_URL_OVERRIDES = {} COMMENTS_ALLOW_PROFANITIES = False TEMPLATE_DEBUG = True IGNORABLE_404_URLS = STATICFILES_DIRS = [] CACHE_MIDDLEWARE_KEY_PREFIX = u'********************' SESSION_COOKIE_HTTPONLY = True DATETIME_FORMAT = 'N j, Y, P' DEFAULT_FILE_STORAGE = 'herokuify.storage.S3MediaStorage' AWS_IS_GZIPPED = False CACHE_MIDDLEWARE_SECONDS = 600 SESSION_EXPIRE_AT_BROWSER_CLOSE = False FILE_UPLOAD_HANDLERS = SESSION_COOKIE_DOMAIN = None COMPRESS_CSSTIDY_ARGUMENTS = u'--template=highest' DATABASE_ROUTERS = [] SESSION_COOKIE_AGE = 1209600 SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' YEAR_MONTH_FORMAT = 'F Y' MEDIA_URL = 'https://huffpsst-prod.s3.amazonaws.com/media/' LAMPOON = 'http://harvardlampoon.com/' COMPRESS_ENABLED = True LOGIN_URL = 'django.contrib.auth.views.login' SESSION_CACHE_ALIAS = 'default' AWS_STORAGE_BUCKET_NAME = 'huffpsst-prod' FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 SHORT_DATETIME_FORMAT = 'm/d/Y P' TEMPLATED_EMAIL_FILE_EXTENSION = 'email' TEST_RUNNER = 'django.test.runner.DiscoverRunner' PASSWORD_RESET_TIMEOUT_DAYS = u'********************' COMPRESS_CACHE_KEY_FUNCTION = u'********************' AWS_S3_SECURE_URLS = True LANGUAGES_BIDI = LANGUAGE_CODE = 'en-us' COMPRESS_DATA_URI_MAX_SIZE = 1024 COMPRESS_OFFLINE_MANIFEST = u'manifest.json' ADMINS = ('Asim Hussain', 'jaw...@gmail.com') STATICFILES_STORAGE = 'herokuify.storage.CachedS3StaticStorage' CSRF_COOKIE_NAME = 'csrftoken' CSRF_COOKIE_PATH = '/' NUMBER_GROUPING = 0 MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage' TIME_FORMAT = 'P' MIDDLEWARE_CLASSES = COMPRESS_MINT_DELAY = 30 DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter' COMPRESS_OFFLINE_CONTEXT = {u'STATIC_URL': 'https://huffpsst-prod.s3.amazonaws.com/static/'} LANGUAGES = COMPRESS_OFFLINE = True SESSION_COOKIE_SECURE = False SESSION_FILE_PATH = None SITE_ID = 1 DEFAULT_TABLESPACE = '' DEFAULT_CONTENT_TYPE = 'text/html' DEFAULT_FROM_EMAIL = 'HuffPsst ' PROFANITIES_LIST = u'********************' COMPRESS_MTIME_DELAY = 10 TEMPLATE_LOADERS = STUDYHALL_SUPPORT_MAIL = 'HuffPsst Support ' COMPRESS_CSS_COMPRESSOR = u'compressor.css.CssCompressor' USE_X_FORWARDED_HOST = False COMPRESS_OUTPUT_DIR = u'CACHE' DATETIME_INPUT_FORMATS = SHORT_DATE_FORMAT = 'm/d/Y' You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 500 page.



middlewares:
MIDDLEWARE_CLASSES = (
    'my_project.middleware.BasicAuthMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',

    # Wagtail middlewares
    'wagtail.wagtailcore.middleware.SiteMiddleware',
    'wagtail.wagtailredirects.middleware.RedirectMiddleware',
)

Karl Hobley

unread,
Aug 26, 2014, 5:34:42 AM8/26/14
to wag...@googlegroups.com
Thanks

When Wagtail generates a preview, it creates a fake request object and runs your sites middleware on it (so the request is as close as possible to an actual request the page would really get).

The issue here is one of those middleware classes is returning a response which would usually prevent the page from rendering when served in real life. Wagtail doesn't know what to do in this situation so it crashes with an error.

The most likely culprit is 'my_project.middleware.BasicAuthMiddleware'. Could you check that the process_request method doesn't return a response when Wagtail is using it to generate a preview?

Thanks,

Karl

Chris Moradi

unread,
Aug 26, 2014, 4:15:27 PM8/26/14
to wag...@googlegroups.com
I was having the same problem with a test site I was building. I have middleware that restricts access to sections of the site (based on URL). I don't know if this is the right way to go long-term, but as a test this worked. I subclassed the Page model (using the name CorePage so I wouldn't need to change the subclass of all my page models... just a hack)

from wagtail.wagtailcore.models import Page as CorePage

# modules specific to overriding dummy_request()
from django_cas.middleware import CASMiddleware
from django.core.handlers.wsgi import WSGIRequest
from django.core.handlers.base import BaseHandler
from six.moves.urllib.parse import urlparse
from six import StringIO


class Page(CorePage):
   
"""Create new page class inheriting from the wagtail core class. This is done so that
    we can override the dummy_request method that used during a page preview.
    """


   
class Meta:
       
abstract = True

   
def dummy_request(self):
       
"""
        Construct a HttpRequest object that is, as far as possible, representative of ones that would
        receive this page as a response. Used for previewing / moderation and any other place where we
        want to display a view of this page in the admin interface without going through the regular
        page routing logic.

        Overridden method to exclude the CAS middleware (which currently handles page
            restrictions) from being applied to the request.
       
        **FUTURE: consider adding a user to the request. It would be great to have the editor's user,
        but this probably can't happen without changing core code. The user probably needs
        staff access to be able to view all pages.
        """

        url
= self.full_url
       
if url:
            url_info
= urlparse(url)
            hostname
= url_info.hostname
            path
= url_info.path
            port
= url_info.port or 80
       
else:
           
# Cannot determine a URL to this page - cobble one together based on
           
# whatever we find in ALLOWED_HOSTS
           
try:
                hostname
= settings.ALLOWED_HOSTS[0]
           
except IndexError:
                hostname
= 'localhost'
            path
= '/'
            port
= 80

        request
= WSGIRequest({
           
'REQUEST_METHOD': 'GET',
           
'PATH_INFO': path,
           
'SERVER_NAME': hostname,
           
'SERVER_PORT': port,
           
'wsgi.input': StringIO(),
       
})

       
# Apply middleware to the request - see http://www.mellowmorning.com/2011/04/18/mock-django-request-for-testing/
        handler
= BaseHandler()
        handler
.load_middleware()
       
for middleware_method in handler._request_middleware:
           
if isinstance(middleware_method.__self__, CASMiddleware):
               
continue
           
elif middleware_method(request):

               
raise Exception("Couldn't create request mock object - "

                               
"request middleware returned a response")
       
return request


Again, this is probably not the right way to do this, but it's a quick way to test things. In the last few lines, I'm processing the request through middleware except for the one that matches CASMiddleware (which currently has the access restrictions).
Reply all
Reply to author
Forward
0 new messages