Django Indentation error - indentation

I am new to Django and was trying this code in a tutorial. But now I'm not able to run my program because of the following error:
IndentationError at /
('unexpected indent', ('D:\\django_workspace\\django_bookmarks\\..\\django_bookmarks\\bookmarks\\views.py', 14, 4, ' return HttpResponse(output)\n'))
Request Method: GET
Request URL: http://localhost:8000/
Exception Type: IndentationError
Exception Value:
('unexpected indent', ('D:\\django_workspace\\django_bookmarks\\..\\django_bookmarks\\bookmarks\\views.py', 14, 4, ' return HttpResponse(output)\n'))
Exception Location: D:\django_workspace\django_bookmarks\..\django_bookmarks\urls.py in <module>, line 2
Python Executable: C:\Python26\python.exe
Python Version: 2.6.4
Python Path: ['D:\\django_workspace\\django_bookmarks', 'C:\\Python26', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26\\lib\\site-packages']
Server time: Tue, 9 Mar 2010 19:18:32 +
My views.py file code is:
from django.http import HttpResponse, Http404
from django.contrib.auth.models import User
from django.template import Context
from django.template.loader import get_template
def main_page(request):
template = get_template('main_page.html')
variables = Context({
'head_title': 'Django Bookmarks',
'page_title': 'Welcome to Django Bookmarks',
'page_body': 'Where you can store and share bookmarks!'
})
output = template.render(variables)
return HttpResponse(output)
def user_page(request, username):
try:
user = User.objects.get(username=username)
except:
raise Http404('Requested user not found.')
bookmarks = user.bookmark_set.all()
template = get_template('user_page.html')
variables = Context({
'username': username,
'bookmarks': bookmarks
})
output = template.render(variables)
return HttpResponse(output)
Kindly help me rectify this problem! Thanks in advance.

Most likely you're mixing tabs with spaces - use one or the other for your indenting... preferably spaces, according to this:
http://www.python.org/dev/peps/pep-0008/

First locate the line on which this error occurs. Delete the line entirely. Go to the end of the preceding line and then press enter. Now enter the line.

Related

Unable to perform conditional redirect from a class based view Django

I am trying to redirect a user who has already registered to a different view. here is the code for the views.py
However when qs.exists() = true I get an error
'The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.'
I am a beginner have read the documentation but unable to find where i am going worng.
Thanks
from django.shortcuts import render, redirect
from django.views import View
from Lpage.forms import SubscriberEntryForm
from Lpage.models import Subscriber
class homeview(View):
def get(self,request):
msg = request.session.get('msg', False)
if(msg):
del(request.session['msg'])
return render(request,'Lpage/index.html')
def post(self, request):
form = SubscriberEntryForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
qs = Subscriber.objects.filter(email__iexact=obj.email)
if qs.exists():
return redirect('messageview')
else:
obj.save()
request.session['msg'] = "msg"
return redirect(request.path)
def messageview(request):
return render(request,'Lpage/messages.html',{})
Here is the error message
ValueError at /
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Request Method: POST
Request URL: http://localhost:8000/
Django Version: 3.2.7
Exception Type: ValueError
Exception Value:
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
Python Executable: C:\Users\Ganesamurthi\anaconda3\python.exe
Python Version: 3.8.5
Python Path:
['D:\dreamdoors\dd',
'C:\Users\Ganesamurthi\anaconda3\python38.zip',
'C:\Users\Ganesamurthi\anaconda3\DLLs',
'C:\Users\Ganesamurthi\anaconda3\lib',
'C:\Users\Ganesamurthi\anaconda3',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32\lib',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\Pythonwin']
Server time: Wed, 29 Sep 2021 05:23:43 +0000
Traceback Switch to copy-and-paste view
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = get_response(request) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 188, in _get_response
self.check_response(response, callback) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
raise ValueError( …
▶ Local vars
redirect expects you to pass a URL but you gave it messageview, which is a view class in fact.
So you need to give redirect to the URL of messageview.

'DeferredAttribute' object is not callable

I'm working on a simple django project, but i face this problem that you see below so, i want a solution because i really got tired
I expect the output of that code to be numberone but the actual output is this error :
TypeError at /db/
'DeferredAttribute' object is not callable
Request Method: GET
Request URL: http://127.0.0.1:8000/db/
Django Version: 2.1.5
Exception Type: TypeError
Exception Value:
'DeferredAttribute' object is not callable
Exception Location: /home/mohammed/Desktop/New life programming/python /pythonDjano/Filecorse/NewDjango/MohammedAlaa/Abdullah/views.py in db, line 16
Python Executable: /usr/bin/python3
Python Version: 3.6.8
Python Path:
['/home/mohammed/Desktop/New life '
'programming/python/pythonDjano/Filecorse/NewDjango/MohammedAlaa',
'/usr/local/lib/python3.6/dist-packages/pip-19.1.1-py3.6.egg',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/home/mohammed/.local/lib/python3.6/site-packages',
'/usr/local/lib/python3.6/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Sat, 31 Aug 2019 11:13:18 +0000
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Product
def Home(request):
return HttpResponse('Welcome, Mohammed Alaa :)')
def htm(request):
return render(request,'htm.html',{'hello':"hello Mohammed Abo Alaa again:)", 'days':['wed', 'fri', 'thru']
})
def others(request):
return HttpResponse('Welcome, Mohammed Alaa :) form others')
def db(request):
dat = ''
p1 = Product(namee='numberone', pricee=500,Type='m')
p1.save()
dat = Product.namee()
return HttpResponse(dat)
You need to refer to the Product instance you just created, not the whole Product class. And it's just a string, no need to call it.
dat = p1.namee

Attribute Error in Uploading Excel File to Django

I am having trouble uploading excel file to my django application. It is a very simple application that should allow a user to upload an excel file with 3 columns. The application will read the contents of this file and process it into bunch of calculations
here is my forms.py:
class InputForm(forms.Form):
FileLocation = forms.FileField(label='Import Data',required=True,widget=forms.FileInput(attrs={'accept': ".xlsx"}))
settings.py:
FILE_UPLOAD_HANDLERS = ["django_excel.ExcelMemoryFileUploadHandler",
"django_excel.TemporaryExcelFileUploadHandler"]
views.py:
import xlrd
from django.shortcuts import render_to_response, render
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.template.context_processors import csrf
from io import TextIOWrapper
from WebApp.forms import *
from django.core.mail import send_mail
from django.utils.safestring import mark_safe
from django.db import connection
import os
import csv
def analyze(request):
if request.method == 'POST':
form = InputForm(request.POST,request.FILES['FileLocation'])
if form.is_valid():
book = xlrd.open_workbook(request.FILES('FileLocation'))
for sheet in book.sheets():
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
print(number_of_rows)
I upload the file in the form and it gives me an error:
AttributeError at /app/analyze/
'ExcelInMemoryUploadedFile' object has no attribute 'get'
Request Method: POST
Request URL: http://127.0.0.1:8000/data/analyze/
Django Version: 1.11
Exception Type: AttributeError
Exception Value:
Exception Location: C:\Python36\lib\site-packages\django\forms\widgets.py in value_from_datadict, line 367
Python Executable: C:\Python36\python.exe
Python Version: 3.6.4
I am also able to upload a .csv file successfully using the following views.py code:
def analyze(request):
c={}
context = RequestContext(request)
c.update(csrf(request))
abc=['a','b','c']
if request.method == 'POST':
form = InputForm(request.POST,request.FILES)
dataType = request.POST.get("DataType")
print(dataType)
if form.is_valid():
cd = form.cleaned_data #print (cd)
a = TextIOWrapper(request.FILES['FileLocation'].file,encoding='ascii',errors='replace')
#print (request.FILES.keys())
data = csv.reader(a)
row1csv = next(data)
region = row1csv[0]
metric = row1csv[2]
I have tried django-excel with same error.
You're correctly initialising your form for the .CSV case but not in your Excel case:
form = InputForm(request.POST, request.FILES)
Don't initialise using request.FILES['FileLocation'] as that's passing the wrong type to the form. It's expecting a MultiValueDict of uploaded files, not a single uploaded file. That's why it fails when calling get on it.
Next, you can't pass an ExcelInMemoryUploadedFile to xlrd.get_workbook(). You need to save the file to disk first, then pass it's path to the get_workbook() method. The documentation of django-excel gives some easier methods:
book = request.FILES['FileLocation'].get_book() # note the square brackets!
or to directly access a sheet:
sheet = request.FILES['FileLocation'].get_sheet('sheet1')

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`\"