'tuple' object has no attribute 'get' - python

I am new to Django framework and I am trying to perform the Django authentication views but i keep on getting this error
C:\Users\Harsley\bookmarks>python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
March 21, 2017 - 21:11:56
Django version 1.10.6, using settings 'bookmarks.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /
Traceback (most recent call last):
File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
response = get_response(request)
File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\deprecation.py", line 138, in __call__
response = self.process_response(request, response)
File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\middleware\clickjacking.py", line 32, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'tuple' object has no attribute 'get'
[21/Mar/2017 21:11:58] "GET / HTTP/1.1" 500 57044
This is my url.py file
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^login$', auth_views.login, name='login'),
url(r'^logout$', auth_views.logout, name='logout'),
url(r'^logout_then_login$', auth_views.logout_then_login, `name='logout_then_login'),`
url(r'^$', views.dashboard, name='dashboard'),
]
Here is my views
from django.contrib.auth.decorators import login_required
#login_required()
def dashboard(request):
return (request, 'dashboard.html', {'section': 'dashboard'})

This is wrong:
return (request, 'dashboard.html', {'section': 'dashboard'})
You are returning a tuple where you have to return a Response.
Instead of directly returning a response you can use the render-shortcut:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
#login_required()
def dashboard(request):
return render(request, 'dashboard.html', {'section': 'dashboard'})

Related

Test case written for url resolver using resolve() in django application not working

I am trying to write test cases for simple user login and registration system in django. First, I was thinking of writing test cases for the urls. The only test case I have written so far is
from django.test import SimpleTestCase
from django.urls import reverse, resolve, path
from main.views import homepage, register, login_request, logout_request
import json
# Create your tests here.
class TestUrls(SimpleTestCase):
def test_list_is_resolved(self):
url = reverse('homepage')
self.assertEquals(resolve(url).func,homepage)
The default urls.py is
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('tinymce/',include('tinymce.urls')),
path("",include('main.urls')),
path('admin/', admin.site.urls),
]`
The main application urls.py is
from django.urls import path
from . import views
app_name='main' # here for namespacing the urls
urlpatterns = [
path("", views.login_request, name="login"),
path("homepage/",views.homepage, name="homepage"),
path("register/", views.register,name="register"),
path("logout", views.logout_request, name="logout"),
]`
Now every time I am running the tests, I am getting the following error.
(myproject) C:\Users\rohan\mysite>py manage.py test
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_list_is_resolved (main.tests.test_urls.TestUrls)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\rohan\mysite\main\tests\test_urls.py", line 11, in test_list_is_resolved
url = reverse('homepage')
File "C:\Users\rohan\Envs\myproject\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\rohan\Envs\myproject\lib\site-packages\django\urls\resolvers.py", line 677, in
_reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'homepage' not found. 'homepage' is not a valid
view
function or pattern name.
----------------------------------------------------------------------
Ran 1 test in 0.015s
FAILED (errors=1)
I am not being able to find any error. What is wrong here?
Remove the following:
app_name='main' # here for namespacing the urls
OR use the following when reversing:
reverse("main:homepage")

Problem with AJAX calls in Django app while developing google chrome extension

When I am trying to send data to my localhost using the ajax call in popup.js, I am getting an error :
Not Found: /sentiment/
"GET /sentiment/?number=219 HTTP/1.1" 404 1714
Even though I checked the url and it is correct and exists.
This is the snippet of my ajax call:
$.ajax({
url:"http://127.0.0.1:8000/sentiment/",
dataType:"json",
data:{
number:newTotal
},
crossDomain:true,
success:function(json)
{
$('#total').text(json.number)
}
})
and this is my urls.py file in django app :
from django.contrib import admin
from django.urls import path,include
from DetectHate import views
from django.urls import path,re_path
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^sentiment/$', views.sentiment,name="sentiment"),
]
and this is my views.py file -
import json
from django.http import Http404,HttpResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def sentiment(request):
if request.is_ajax():
var=request.POST.get('number')+5
data={}
data['number']=var+5
return HttpResponse(json.dumps(data),content_type='application/json')
else:
raise Http404

Django error in request/response middleware- TypeError: __init__() takes 1 positional argument but 2 were given

I'm still pretty new to Django and cant seem to get anywhere with this error (I've read through similar posts here with no luck). Code in urls.py is pasted below:
from django.conf.urls import include, url
from django.contrib import admin
# Add this import
from django.contrib.auth import views
from log.forms import LoginForm
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(('dashboard.urls', "dashboard"), namespace='dashboard')),
url(r'^login/$', views.LoginView, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'),
url(r'^logout/$', views.LogoutView, {'next_page': '/'}),
]
Full trace is below:
Internal Server Error: /login/
Traceback (most recent call last):
File "C:\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python36-32\lib\site-packages\django\core\handlers\base.py", line 127, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python36-32\lib\site-packages\django\core\handlers\base.py", line 125, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: __init__() takes 1 positional argument but 2 were given
[21/Aug/2018 00:20:27] "GET /login/?next=/ HTTP/1.1" 500 64213
Any ideas on how to solve this? Or what could be causing this error?
In short: you need to use .as_view() to "convert" a class-based view, to a view that can be used in the urls.py.
The LoginView [Django-doc] and LogoutView [Django-doc] are class-based views, in order to make these callable in the urls.py, you need to use as_view:
from django.conf.urls import include, url
from django.contrib import admin
# Add this import
from django.contrib.auth import views
from log.forms import LoginForm
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(('dashboard.urls', "dashboard"), namespace='dashboard')),
url(r'^login/$', views.LoginView.as_view(), {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'),
url(r'^logout/$', views.LogoutView.as_view(), {'next_page': '/'}),
]
A class-based view contains such function that acts as a wrapper, and each time initializes a instance. If you would use LoginView directly, you would call the constructor of the LoginView class. Although with some extra logic, it would be possible to return a HttpResponse, it is not very elegant (you do not expect a HttpResponse when you construct a LoginView), and furthermore it would make subclassing of views (which is one of the reasons why such class-based views can save a lot of work) very cumbersome.

Django first app

I have some problems with my first django app (its name is magghy). I'm at the start of development. So, I have:
magghy/urls.py:
from django.conf.urls import *
from magghy import views
from . import views
app_name = 'magghy'
urlpatterns = [
# esempio: /magghy/
url(r'^$', views.index, name='index'),
#esempio: /magghy/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /magghy/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /magghy/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
In magghy/views.py:
from __future__ import unicode_literals
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Choice, Question
from django.template import loader
from django.urls import reverse
#visualizzare domande e argomento specifico - collegare con modulo magghy.urls
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
#visualizzare pagina html secondo schema index.html oppure html 404 (eccezione)
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('magghy/index.html')
context = RequestContext (request, {
'latest_question_list': latest_question_list,
})
return HttpResponse(template.render(context))
#visualizzare pagina 404
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
In mysite/urls.py:
from django.conf.urls import *
from django.contrib import admin
from magghy import views
urlpatterns = [
url(r'^magghy/', views.detail),
url(r'^admin/', include (admin.site.urls)),
]
The page http://127.0.0.1:8000/admin/ works perfectly!
The page http://127.0.0.1:8000/magghy/ doesn't work
The page http://127.0.0.1:8000/magghy/5 doesn't work
In both case the terminal logs are:
Internal Server Error: /magghy/
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: detail() takes exactly 2 arguments (1 given)
Please, can you help me? Thanks a lot!
Adri
mysite/urls.py is linking directly to the detail view, rather than including the app URLs. It should be:
urlpatterns = [
url(r'^magghy/', include('magghy.urls')),
url(r'^admin/', include (admin.site.urls)),
]

Passing parameters to a view in Django

In my urls.py I have set handler404 to CustomErrorView. CustomErrorView is a generic view which generates a template for an error based on the error message and error code that it receives.
Since the handler404 is only raised in the case of a 404 error, how can I send the errorcode = 404 kwarg to CustomErrorView whenever it is raised?
Already tried-
handler404 = CustomErrorView(errorcode = 404)
This causes an "Expected one positional argument, none given error."
handler404 = CustomErrorView(request, errorcode = 404)
This causes a NameError (Name 'request' is not defined)
My urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from blog_user.views import home, create_error_view
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', home),
url(r'^', include('user_manager.urls')),
]
handler404 = create_error_view(error = 404)
handler500 = create_error_view(error = 500)
My views.py (after using the modifications recommended by #knbk) :
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound
def create_error_view(error = 404, mybad = False):
def custom_error_view(request, error, mybad):
''' Returns a generic error page. Not completed yet. error code and messages are supposed to be modular so that it can be used anywhere for any error in the page.'''
content = "Incorrect url"
context= {
'error': error,
'content':content,
'mybad':mybad
}
response = render(request, 'error.html', context=context, status=error)
return HttpResponse(response)
return custom_error_view
You can use a function closure to create the view function:
def create_error_view(error_code):
def custom_error_view(request, *args, **kwargs):
# You can access error_code here
return custom_error_view
Then just call create_error_view to set the handler:
handler404 = create_error_view(error_code=404)
Or you can use functools.partial(), which basically does the same:
from functools import partial
handler404 = partial(custom_error_view, error_code=404)

Categories