How to fix "Incomplete response received from application" - python

I must be going crazy...
If I have my views.py file with 48 or less lines, when I POST data to it, I see
Incomplete response received from application
However, If I have 49 lines or more I get a
NameError, 'request' is not defined
thrown on line 31 and 49, even if line 31/49 is empty.
Could someone please explain what is happening?
Also btw Django Admin - "Incomplete response received from application" does not answer my question.
veiws.py:
from django.shortcuts import render
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.core.exceptions import *
from datetime import datetime
def remove_xss(chat, request):
return chat
def find_urls(chat, request):
new_chat = ' '.join([('{}'.format(word, word) if ('http://' in word or 'https://' in word) else word) for word in chat.split(' ')])
return new_chat
def format_chat(chat, username, request):
chat = remove_xss(chat, request)
chat = find_urls(chat, request)
request = request
return "hi"
def chat_index(request):
return render(request, 'chatroom.html')
def chat(request):
if request.method == 'POST':
chat = request.POST.get('textfield', None)
if request.user.is_authenticated():
u = request.user.username
f_chat = format_chat(chat, u, request)
else:
return HttpResponse('You must be signed in to continue')
with open('chats.txt', 'a') as chats:
chats.write(f_chat)
return render(request, 'chatroom.html')
urls.py: (Working (i think))
from chat import views
from django.urls import path
urlpatterns = [
path('/', views.chat_index),
path('chat/', views.chat)
]
Full Traceback: (when there is >=49 lines)
Traceback:
File "/home/raveivcs/virtualenv/backend/3.5/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/raveivcs/virtualenv/backend/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/home/raveivcs/virtualenv/backend/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/raveivcs/backend/chat/views.py" in chat
49.
File "/home/raveivcs/backend/chat/views.py" in format_chat
31.
Exception Type: NameError at /chat/chat/
Exception Value: name 'request' is not defined

Ok, for anyone coming here, all you need to do is look in different files. The error doesn't have to be in the file you think it is in.

Related

django-tenants: redirecting to tenant url after login raises "NoReverseMatch: 'demo.localhost' is not a registered namespace"

I don't seem to find a way to solve an error happening at the user authentication.
User needs to login at the public website level let's say localhost/login and when he/she is authenticated, I need the user to be redirected in the corresponding sub domain, for example demo.localhost. This is not working for me so far, even after checking some posts about the subject.
Here is the views.py in customers.views where user log in:
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(request,data=request.POST)
print("form login view")
if form.is_valid():
print("checkpoint")
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
user = form.get_user()
schema_name = user.schema_name
print(user)
if user is not None:
login(request, user)
url = reverse(schema_name + '.localhost:8000/mydashboard/')
print("url")
return HttpResponseRedirect(url)
else:
print("not working")
form = AuthenticationForm()
context = {
'form': form,
}
return render(request, 'login.html', context)
here is what urls in the core folder:
urlpatterns = [
path('admin/', admin.site.urls),
path('django_plotly_dash/', include('django_plotly_dash.urls')),
path('mydashboard/', include('mydashboard.urls',namespace="mydashboard")),
]
and I have added app_name = 'mydashboard' in mydashboard.urls
Here is the traceback of the error I keep getting:
Internal Server Error: /registration/loginUser
Traceback (most recent call last):
File "/Users/pierre/opt/anaconda3/lib/python3.9/site-packages/django/urls/base.py", line 71, in reverse
extra, resolver = resolver.namespace_dict[ns]
KeyError: 'demo.localhost'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/pierre/opt/anaconda3/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/pierre/opt/anaconda3/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/pierre/Desktop/simulation_application/customers/views.py", line 65, in login_view
url = reverse(schema_name + '.localhost:8000/mydashboard/')
File "/Users/pierre/opt/anaconda3/lib/python3.9/site-packages/django/urls/base.py", line 82, in reverse
raise NoReverseMatch("%s is not a registered namespace" % key)
django.urls.exceptions.NoReverseMatch: 'demo.localhost' is not a registered namespace
UPDATE:
Remove the reverse and included request.scheme in the url.
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(request,data=request.POST)
print("form login view")
if form.is_valid():
print("checkpoint")
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
user = form.get_user()
schema_name = user.schema_name
print(user)
if user is not None:
login(request, user)
print(request.scheme)
url = request.scheme + '://' + schema_name + '.localhost:8000/mydashboard/'
print("url",url)
return HttpResponseRedirect(url)
else:
print("not working")
form = AuthenticationForm()
context = {
'form': form,
}
return render(request, 'login.html', context)
this is still working and output the following error:
response = get_response(request) …
Local vars
/Users/pierre/opt/anaconda3/lib/python3.9/site-packages/django/core/handlers/base.py, line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
Local vars
/Users/pierre/opt/anaconda3/lib/python3.9/site-packages/django/contrib/auth/decorators.py, line 32, in _wrapped_view
return redirect_to_login( …
Local vars
/Users/pierre/opt/anaconda3/lib/python3.9/site-packages/django/contrib/auth/views.py, line 190, in redirect_to_login
return HttpResponseRedirect(urlunparse(login_url_parts)) …
Local vars
/Users/pierre/opt/anaconda3/lib/python3.9/site-packages/django/http/response.py, line 507, in __init__
raise DisallowedRedirect("Unsafe redirect to URL with protocol '%s'" % parsed.scheme) …
Local vars
Unsafe redirect to URL with protocol 'localhost'
Bad Request: /mydashboard/simulations_list
HTTP GET /mydashboard/simulations_list 400 [0.09, 127.0.0.1:50218]
This is strange because the requested url is perfectly working url, registered and accessible without a problem before trying to redirect to it after the login
EDIT #2:
Found out that the above code works when the target url does not require login required
# this does not work
#login_required
def simulationslistView(request,):
return render(request, 'simulations_list.html')
# this works
def simulationslistView(request,):
return render(request, 'simulations_list.html')
I am obviously make sure that the app is secured and can only be accessed by logged in users. Is there a work around to make sure it works?
reverse is an internal django utility to go from "app name" + ':' + "url friendly name" to "real url". In your example, you're already providing the "real url".
Quit while you're ahead and just do:
if user is not None:
login(request, user)
url = request.scheme + '://' + schema_name + '.localhost:8000/mydashboard/'
print("url")
return HttpResponseRedirect(url)
Notice no reverse
Notice the adding of the URL scheme (http/https determined by how the request was originally made)

TypeError: login() got an unexpected keyword argument 'template_name'

I upgraded my project from Django 1.11 to 2.2, made all the changes but came with new error that says login() got an unexpected keyword argument 'template_name'.It worked fine with the previous version of Django 1.11 (All the other urls are working, only the landing page gives the error). I couldn't find any references to this issue. Below is the error and urls and views for the issue.
Internal Server Error: /
Traceback (most recent call last):
File "C:\Users\User\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\User\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\User\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\PycharmProjects\MyWebsite\landing\views.py", line 43, in landing_validation
login_response = login(request, template_name='landing.html')
TypeError: login() got an unexpected keyword argument 'template_name'
[19/Apr/2019 16:20:00] "GET / HTTP/1.1" 500 71948
Landing\urls.py
from django.conf.urls import url
from landing.views import landing_validation
app_name='landing'
urlpatterns = [
url(r'^$', landing_validation, name='landing')
]
Landing\views.py
from django.contrib.auth import login
def landing_validation(request):
login_response = login(request, template_name='landing.html')
return login_response
C:\Users\User\venv\Lib\site-packages\django\contrib\auth__init__.py
def login(request, user, backend=None):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = ''
if user is None:
user = request.user
if hasattr(user, 'get_session_auth_hash'):
session_auth_hash = user.get_session_auth_hash()
if SESSION_KEY in request.session:
if _get_user_session_key(request) != user.pk or (
session_auth_hash and
not constant_time_compare(request.session.get(HASH_SESSION_KEY, ''), session_auth_hash)):
# To avoid reusing another user's session, create a new, empty
# session if the existing session corresponds to a different
# authenticated user.
request.session.flush()
else:
request.session.cycle_key()
try:
backend = backend or user.backend
except AttributeError:
backends = _get_backends(return_tuples=True)
if len(backends) == 1:
_, backend = backends[0]
else:
raise ValueError(
'You have multiple authentication backends configured and '
'therefore must provide the `backend` argument or set the '
'`backend` attribute on the user.'
)
else:
if not isinstance(backend, str):
raise TypeError('backend must be a dotted import path string (got %r).' % backend)
request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
request.session[BACKEND_SESSION_KEY] = backend
request.session[HASH_SESSION_KEY] = session_auth_hash
if hasattr(request, 'user'):
request.user = user
rotate_token(request)
user_logged_in.send(sender=user.__class__, request=request, user=user)
There was no need to do a landing_validation view this line solved the issue.
url(r'^$', LoginView.as_view(template_name='landing.html'), name='landing')
In Django 2.2 app I fixed similar error by using LoginView instead of login.
File users/urls.py:
from django.conf.urls import url
# from django.contrib.auth.views import login
from django.contrib.auth.views import LoginView
from . import views
app_name = 'users'
urlpatterns = [
# url(r'^login/$', login, {'template_name': 'users/login.html'}, name='login'),
url(r'^login/$', LoginView.as_view(template_name='users/login.html'), name='login'),
]
The login function that you're using is not actually a view. It's just a regular function which you can use to authenticate a user and set the session cookie, etc.
Read the docs for it's usage: https://docs.djangoproject.com/en/2.2/topics/auth/default/#django.contrib.auth.login
Judging by your code, it appears you want to use LoginView.
from django.contrib.auth.views import LoginView
def landing_validation(request):
login_response = LoginView.as_view()(request, template_name='landing.html')
return login_response
You can see that django.contrib.auth.login takes request, user, and an optional backend. There is no template_name. This hasn't changed recently, so I think you would get the same problem in 1.11, too.
It looks like you want a view function, but django.contrib.auth.login is not that. It doesn't return a response.

How to solve a attribute error in Django?

I am trying to log in a user but I am getting an attribute error.
Here is my forms.py:
class Login(forms.Form):
email = forms.EmailField(max_length=250)
password = forms.CharField(widget=forms.PasswordInput)
def login_user(self):
email = self.cleaned_data['email']
password = self.cleaned_data.get('password')
user = authenticate(email=email, password=password)
if user in User.objects.all():
login(self, user)
else:
return render(self, 'todoapp/waiting_2.html')
Here is my views.py:
def login_user(request):
if request.method == 'POST':
login_form = Login(request.POST)
if login_form.is_valid():
login_form.login_user()
login_form.save()
return HttpResponseRedirect(reverse('dashboard'))
else:
return render(request, 'todoapp/waiting_2.html')
return render(request, 'registration/login.html', {'form': Login()})
When I fill in the fields and try to log in, I am getting the error:
AttributeError at /login/
'Login' object has no attribute 'session'
Traceback:
File "/home/gblp250/PycharmProjects/practice/venv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/home/gblp250/PycharmProjects/practice/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/gblp250/PycharmProjects/practice/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/gblp250/PycharmProjects/assignment/todoapp/views.py" in login_user
48. login_form.login_user(request)
File "/home/gblp250/PycharmProjects/assignment/todoapp/forms.py" in login_user
27. login(self, request, user)
File "/home/gblp250/PycharmProjects/practice/venv/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in login
126. if SESSION_KEY in request.session:
Exception Type: AttributeError at /login/
Exception Value: 'Login' object has no attribute 'session'
There are a few errors here. The main one of attempting to render within the form login_user method. Apart from anything else, you attempt to pass the self as the request parameter to render, which mages no sense.
Remove all of that if/else. You don't need to render; but also note that your if condition is needlessly inefficient. If you get a user, it's necessarily a User.
Finally, the actual cause of your error, where again you are trying to pass self in the place of a request, but this time as the parameter to login. That code belongs in the view.
And finally, the form is not a ModelForm, so there is no save method.
So, form:
def login_user(self):
email = self.cleaned_data['email']
password = self.cleaned_data.get('password')
return authenticate(email=email, password=password)
and view:
if login_form.is_valid():
user = login_form.login_user()
if user:
login(request, user)
return HttpResponseRedirect(reverse('dashboard'))
Although at this point you may as well move all that logic to the view.
login() get as first argument the request, you call it with the form as first argument.
https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.login

Django missing 1 required positional argument

I am trying to make a view that i can use in multiple apps with different redirect urls:
Parent function:
def create_order(request, redirect_url):
data = dict()
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
form.save()
return redirect(redirect_url)
else:
form = OrderForm()
data['form'] = form
return render(request, 'core/order_document.html', data)
Child function:
#login_required()
def admin_order_document(request):
redirect_url = 'administrator:order_waiting_list'
return create_order(request, redirect_url)
When i'm trying to call admin_order_document function i'm getting:
Traceback (most recent call last):
File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: create_order() missing 1 required positional argument: 'redirect_url'
If i remove redirect_url from both functions and manually add 'administrator:order_waiting_list' to redirect() it works, but i need to redirect to multiple urls. So, why am i getting this error?
url(r'^orders/create/', views.create_order, name='create_order')
This clearly is not going to work, since create_order requires redirect_url but there is no redirect_url kwarg in the regex r'^orders/create/'.
Perhaps you want to use the admin_order_document view here instead:
url(r'^orders/create/', views.admin_order_document, name='create_order')
Note you should add a trailing dollar, i.e. r'^orders/create/$' unless you want to match orders/create/something-else as well as orders/create/.
If you didn't changed the regular url
urlpatterns = [
url(r'^admin/', admin_site.urls),
...
]
of your admin site you need to call your function like that:
#login_required()
def admin_order_document(request):
redirect_url = 'admin:order_waiting_list'
return create_order(request, redirect_url)
That should fix your problem.

python-social-auth AuthCanceled exception

I'm using python-social-auth in my Django application for authentication via Facebook.
But when a user tries to login, they have been redirected to the Facebook app page, and they click on the "Cancel" button, the following exception appears:
ERROR 2014-01-03 15:32:15,308 base :: Internal Server Error: /complete/facebook/
Traceback (most recent call last):
File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
return view_func(*args, **kwargs)
File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/apps/django_app/utils.py", line 45, in wrapper
return func(request, backend, *args, **kwargs)
File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/apps/django_app/views.py", line 21, in complete
redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/actions.py", line 54, in do_complete
*args, **kwargs)
File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/strategies/base.py", line 62, in complete
return self.backend.auth_complete(*args, **kwargs)
File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/facebook.py", line 63, in auth_complete
self.process_error(self.data)
File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/facebook.py", line 56, in process_error
super(FacebookOAuth2, self).process_error(data)
File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/oauth.py", line 312, in process_error
raise AuthCanceled(self, data.get('error_description', ''))
AuthCanceled: Authentication process canceled
Is the any way to catch it Django?
python-social-auth is a newer, derived version of django-social-auth.
AlexYar's answer can be slightly modified to work with python-social-auth by modify settings.py with following changes:
Add a middleware to handle the SocialAuthException
MIDDLEWARE_CLASSES += (
'social.apps.django_app.middleware.SocialAuthExceptionMiddleware',
)
URL to redirect to, when an exception occurred
SOCIAL_AUTH_LOGIN_ERROR_URL = '/'
Note that you also need to set
DEBUG = False
That's all or read http://python-social-auth.readthedocs.org/en/latest/configuration/django.html#exceptions-middleware
you can create a middleware and catch any exceptions,
exception list: https://github.com/omab/python-social-auth/blob/master/social/exceptions.py
in this case your AuthCanceled Exception.
middleware.py
from social.apps.django_app.middleware import SocialAuthExceptionMiddleware
from django.shortcuts import HttpResponse
from social import exceptions as social_exceptions
class SocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware):
def process_exception(self, request, exception):
if hasattr(social_exceptions, 'AuthCanceled'):
return HttpResponse("I'm the Pony %s" % exception)
else:
raise exception
settings.py
MIDDLEWARE_CLASSES = (
.....
'pat_to_middleware.SocialAuthExceptionMiddleware',
)
This is slight modification of #Nicolas answer and this works for me.
middleware.py
from social.apps.django_app.middleware import SocialAuthExceptionMiddleware
from django.shortcuts import render
from social.exceptions import AuthCanceled
class SocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware):
def process_exception(self, request, exception):
if type(exception) == AuthCanceled:
return render(request, "pysocial/authcancelled.html", {})
else:
pass
settings.py
MIDDLEWARE_CLASSES += (
'myapp.middleware.SocialAuthExceptionMiddleware',
)
The 2018 answer:
Add SocialAuthExceptionMiddleware middleware to your config:
MIDDLEWARE_CLASSES = [
...
'social_django.middleware.SocialAuthExceptionMiddleware',
]
Set SOCIAL_AUTH_LOGIN_ERROR_URL in your config:
SOCIAL_AUTH_LOGIN_ERROR_URL = '/login'
Now when you have DEBUG = False, your users will get redirected to your login page when they click cancel in social auth provider's page.
When DEBUG = True you will still see the error page in your browser during development.
Just add in
MIDDLEWARE_CLASSES = (
'social_auth.middleware.SocialAuthExceptionMiddleware',
)
and something like
LOGIN_ERROR_URL = '/'
That's all
or read http://django-social-auth.readthedocs.org/en/latest/configuration.html#exceptions-middleware
If you don't care about handling the exception do the following in your settings.py
SOCIAL_AUTH_RAISE_EXCEPTIONS = False
See this answer: How to solve Authentication process canceled error?
This is a updated imports middleware using social_django
from social_django.middleware import SocialAuthExceptionMiddleware
from social_core import exceptions as social_exceptions
from django.shortcuts import HttpResponse
from django.shortcuts import render, redirect
class FacebookAuthCanceledExceptionMiddleware(SocialAuthExceptionMiddleware):
def process_exception(self, request, exception):
if hasattr(social_exceptions, 'AuthCanceled'):
return redirect('auth_login')
else:
raise exception

Categories

Resources