i am trying to send a message to the user of my site when they register i used django message import but i did not work
here is my views.py code
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .models import cooking
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
# Create your views here.
def homepage(request):
return render(request=request,template_name='main/home.html',context={"cooking": cooking.objects.all})
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.succees(request, f"new account created: {username}")#error on this line
login(request, user)
return redirect("main:homepage")
else:
for msg in form.error_messages:
messages.error(request, form.error_messages[msg])
form = UserCreationForm
return render(request,"main/register.html",context={"form":form })
f-strings have been introduced in Python 3.6, you're probably using a previous version.
If you really wanted to use them you could install future-fstrings but I'm not sure it's worth.
A probably better solution would be to either upgrade Python to a version greather or equal to 3.6 or use one of the alternative formatting options:
"new account created: {}".format(username)
"new account created: %s" % username
Related
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.
I am using the latest version of django and python 3, When I log in I get the below error message.
django login() takes 1 positional argument but 2 were given
Please find the code for my login view below.
from django.shortcuts import render, get_object_or_404,redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from authentication.forms import LoginForm, ForgottenPasswordForm, ResetPasswordForm
from authentication.functions import send_user_reset_password_link, resend_password_reset_link
from authentication.models import ResetPassword
# Create your views here.
def login(request):
error_message = None
heading = 'Login Form'
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
remember_me = form.cleaned_data['remember_me']
user = authenticate(request,username=username, password=password)
if not request.POST.get('remember_me', None):
#request.session.set_expiry(0)
if user is not None:
login(request, user)
return redirect('property_index',user.id)
# A backend authenticated the credentials
else:
error_message = 'No login credentials found'
# No backend authenticated the credentials
form = LoginForm()
return render(request,'authentication/forms/login.html',{
'form':form,
'error_message':error_message,
'heading':heading
})
The trouble is: you override the original django login function. So you should change import.
from django.contrib.auth import authenticate, login as dj_login
# ^^^^^^^^
and use
dj_login(request, user)
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))
I'm trying to set up a custom user model, but I'm getting the following error on my login page when trying to authenticate a member
ImportError at /members/login/
cannot import name check_password
I know the check_password method exists, but not sure what I'm missing. What am I doing wring when trying to import it?
/members/backends.py
from django.conf import settings
# failing to import check_password here
from django.contrib.auth.models import check_password
from members.models import Member
class EmailAuthBackend(object):
"""Custom authentication backend the allows users to log in using
their email address."""
def authenticate(self, email=None, password=None):
"""Authentication method."""
try:
member = Member.objects.get(email=email)
if member.check_password(password):
return member
except Member.DoesNotExist:
return None
mebers/views.py
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib.auth import login as django_login, authenticate, logout as django_logout
from members.forms.login import LoginForm
from members.forms.register import RegisterForm
def login(request):
"""Login view."""
if request.method != 'POST':
form = LoginForm()
form = LoginForm(data=request.POST)
if form.is_valid():
member = authenticate(email=request.POST.get('email'),
password=request.POST.get('password1'))
if member is not None:
if member.is_active:
django_login(request, member)
return redirect('/')
else:
form = LoginForm()
return render_to_response('members/login.html', {
'form': form
}, context_instance=RequestContext(request))
Try this:
from django.contrib.auth.hashers import check_password
You seem a bit confused about functions and methods. check_password is a method on the auth.models.User class; you can't just import it on its own. And you don't use it anyway; you call the - completely separate - check_password method on your own Member class; there's no need to import anything else there.
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.