Django login doesn't work - django

I tried to create a login view like the following:
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('rango/index.html')
else:
return HttpResponse('Your Rango account is disabled!')
else:
print("Invalid login details: {0}, {1}".format(username, password))
return HttpResponse("Invalid login details supplied!")
else:
return render(request, 'rango/login.html', {})
This seems to be the correct way to do so, but when I try to open the page in my browser, I get the following error:
TypeError at /rango/login/
login() missing 1 required positional argument: 'user'
Request Method: GET
Request URL: http://localhost:8000/rango/login/
Django Version: 1.9.10
Exception Type: TypeError
Exception Value:
login() missing 1 required positional argument: 'user'
Exception Location: C:\Users\Johannes\tangowithdjango\lib\site-packages\django\core\handlers\base.py in get_response, line 147
Python Executable: C:\Users\Johannes\tangowithdjango\Scripts\python.exe
Python Version: 3.6.0
Python Path:
['C:\\Users\\Johannes\\tangowithdjango\\tango_with_django_project',
'C:\\Users\\Johannes\\tangowithdjango\\Scripts\\python36.zip',
'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36\\lib',
'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36',
'C:\\Users\\Johannes\\tangowithdjango',
'C:\\Users\\Johannes\\tangowithdjango\\lib\\site-packages']
Server time: Thu, 12 Jan 2017 17:56:38 +0100
Has anyone encountered something similar or knows a solution to the problem? I already searched and tried around for a bit but couldn't find an answer.

Your code looks good, make sure that you are importing this
from django.contrib.auth import authenticate, login
Also check your views
This is the first url:
url(r'^login', example_views.login, name='log'),
And you have to change to this:
url(r'^log', example_views.log, name='log'),

I followed that tutorial and came across the same error.
I solved it by correcting one line in urls.py
urlpatterns = patterns(
...
url(r'^login/$', views.login, name='login'),
)
into this:
urlpatterns = patterns(
...
url(r'^login/$', views.user_login, name='login'),
)
It should be the name of the login view you created, which is 'user_login' in your case.

Related

issue in redirecting user to home page django

When I try to login, it does not reedirect me to home page. instead, it shows me an error
the url should be http://127.0.0.1:8000/ it shows http://127.0.0.1:8000/login
I tried to user both function and path names
urls.py
app_name = "accounts"
urlpatterns = [
path('', views.home,name="home"),
path('register/',views.register, name='register'),
path('login/',views.loginPage, name='login')]
views.py
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request,username=username, password=password)
if user is not None:
login(request,user)
return redirect('home')
return render(request,'accounts/login.html')
Error
NoReverseMatch at /login/
Reverse for 'home' not found. 'home' is not a valid view function or pattern name.
Request Method: POST
Request URL: http://127.0.0.1:8000/login/
Django Version: 3.0.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'home' not found. 'home' is not a valid view function or pattern name.
Exception Location: C:\Users\Mahmoud Ishag\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677
In views.py the url name works differently to when in template.
You can try to change return redirect('home') to return redirect('') or return redirect('/'), depends on how you defined the URL in path('', views.home, name="home").

NoReverseMatch: Reverse for 'INSERT URL NAME' not found

I am learning about Django forms and am struggling to render a basic 'results' page for the form.
I would be greatly appreciative if somebody could point out what I'm doing wrong! Thanks in advance :)
ERROR
NoReverseMatch at /search_query/
Reverse for 'results' not found. 'results' is not a valid view function or pattern name.
Request Method: POST
Request URL: http://ozxlitwi.apps.lair.io/search_query/
Django Version: 2.0
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'results' not found. 'results' is not a valid view function or pattern name.
Exception Location: /mnt/data/.python-3.6/lib/python3.6/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 632
Python Executable: /mnt/data/.python-3.6/bin/python
Python Version: 3.6.5
Python Path:
['/mnt/project',
'/mnt/data/.python-3.6/lib/python36.zip',
'/mnt/data/.python-3.6/lib/python3.6',
'/mnt/data/.python-3.6/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6',
'/mnt/data/.python-3.6/lib/python3.6/site-packages']
Server time: Fri, 1 Jun 2018 10:00:20 +0900
views.py
def search_query(request):
# If POST request, process the Form data:
if request.method == 'POST':
# Create a form instance and populate it with the data from the request (binding):
form = SearchQueryForm(request.POST)
# Check if the form is valid:
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('results'))
else:
form = SearchQueryForm()
context = {'form':form}
return render (request, 'mapping_twitter/search_query.html', context)
def results(request):
context = {'form':form}
return render(request, 'mapping_twitter/results.html', context)
mapping_twitter/urls.py
from django.urls import path
from . import views
app_name = 'mapping_twitter'
urlpatterns = [
path('', views.search_query, name='search-query'),
path('results/', views.results, name='results'),
]
mapping_data/urls.py
urlpatterns = [
path('search_query/', include('mapping_twitter.urls')),
path('admin/', admin.site.urls),
path('', RedirectView.as_view(url='/search_query', permanent=True)),
]
mapping_twitter/results.html
<!--- DRAFT --->
Display search results here
If your results endpoint is in an app called mapping_twitter, then you can get at it with reverse('mapping_twitter:results').
Further reading on reversing namespaced URLs: https://docs.djangoproject.com/en/2.0/topics/http/urls/#reversing-namespaced-urls

About django rest framework document, how custom the description of request params and add the field to post params?

In the auto-generate view by rest_framework.documentation,when I take the post test, there is no field to fill my params, and how to add the description of request params like the api of "delete>list"?
I can not get the ideas from the document:Documenting your API
Should I write some code at here?
#api_view(['POST'])
def Login(request):
try:
username=request.data['username']
password=request.data['password']
except Exception as error:
return Response(str(error), status=status.HTTP_400_BAD_REQUEST)
user = authenticate(username=username, password=password)
if user is None:
or :
from django.conf.urls import url, include
from django.contrib import admin
from . import views
from rest_framework.documentation import include_docs_urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^media/(?P<file_path>.*)', views.GetMediaFiles),
url(r'^api/',include('api.urls')),
url(r'^docs/', include_docs_urls(title='CLTools API Docs')),
]
Thanks!

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

Facebook authentication using angular JS and Django

I'm a beginner in both angular JS and django. I was following this particular tutorial in making a facebook authentication app.
http://cbdev.blogspot.in/2014/02/facebook-login-with-angularjs-django.html
I've followed the tutorial exactly. And when I start the server I get the error.
NameError at /
name 'strategy' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.3.1
Exception Type: NameError
Exception Value:
name 'strategy' is not defined
Exception Location: /root/Documents/django/clueless/clueless_engine/../clueless_engine/views.py in <module>, line 1
Python Executable: /root/Documents/django/clueless/bin/python
Python Version: 2.7.13
Python Path:
['/root/Documents/django/clueless/clueless_engine',
'/root/Documents/django/clueless/lib/python2.7',
'/root/Documents/django/clueless/lib/python2.7/plat-x86_64-linux-gnu',
'/root/Documents/django/clueless/lib/python2.7/lib-tk',
'/root/Documents/django/clueless/lib/python2.7/lib-old',
'/root/Documents/django/clueless/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/root/Documents/django/clueless/local/lib/python2.7/site-packages',
'/root/Documents/django/clueless/lib/python2.7/site-packages']
Server time: Thu, 1 Jun 2017 07:30:14 +0530
my views.py file is
#strategy()
def auth_by_token(request, backend):
backend = request.strategy.backend
user=request.user
user = backend.do_auth(
access_token=request.DATA.get('access_token'),
user=user.is_authenticated() and user or None
)
if user and user.is_active:
return user# Return anything that makes sense here
else:
return None
#csrf_exempt
#api_view(['POST'])
#permission_classes((permissions.AllowAny,))
def social_register(request):
auth_token = request.DATA.get('access_token', None)
backend = request.DATA.get('backend', None)
if auth_token and backend:
try:
user = auth_by_token(request, backend)
except Exception, err:
return Response(str(err), status=400)
if user:
strategy = load_strategy(request=request, backend=backend)
_do_login(strategy, user)
return Response( "User logged in", status=status.HTTP_200_OK )
else:
return Response("Bad Credentials", status=403)
else:
return Response("Bad request", status=400)
I have created Social Auth authentication using python scocial auth. you can check:
https://github.com/ranvijay-sachan/django-rest-login-and-social_auth/tree/master/profiles
POST: http://localhost:8000/api/v1/login/2/
Content-Type : application/json
{ "accessToken": "alert token" }
The problem was that I forgot to import modules.
from social.apps.django_app.utils import load_strategy strategy = load_strategy(request)