I'm trying to implement and Login and Registration system for my Django project. I'm currently getting this error...
NoReverseMatch at /
Reverse for 'register' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Here is some of my code so hopefully you can help....
Urls.py
urlpatterns = [
url(r'^stocks/$', StockView.as_view(), name='stocks'),
url(r'^$', IndexView.as_view(), name="index"),
#url(r'^data/$', DataView.as_view(), name='data'),
url(r'^quizzes/$', DefView.as_view(), name='quizzes'),
url(r'^tickers/$', DefView.as_view(), name='ticker'),
url(r'^accounts/login/$', 'stockmarket.views.login'),
url(r'^accounts/auth/$', 'stockmarket.views.auth_view'),
url(r'^accounts/logout/$', 'stockmarket.views.logout'),
url(r'^accounts/loggedin/$', 'stockmarket.views.loggedin'),
url(r'^accounts/invalid/$', 'stockmarket.views.invalid_login'),
url(r'^accounts/register/$', 'stockmarket.views.register_user'),
url(r'^accounts/register_success/$', 'stockmarket.views.register_success'),
]
Views.py
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from django.contrib.auth.forms import UserCreationForm
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = reqruest.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 HttpResponseRedirect('/accounts/loggedin')
else:
return HttpResponseRedirect('/accounts/invalid')
def loggedin(request):
return render_to_response('loggedin.html', {'full_name': request.user.username})
def invalid_login(request):
return render_to_response('invalid_login.html')
def logout(request):
auth.logout(request)
return render_to_response('logout.html')
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
return render_to_response('register.html', args)
def register_success(request):
return render_to_response('register_success.html')
Thanks for your help.
Somewhere in your project you used django's urlresolvers to return url for using a named url called 'register'.
After seeing your urls.py, it appears that you don't have any url with register named assigned to it. You should named it where it is appropriate.. something like this:
url(r'^accounts/register/$', 'stockmarket.views.register_user', name='register'),
Related
Hi i know there is many of these asking about routing from a veiw to a new app in django. I have looked at a lot of them. And figured out to use app_name = 'name' and to use named routes for my html templates makes everything easier for sure. When i try to use a app_name:named-route i get this :
ValueError at /recipedashboard
The view recipeApp.views.dashboard didn't return an HttpResponse object. It returned None instead.
I have gotten the name_app:named-route to send me to the second app, but how do i pass the session to the new app?
userApp veiws:
from django.shortcuts import render, redirect
from django.contrib import messages
from .models import User as LoggedUser
# Create your views here.
def index(request):
return render(request, 'index.html')
def register(request):
if request.method == "GET":
return redirect('/')
errors = LoggedUser.objects.validate(request.POST)
if len(errors) > 0:
for er in errors.values():
messages.error(request, er)
return redirect('/')
else:
new_user = LoggedUser.objects.register(request.POST)
request.session['user_id'] = new_user.id
messages.success(request, "You have successfully registered")
return redirect('/success')
def login(request):
if request.method == "GET":
return redirect('/')
if not LoggedUser.objects.authenticate(request.POST['email'],
request.POST['password']):
messages.error(request, "Invalid Email/Password")
return redirect('/')
user = LoggedUser.objects.get(email=request.POST['email'])
request.session['user_id'] = user.id
messages.success(request, "You have successfully logged in!")
return redirect('/success')
def logout(request):
request.session.clear()
return redirect('/')
def success(request):
if 'user_id' not in request.session:
return redirect('/')
context = {
'user' : LoggedUser.objects.get(id=request.session['user_id'])
}
return redirect("recipe:recipe-dashboard")
recipeApp urls.py:
from django.urls import path
from . import views as recipeViews
app_name ='recipe'
urlpatterns = [
path('dashboard', recipeViews.dashboard, name= "recipe-dashboard" )
]
recipeApp.Views :
from django.shortcuts import render, redirect
from userApp.models import User as LoggedUser
# Create your views here.
def dashboard(request):
if 'user_id' not in request.session:
return redirect('/')
user = LoggedUser.objects.get(id=request.session['user_id'])
context = {
'user' : user
}
render (request, 'dashboard.html', context)
Your dashboard view is not returning anything.
You need to return the results of render. Like
from django.shortcuts import render, redirect
from userApp.models import User as LoggedUser
# Create your views here.
def dashboard(request):
if 'user_id' not in request.session:
return redirect('/')
user = LoggedUser.objects.get(id=request.session['user_id'])
context = {
'user' : user
}
return render (request, 'dashboard.html', context)
There is no need to deal with passing a session. The framework will handle that for you if the apps are all under the same project.
Trying to register user in Django. it keep giving me HttpResponse error
signup.html templates location is : templates/registration/signup.html
Here's what i tried:
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
username = forms.CharField(max_length=50)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2', )
views.py
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth.decorators import login_required
from .forms import SignUpForm
#login_required
def home(request):
return render(request, 'registration/home.html')
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(email= email, password= raw_password)
login(request, user)
return redirect('registration/home')
else:
form = SignUpForm()
return render(request, 'registration/signup.html', {'form': form})
I did tried replacing redirect with HttpResponseRedirect but it did't work
Account urls.py
from django.contrib.auth import views as auth_views
from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns = [
path("login/", auth_views.LoginView.as_view(template_name = "registration/login.html"), name='login'),
path("logout/", auth_views.LogoutView.as_view(), name='logout'),
path('home/', views.home, name='home'),
url('signup/', views.signup, name='signup'),
]
Error
ValueError at /accounts/signup/
The view account.views.signup didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/signup/
Django Version: 3.0.3
Exception Type: ValueError
Exception Value:
The view account.views.signup didn't return an HttpResponse object. It returned None instead.
You need to support GET method e.g.:
def signup(request):
form = SignUpForm()
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(email= email, password= raw_password)
login(request, user)
return redirect('registration/home')
return render(request, 'registration/signup.html', {'form': form})
I have a login-page set as my homepage, localhost/mysite. I can login and successfully be redirected to localhost/mysite/mainpage.
The issue is that I can bypass the login simply by just entering the path in the URL, for example; I navigate to the homepage where the login-form is, then I just add /mainpage to localhost/mysite/ which successfully loads localhost/mysite/mainpage.
As you could imagine, this is not great. Does anyone know what I did wrong here?
My view
def index(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, "OK")
return redirect('/mysite/mainpage')
else:
messages.error(request, "NOT OK")
form = AuthenticationForm()
return render(request, 'mysite/login.html', {"form":form})
My urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^mainpage/$', views.main),
]
You can use the #login_required decorator [Django-doc] on your main view. This will redirect to the path set by the LOGIN_URL setting [Django-doc] to log in the user:
# app/views.py
from django.contrib.auth.decorators import login_required
def index(request):
# …
#login_required
def main(request):
# …
and in the settings.py:
# settings.py
# …
LOGIN_URL = 'index'
# …
EDIT: You can omit the ?next= query parameter, by setting the redirect_field_name=… parameter to None:
#login_required(redirect_field_name=None)
def main(request):
# …
I am trying to create a login and logout page for my sample project and have coded all logic up. The tutorial I was following used the following code
from django.shortcuts import render
from basic_app.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.decoraters import login_required
# Create your views here.
def index(request):
return render(request,'basic_app/index.html')
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'basic_app/registration.html',
{'user_form':user_form,
'registered':registered })
#login_required
def special(request):
return HttpResponse("You are logged in!")
#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:
login(request,user)
return HttpResponseRedirect(reverse('index'))
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 supplied")
else:
return render(request,'basic_app/login.html',{})
The error I am getting is this
from django.contrib.auth.decoraters import login_required
ModuleNotFoundError: No module named 'django.contrib.auth.decoraters'
You make spelling mistakes while importing the decorators:
Change:
from django.contrib.auth.decoraters import login_required
To:
from django.contrib.auth.decorators import login_required
The login function is not working , after i call login , authenticated is set 'true' but after i redirect to 'main' view authenticated is set 'false'. How to keep the user logged in even after redirection?
class LoginForm(forms.Form):
user = forms.CharField()
password = forms.CharField()
def login(self):
try:
cred = users.objects.get(username = user)
if password==cred.password):
return (True, cred)
return (False, 'Invalid Password.')
except:
return (False, 'Not exist')
from django.contrib.auth import login as auth_login
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
valid, message = form.login()
if valid:
auth_login(request, message)
print(request.user.is_authenticated)
# this is not working
return redirect(main)
else:
return redirect(login)
form = LoginForm()
args = {'form': form}
return render(request, 'accounts/login.html', args)
def main(request):
print(request.user.is_authenticated)
You shouldn't write check your user credentials in form class. Do it in your login view. Example:
# views.py
from django.contrib.auth import authenticate, login
from django.urls import reverse
from django.shortcuts import redirect, render
def login_view(request): #changed_the name shouldn't be login
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username, password)
if user:
login(user)
return redirect(reverse("main"))
else:
return redirect(reverse("login"))
form = LoginForm()
args = {"form": form}
return render(request, 'accounts/login.html', args)
# urls.py
urlpatterns = [
path("login/", views.login_view, name="login"), # <-- really important
path("main/", views.main_view, name="main")
]
To summarize - to redirect to another page use redirect function. If you set name parameter in url of you view, you can reffer to this view using reverse. Also don't reinvent the wheel and write your own authentication function. Django provides: authenticate(username, password) and login(user) function.