How import and use csrf token in django 1.11? - python

Pease help use csrf token in django 1.11
in view.py i use follow code:
from django.shortcuts import render_to_response, redirect
from django.contrib import auth
from django.views.decorators.csrf import csrf
def login(request):
args = {}
args.update(csrf(request))
if request.POST:
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
args['login_error'] = 'Пользователь не найден';
return render_to_response('login.html', args)
else:
return render_to_response('login.html', args)
but console display follow error message:
File "/home/kalinin/django/login/views.py", line 3, in from
django.views.decorators.csrf import csrf ImportError: cannot import
name 'csrf'
in django 1.8 i use similar code, but import csrf:
from django.core.context_processors import csrf
and applications is running without problems
Please help run my application for django 1.11

In Django 1.8 the template context processor was moved to django.template.context_processors.csrf, so the import would be:
from django.template.context_processors import csrf
However, you don't need to import it at all. Stop using render_to_response, it's obsolete. Use the render shortcut instead.
from django.shortcuts import render
return render(request, 'login.html', args)
When you use the render shortcut, then you don't need to worry about the csrf token in the view, and you can remove this line.
args.update(csrf(request))

Related

Django. ImportError: attempted relative import beyond top-level package

I'm a newbie. And I just started writing a django project. It is called the iRayProject and consists of two applications iRay_user_authentication and iRay_working_with_notes:
project structure here
iRay_user_authentication - this is a standard django app for registration
Here is his urls.py
from django.urls import path
from .views import login_user, registration
urlpatterns = [
path('', login_user, name='login_user'),
path('registration', registration, name='registration'),
]
In views.py registered user using redirect I want to send to the second application of the project
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.contrib.auth import login, logout, authenticate
from ..iRay_working_with_notes.views import list_notes
def login_user(request):
if request.method == 'GET':
return render(request, 'iRay_user_authentication/login.html', {'form': AuthenticationForm})
def registration(request):
if request.method == 'GET':
return render(request, 'iRay_user_authentication/registration.html', {'form': UserCreationForm})
else:
if '_guest' in request.POST:
pass
else:
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
user.save()
login(request, user)
return redirect(list_notes)
except IntegrityError:
return render(request, 'iRay_user_authentication/registration.html', {'form': UserCreationForm,
'error': 'name is busy '
})
else:
return render(request, 'todo_app/registration.html', {'form': UserCreationForm,
'error': 'passwords not math'})
But when trying to import a function from the second views.py
from django.shortcuts import render
def list_notes(request):
return render(request, 'iRay_working_with_notes/list_notes.html')
I get an error:
ImportError: attempted relative import beyond top-level package
And I found a lot of theoretical information about why this error occurs.
But I still couldn 't figure out if there is an easy way for relative or absolute import , or I just didn 't structure my project correctly ??
import is wrong
from ..iRay_working_with_notes.views import list_notes
should be
from iRay_working_with_notes.views import list_notes
redirect needs view name from the urls-pattern:
redirect('name-of-my-view-pattern')
So please create a url-pattern entry for the list_notes view and give the pattern name as parameter to the redirect.
Why? because a redirect is telling the browser on the client side to load the target redirect page, so it needs an url (that is generated by django via the url-pattern), as the target page will be called from the browser.
Technically of course you can import a view and call it from another module directly as it is just a python function - but that is not a http redirect (and would not change the url in the browser to the redirected page) and additionally that is not really the idea of the django request/response architecture.

Trying to redirect to different page based on login credential provided in DJango

I want to redirect to different pages based on the login credentials in django.
For an example: There are two login provided
If i login with X credentials then i will be redirected to X page. While on same login page if i login with Y credential i will be redirected to correponding Y page.
I tried to put condition in user_login views.py file but this gives me following error.
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'companyDashboard.html' not found. 'companyDashboard.html' is not a valid view function or pattern name.
My views.py file
from django.shortcuts import render
from django.template import RequestContext
from wfhApp.forms import UserForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required
def company_dashboard(request):
return render(request, 'wfhApp/company_dashboard.html')
#login_required
def companyDashboard(request):
return render(request, 'wfhApp/companyDashboard.html')
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
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:
if user.username == 'prashant':
login(request, user)
return HttpResponseRedirect(reverse('company_dashboard.html'))
elif user.username == 'saurabh':
login(request, user)
return HttpResponseRedirect(reverse('companyDashboard.html'))
else:
return HttpResponse("Account Not Exists")
else:
return HttpResponse("Account Not Active")
else:
print("Someone tried to login and failed")
print("Username: {} and Password: {}".format(username, password))
return HttpResponse("Invalid Login Details")
else:
return render(request, 'wfhApp/login.html')
Thank you for your time and consideration.
Check out urlresolvers docs, to use reverse you must set name in path (urls.py). Don´t add .html extension, use the setted name at urls.py.
from news import views
path('archive/', views.archive, name='news-archive')
Use the setted name.
# using the named URL
reverse('news-archive')
# passing a callable object
# (This is discouraged because you can't reverse namespaced views this way.)
from news import views
reverse(views.archive)

View UrlGatewayLogin didn't return an HttpResponse object. It returned None instead

It's a bit repetitive this error is everywhere to find, but I'm a bit confused about what is happening.
I'm trying to pass a token in the url for the user to login like so http://localhost:8000/auth/login/?token=token. After the user is authenticated it should be redirected to dashboard. But I'm getting this error. Can you help me understand what is happening?
View:
import logging
from django.contrib.auth import authenticate, login
from django.core.urlresolvers import reverse, reverse_lazy
from django.shortcuts import render
from django.views.generic import View
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.contrib.auth.backends import ModelBackend
from rest_framework_jwt.settings import api_settings
from business_accounts.models.my_user import MyUser
logger = logging.getLogger(__name__)
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
class UrlGatewayLogin(View):
def get(self, request, **kwargs):
page_group = kwargs.get('page_group')
token = request.GET.get('token')
try:
payload = jwt_decode_handler(token)
user = MyUser.objects.get(pk=payload.get('id'))
user.backend = 'django.contrib.auth.backends.ModelBackend'
except MyUser.DoesNotExist:
return None
authenticate(token=token)
logger.warning("User is=%s", user)
print(user)
login(request, user)
return HttpResponseRedirect('dashboard', {'page_group': page_group})
URL:
url(r'^auth/login/$', UrlGatewayLogin.as_view(), name='auth-login')
As the error suggests, your view should always return an HttpResponse object. At the moment, you have return None in your except block.
You could prevent the error by doing something like:
from django.http import HttpResponseBadRequest
try:
...
except MyUser.DoesNotExist:
return HttpResponseBadRequest("Invalid token")

Django login part

I am now working on a system using the Django framework. I am writing the user login part. It seems successful but it doesn't work very well.
The login system can recognise the user by his/her username and password.
The authentication could only last for one "webpage". When I loaded another page or even reloaded the page, django can't get the info of the user(seems logged out)
If I looked at the page resources, I saw a session number made after the login process.
What should I do to ensure only one login is needed? And keep my user logged in during the whole process?
Here is my view file
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext, loader
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render_to_response,redirect
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.template.context_processors import csrf
from . import models
from . import form as f
from django.contrib.sessions.backends.db import SessionStore
def index(request):
if request.user != None :
template = loader.get_template('index.html')
return HttpResponse(template.render(None))
else :
return HttpResponseRedirect('/PDT/login_failed')
def Home(request):
template = loader.get_template('Home.html')
return HttpResponse(template.render(None))
def loggin_in(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def login_user(request):
logout(request)
username = password = ''
if request.POST:
username = request.POST.get('username','')
password = request.POST.get('password','')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
request.session['username']=user.username
return HttpResponseRedirect('/PDT/logged_successful')
return HttpResponseRedirect('/PDT/inactive')
return HttpResponseRedirect('/PDT/incorrect')
return HttpResponseRedirect('/PDT/login_failed')
def logged_in(request):
if request.user :
return render_to_response('index.html',{ 'user' : request.user },context_instance=RequestContext(request))
else :
return HttpResponseRedirect('/PDT/login_failed')
def login_failed(request):
return render_to_response('problem.html',{ 'message' : "Login failed" })
def log_out(request):
request.session.flush()
logout(request)
return render_to_response('problem.html',{ 'message' : "Logged out" })
def inactive(request):
return render_to_response('problem.html',{ 'message' : "Inactive" })
def incorrect(request):
return render_to_response('problem.html',{ 'message' : "Incorrect Username or Password" })
def iter_update(request):
if request.session['username'] != None :
return render_to_response('iter_update.html',{ 'user' : request.user },context_instance=RequestContext(request))
else :
return HttpResponseRedirect('/PDT/login_failed')
def Create_form(request):
if request.method == "POST":
form = f.ProjectForm(request.POST)
if(form.is_valid()):
print(request.POST['title'])
form.save()
message = 'success'
else:
message = 'fail'
return render_to_response('Create_form.html',
{'message': message,
'user': request.user,},
context_instance=RequestContext(request))
else:
return render_to_response('Create_form.html',
{'form': f.ProjectForm()},
context_instance=RequestContext(request))
Please use return render(request, template_name, context_dict) to render templates. Your peculiar way probably strips it of context.
Also, take a look at this decorator, and use it instead of your current if request.user != None : statements.
Your user is logged in, but because you are strangely rendering the Home and Index templates via template.render(None), there is no request or user context in your template. Instead, use the render shortcut which runs context processors.

Django serves zero byte response

This just happened to one of my sites and I have no idea what caused it.
This happens for any URL that is served by mod_wsgi for a particular application, which used to work fine.
Syntax errors in settings.py cause HTTP 500.
Syntax errors in urls.py don't influence anything—seems like this file is never loaded.
What is there to check?
The culprit was this line:
from django.contrib.auth.forms import AuthenticationForm
in middleware.py.
Moving the import into the function that uses AuthenticationForm solved the problem:
from django.http import HttpResponseRedirect
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login
#from django.contrib.auth.forms import AuthenticationForm <-- THE LINE WAS HERE
class LoginFormMiddleware(object):
def process_request(self, request):
if request.method == 'POST' and 'is_top_login_form' in request.POST:
from django.contrib.auth.forms import AuthenticationForm # <-- MOVED HERE
form = AuthenticationForm(data=request.POST)
is_valid = form.is_valid()
if is_valid:
login(request, form.get_user())
program = request.user.get_profile().first_intern.program
NavigationMiddleware.set_program(request, program)
return HttpResponseRedirect('%s?quick' % program.get_absolute_url())
else:
messages.error(request, request.POST['username'], extra_tags='login')
return HttpResponseRedirect(request.get_full_path())
I still have no idea why the code used to work, why it suddenly broke and why doing this solved the problem.
There has to be some magick in Python, after all.

Categories