global name 'csrf' is not defined in Django 1.10 - python-2.7

NameError at /todos/accounts/register/
global name 'csrf' is not defined
Request Method: GET
Request URL: http://localhost:8000/todos/accounts/register/
Django Version: 1.10.5
Exception Type: NameError
Exception Value:
global name 'csrf' is not defined
Exception Location: /home/rahul/Desktop/apps/todolist/todos/views.py in register, line 37
Python Executable: /usr/bin/python
Python Version: 2.7.6
Python Path:
Error in views.py :
from django.shortcuts import render
from django.http import HttpResponse
from .models import Todo
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.auth.forms import UserCreationForm
#from django.core.context_processors import csrf
def index(request):
todos = Todo.objects.all()[:10]
context = {
'todos' : todos
}
return render(request, 'index.html', context)
def details(request, id):
todo = Todo.objects.get(id=id)
context = {
'todo' : todo
}
return render(request, 'details.html', context)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register/complete')
else:
form = UserCreationForm()
token = {}
token.update(csrf(request))
token['form'] = form
return render_to_response('registration/registration_form.html', token)
def registration_complete(request):
return render_to_response('registration/registration_complete.html')
Currently my code is showing global name 'csrf' is not defined. To overcome this error, If I uncomment from django.core.context_processors import csrf, than it shows context_processors module not found. Please help.
Thanks in advance.

Django built-in template context processors were moved from package django.core to django.template. So you should change your import as
from django.template.context_processors import csrf

Related

I'm trying to add a new page in Django but getting 404 error yet I've added urls and views

I'm a newbie trying to add an a new page but get the following error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/study
Using the URLconf defined in student_management_system.urls, Django tried these URL patterns, in this order:
I've added a function for the page in Views.py and also added the path in URLS.py.
StudentViews.py ---> in student management app folder:
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.core.files.storage import FileSystemStorage # To upload Profile Picture
from django.urls import reverse
import datetime # To Parse input DateTime into Python Date Time Object
from student_management_app.models import CustomUser, Staffs, Courses, Subjects, Students, Attendance, AttendanceReport, \
LeaveReportStudent, FeedBackStudent, StudentResult
def study(request):
return render(request, "student_template/study.html")
Views.py ---> in student management app folder:
# from channels.auth import login, logout
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, redirect
from django.contrib import messages
from student_management_app.EmailBackEnd import EmailBackEnd
def home(request):
return render(request, 'index.html')
def loginPage(request):
return render(request, 'login.html')
def doLogin(request):
if request.method != "POST":
return HttpResponse("<h2>Method Not Allowed</h2>")
else:
user = EmailBackEnd.authenticate(request, username=request.POST.get('email'), password=request.POST.get('password'))
if user != None:
login(request, user)
user_type = user.user_type
#return HttpResponse("Email: "+request.POST.get('email')+ " Password: "+request.POST.get('password'))
if user_type == '1':
return redirect('admin_home')
elif user_type == '2':
# return HttpResponse("Staff Login")
return redirect('staff_home')
elif user_type == '3':
# return HttpResponse("Student Login")
return redirect('student_home')
else:
messages.error(request, "Invalid Login!")
return redirect('login')
else:
messages.error(request, "Invalid Login Credentials!")
#return HttpResponseRedirect("/")
return redirect('login')
def get_user_details(request):
if request.user != None:
return HttpResponse("User: "+request.user.email+" User Type: "+request.user.user_type)
else:
return HttpResponse("Please Login First")
def logout_user(request):
logout(request)
return HttpResponseRedirect('/')
URLS.py ---> in student management app folder:
from django.urls import path, include
from . import views
from .import HodViews, StaffViews, StudentViews
urlpatterns = [
path('', views.loginPage, name="login"),
path('student_view_result/', StudentViews.student_view_result, name="student_view_result"),
path('study/', StudentViews.study, name="study"),
]
Urls.py for the whole system:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from student_management_system import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('student_management_app.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
How could I resolve this error? And why it reported this error?

Django - missing 1 required positional argument: '_id'

im getting an error
BlogDetailView() missing 1 required positional argument: '_id'
when im trying to access the function BlogDetailView.
views.py :
from django.http.response import Http404
from .models import BlogModel,CommentModel
from .forms import SearchForm,CommentForm
from django.shortcuts import render,redirect
def BlogDetailView(request,_id):
try:
data = BlogModel.objects.get(id = _id)
comments = CommentModel.objects.filter(blog = data)
except BlogModel.DoesNotExist:
raise Http404('Data does not exist')
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
Comment = CommentModel(your_name= form.cleaned_data['your_name'],
comment_text=form.cleaned_data['comment_text'],
blog=data)
Comment.save()
return redirect(f'/blog/{_id}')
else:
form = CommentForm()
context = {
'data': data,
'form': form,
'comments': comments,
}
return render(request,'Test_one/detailview.html',context)
urls.py :
from django.conf.urls import url
from django.urls.conf import path
from blogapp.views import BlogDetailView, BlogListView
from . import views
app_name = "Blogapp"
urlpatterns = [
url(r'^blogs/', views.BlogDetailView, name="blogs"),
url(r'^blog/<int:_id>', views.BlogListView, name="blog"),
]
Can anyone solve this problem?
I think you wrote code wrongly, logically a blog list doesn't need an id to fetch (you want all blog posts so probably don't need id) and you need to fetch a specific blog post so you need an id to fetch this. so I think this is the right code that you tried to write:
from django.conf.urls import url
from django.urls.conf import path
from blogapp.views import BlogDetailView, BlogListView
from . import views
app_name = "Blogapp"
urlpatterns = [
url(r'^blogs/<int:_id>', views.BlogDetailView, name="blogs"),
url(r'^blog/', views.BlogListView, name="blog"),
]

How do I fix this error in Python Django involving request.user.is_authenticated() and bool object not callable?

I am trying to make profile pages for each user. I added a code that checks if the user is logged in and does a redirect (see line 12 of the code below).
from django.shortcuts import render
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from .models import Account, ForSale, WTB
from mysite.forms import MyRegistrationForm
def signup(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/user/')
else:
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/user/')
context = {}
context.update(csrf(request))
context['form'] = MyRegistrationForm()
return render(request, 'signup.html', context)
def index(request):
return render(request, 'index.html')
However, upon accessing /signup/ on the site I get the following debug message:
TypeError at /signup/
'bool' object is not callable
Request Method: GET
Request URL: http://url:8000/signup/
Django Version: 2.0
Exception Type: TypeError
Exception Value:
'bool' object is not callable
Exception Location: /www/mysite.com/mysite/views.py in signup, line 13
Python Executable: /usr/bin/python3
Python Version: 3.5.2
Python Path:
['/www/mysite.com',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/lib/python3.5/site-packages',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Sun, 3 Dec 2017 18:07:54 -0800
In older versions of Django request.user.is_authenticated was a method. It's now an attribute and no longer requires parenthesis. If you change your code to:
if request.user.is_authenticated:
It should be work as expected.
For more info see the docs here: https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated
you forget to import csrf module please try to add this line and make sure to avoid hardcoded urls try to use url names
from django.core.context_processors import csrf

invalid syntax (views.py, line 34)

I'm new to django, I'm getting an invalid syntax error in views.py file. Is there a way i can debug syntax errors in django? When running the development server with python manage.py runserver I'm getting the below error
===============
SyntaxError at /
invalid syntax (views.py, line 34)
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 1.8.5
Exception Type: SyntaxError
Exception Value:
invalid syntax (views.py, line 34)
Exception Location: /home/arajguru/training/mycode/myshop/orders/urls.py in <module>, line 2
Python Executable: /home/arajguru/training/mycode/env/myshop/bin/python
.......
===============
Below is my views.py file:
from django.shortcuts import render
from .models import OrderItem
from .forms import OrderCreateForm
from cart.cart import Cart
#from .tasks import order_created
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
def order_create(request):
cart = Cart(request)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save()
for item in cart:
OrderItem.objects.create(order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity'])
# clear the cart
cart.clear()
# launch asynchronous task
# order_created.delay(order.id)
# set the order in the session
request.session['order_id'] = order.id
# redirect to the payment
return redirect(reverse('payment:process'))
else:
form = OrderCreateForm()
return render(request,`enter code here`
'orders/order/create.html',
{'cart': cart, 'form': form}
I didn't close the render function with parenthesis.
P.S. Use Pycharm to avoid syntax errors. It will show you immediately if something is wrong with the syntax.
Close the render function parenthesis.
add backslash after "enter code here`\"

Custom template in django form wizard - NameError

I am trying to create custom templates for a simple contact form as per the django docs but I am getting a NameError. Looks like a simple issue but I can't figure it out. Any help will be greatly appreciated. The error message is:
"NameError at /contact/
name 'wizardcustomtemplate' is not defined"
where 'wizardcustomtemplate' is the app. Here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from wizardcustomtemplate.forms import SubjectForm, SenderForm, MessageForm
from wizardcustomtemplate.views import ContactWizard
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^contact/$', ContactWizard.as_view(FORMS)),
)
views.py
import os
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.formtools.wizard.views import WizardView
from django.core.files.storage import FileSystemStorage
from django.core.files import File
FORMS = [("0", wizardcustomtemplate.forms.SubjectForm),
("1", wizardcustomtemplate.forms.SenderForm),
("2", wizardcustomtemplate.forms.MessageForm)
]
TEMPLATES = {"0": "wizardcustomtemplate/subject.html",
"1": "wizardcustomtemplate/sender.html",
"2": "wizardcustomtemplate/message.html"
}
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('wizardcustomtemplate/thanks.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
forms.py
from django import forms
class SubjectForm(forms.Form):
subject = forms.CharField(max_length = 100,initial='Wizard')
class SenderForm(forms.Form):
sender = forms.EmailField(initial='abcd#efgh.org')
class MessageForm(forms.Form):
message = forms.CharField(initial='How r u?')
The form wizard works fine if I don't use the custom templates (FORMS, TEMPLATES etc.) Please let me know if you need additional information.
Solved it by adding import wizardcustomtemplate in views.py as suggested by #Rohan.