Sean
Sean

Reputation: 1

TOPIC: Django issue : context must be a dict rather than RequestContext

Excuse me. When i submit the form that i get following error.

TypeError at /foodlogin/
context must be a dict rather than RequestContext.

My views.py is below. My login form need to identify the database info:Models.py-User class, and need to session keep the all webpage. In addition, login successed will redirect to "foodmenu.html".

# -*- coding: utf-8 -*-
from django.shortcuts import redirect
from django.template.loader import get_template
from django.http import HttpResponse
from castecfood.models import User
from castecfood import forms
from django.template import RequestContext

def index(request):    
    template=get_template('index.html')
    html=template.render(locals())
    return HttpResponse(html)

def foodlogin(request):    
    if request.method=='POST':
       form=forms.LoginForm(request.POST)
       if form.is_valid():
          login_id=request.POST['user_id'].strip()
          login_password=request.POST['user_pass']
          try:
             user=User.objects.get(jobnumber=login_id)
             if user.jobnumber==login_id anduser.personpwd==login_password:
             request.session['user_id']=user.jobnumber
             request.session['user_pass']=user.personpwd
             return redirect('/foodmenu/')
             else:
                message="ID或密碼有錯喔,請再檢查一次"
          except:
            message="目前無法登入"
       else:
          message="請檢查輸入的欄位內容"
    else:
        form=forms.LoginForm()

    template=get_template('foodlogin.html')
    request_context=RequestContext(request)
    request_context.push(locals())
    html=template.render(request_context)    
    reponse=HttpResponse(html)
    return reponse

def foodmenu(request):
    template=get_template('foodmenu.html')  
    html=template.render(locals())
    return HttpResponse(html)

My foodlogin.html file: It use to login for user input the "user.jobnumber and user.personpwd"

<!--foodlogin.html (castecsystem project)>-->
    <!DOCTYPE HTML>
    <html>
      <head>
        <title>Login</title>
        {% include "stylesheet.html" %}
      </head>
   <body>
    <!-- Banner -->
            {% include "banner.html" %}
        <!--InnerHeader -->
            {% block content %}
                   <section id="one" class="wrapper special">
                  <div class="inner">
                       <header class="major">
                     <h2>FoodOrder System</h2>
                       </header>
                  </div>
               <div class="container">
               <div class="foodlogin_image"><img src="/static/images/person_head1.png"></div>
               <form name='login' action='.' method="POST">
               {% csrf_token %}                 
               <fieldset>                  
               {{form.as_table}}
               </fieldset>                          
               <br/>
               <input type="submit" value="Login">
               <input type="reset" value="Reset">
               </form>
               </div>
               </section>
           {% endblock %}           
    <!-- Footer -->
        {% include "footer.html" %}
    <!-- Scripts -->
        {% include "script.html" %}
    </body>
   </html>

My forms.py file:

# -*- coding: utf-8 -*-
from django import forms

class LoginForm(forms.Form): 
    user_id=forms.CharField(label='Your ID:', max_length=10)
    user_pass=forms.CharField(label='Your Password:',  
    widget=forms.PasswordInput())

My urls.py file:

urlpatterns = [
url(r'^admin/', include(admin.site.urls)), 
url(r'^$', index),
url(r'^foodlogin/$', foodlogin),
url(r'^foodmenu/$', foodmenu),
url(r'^captcha/', include('captcha.urls'))
]

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/foodlogin/

Django Version: 1.11.3
Python Version: 3.6.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'castecfood',
'captcha']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Users\Sean\.spyder-py3\myproject\env\lib\site-   
packages\django\core\handlers\exception.py" in inner
41.response = get_response(request)
File "C:\Users\Sean\.spyder-py3\myproject\env\lib\site- 
packages\django\core\handlers\base.py" in _get_response
187.response = self.process_exception_by_middleware(e, request)
File "C:\Users\Sean\.spyder-py3\myproject\env\lib\site- 
packages\django\core\handlers\base.py" in _get_response
185.response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Sean\.spyder-py3\myproject\castecsystem\castecfood\views.py" 
in foodlogin
39.html=template.render(request_context)    
File "C:\Users\Sean\.spyder-py3\myproject\env\lib\site-
packages\django\template\backends\django.py" in render
64.context = make_context(context, request,   
autoescape=self.backend.engine.autoescape)
File "C:\Users\Sean\.spyder-py3\myproject\env\lib\site-
packages\django\template\context.py" in make_context
287.raise TypeError('context must be a dict rather than %s.' % 
context.__class__.__name__)

Exception Type: TypeError at /foodlogin/
Exception Value: context must be a dict rather than RequestContext.

I have no idea how to solve this problem. I try it of long time, but i still not solved. Please let me know how to solve it. I am very appreciate.

Upvotes: 0

Views: 634

Answers (1)

Stavros Korokithakis
Stavros Korokithakis

Reputation: 4946

You need to change:

html=template.render(request_context)

to:

html=template.render(context=locals(), request=request)

Upvotes: 1

Related Questions