I am trying to use the redirect() method redirect to my index view upon successful submission of the form found in my register view.
I have the following urls.py:
from django.contrib import admin
from django.urls import path
from users import views as usersViews
urlpatterns = [
path('admin/', admin.site.urls),
path('', usersViews.index, name = 'index'),
path('register/', usersViews.register, name = 'regsister'),
]
and the following views.py:
from django.shortcuts import render, redirect
from .forms import RegistrationForm
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse('signed up')
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save() # save form? to db?
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('email')
return redirect("index") #this statement is not working
else:
form = RegistrationForm()
return render(request, 'users/registration.html', {'registrationForm':form})
Upon submission of the form I am being redirected to "/register/index.html" and not "/" (index page). Can anyone help with this?
Try it with reverse:
from django.urls import reverse
return redirect(reverse('app_name:view_name'), {'registrationForm':form})
Related
as the title says, I want to create a functions that redirects the user to another app based on a random variable.
I created a function and gave a random value to a variable that calls the corresponding view of another app, but only the first value of the random range works fine, while the other get an error at the form validation.
contest.views:
from django.shortcuts import render
from django import forms
import random
from user.models import UserProfileInfo
from .problems.problem5_1contest.views import problem_one
from .problems.problem5_2contest.views import problem_two
from .problems.problem5_3contest.views import problem_three
def contestproblem1(request):
return problem_one(request)
def contestproblem2(request):
return problem_two(request)
def contestproblem3(request):
return problem_three(request)
def contest(request):
k = random.randint(1,3)
if(k == 1):
return contestproblem1(request)
if(k == 2):
return contestproblem2(request)
if(k == 3):
return contestproblem3(request)
problem5_1contest.views:
from django.shortcuts import render
from django import forms
from .forms import ProblemOneForm
from .models import ProblemOneContest
from user.models import UserProfileInfo
# Create your views here.
def wrong(request):
return render(request, 'problem5_1contest/wrong.html')
def correct(request):
return render(request, 'problem5_1contest/correct.html')
def problem_one(request):
form = ProblemOneForm()
form.fields['first'].widget = forms.HiddenInput()
form.fields['second'].widget = forms.HiddenInput()
form.fields['solution'].widget = forms.HiddenInput()
if request.method == 'POST':
form = ProblemOneForm(request.POST)
if form.is_valid():
form.save(commit=True)
if(int(form.cleaned_data['answer']) == int(form.cleaned_data['solution'])):
return render(request, 'problem5_1contest/correct.html')
else:
return render(request, 'problem5_1contest/wrong.html')
else:
print('ERROR')
return render(request, 'problem1/problem1.html',{ 'form':form } )
problem5_2contest.views:
from django.shortcuts import render
from django import forms
from .forms import ProblemTwoForm
from .models import ProblemTwoContest
from user.models import UserProfileInfo
# Create your views here.
def wrong(request):
return render(request, 'problem5_2contest/wrong.html')
def correct(request):
return render(request, 'problem5_2contest/correct.html')
def problem_two(request):
form = ProblemTwoForm()
form.fields['solution'].widget = forms.HiddenInput()
if request.method == 'POST':
form = ProblemTwoForm(request.POST)
if form.is_valid():
form.save(commit=True)
if(int(form.cleaned_data['answer']) == int(form.cleaned_data['solution'])):
return render(request, 'problem5_2contest/correct.html')
else:
return render(request, 'problem5_2contest/wrong.html')
else:
print('ERROR')
return render(request, 'problem2/problem2.html',{ 'form':form } )
problem5_3contest.views:
from django.shortcuts import render
from django import forms
from .forms import ProblemThreeForm
from .models import ProblemThreeContest
from user.models import UserProfileInfo
# Create your views here.
def wrong(request):
return render(request, 'problem5_3contest/wrong.html')
def correct(request):
return render(request, 'problem5_3contest/correct.html')
def problem_three(request):
form = ProblemThreeForm()
form.fields['first_digit_one'].widget = forms.HiddenInput()
form.fields['first_digit_two'].widget = forms.HiddenInput()
form.fields['second_digit_one'].widget = forms.HiddenInput()
form.fields['second_digit_two'].widget = forms.HiddenInput()
form.fields['second_digit_three'].widget = forms.HiddenInput()
form.fields['third_digit_one'].widget = forms.HiddenInput()
form.fields['third_digit_two'].widget = forms.HiddenInput()
form.fields['answer_digit_one'].widget = forms.HiddenInput()
form.fields['answer_digit_two'].widget = forms.HiddenInput()
form.fields['answer_digit_three'].widget = forms.HiddenInput()
if request.method == 'POST':
form = ProblemThreeForm(request.POST)
if form.is_valid():
form.save(commit=True)
if(int(form.cleaned_data['answer']) != int(form.cleaned_data['answer_digit_one']) + int(form.cleaned_data['answer_digit_two']) + int(form.cleaned_data['answer_digit_three'])):
return render(request, 'problem5_3contest/wrong.html')
else:
return render(request, 'problem5_3contest/correct.html')
else:
print('ERROR')
return render(request, 'problem3/problem3.html',{ 'form':form } )
urls.py:
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from user import views
from classes.views import class5, class6, class7, class8, classes
from contest.views import contest
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pwa.urls')),
path('register/',views.register,name='register'),
path('login/',views.user_login,name='login'),
path('logout/', views.user_logout, name='logout'),
path('home/', views.index, name='home'),
path('classes/', classes, name='classes'),
path('class5/', class5, name='class5'),
path('class6/', class6, name='class6'),
path('class7/', class7, name='class7'),
path('class8/', class8, name='class8'),
path('contest/', contest, name='contest'),
]
contest.urls.py:
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from contest.problems.problem5_1contest.views import problem_one as contestproblem1
from contest.problems.problem5_2contest.views import problem_two as contestproblem2
from contest.problems.problem5_3contest.views import problem_three as contestproblem3
urlpatterns = [
path('contest/class5/problemone', contestproblem1),
path('contest/class5/problemtwo', contestproblem2),
path('contest/class5/problemthree', contestproblem3),
]
You are not returning anything when the form is not valid.
def problem_one(request):
...
if form.is_valid():
...
else:
print('ERROR')
...
def problem_two(request):
...
if form.is_valid():
...
else:
print('ERROR')
...
def problem_three(request):
...
if form.is_valid():
...
else:
print('ERROR')
...
Instead of just printing ERROR, you should return something that can be like return render(request, 'wrong.html', {'error: 'The form is invalid'})
If you don't return anything, you will get this error, which I assume to be the one you are getting.
The view didn't return an HttpResponse object. It returned None instead
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'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'),
forms.py:
from django import forms
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.utils.text import capfirst
from .models import Classname, Sectionname, Teachername, Attendancename
class AuthenticationForm(forms.Form):
username = forms.CharField(max_length=20)
password = forms.CharField(widget=forms.PasswordInput)
error_messages = {
'invalid_login': ("Please enter a correct %(username)s and password."
"Note that both fields may be case-sensitive."),
'inactive': ("This account is inactive"),
}
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = authenticate(username=username, password=password)
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
)
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
def confirm_login_allowed(self, user):
if user.is_active:
login(self.user) /** It raises error here... **/
else:
raise forms.ValidationError(
self.error_messages['inactive'],
code='inactive',
)
def get_user_id(self):
if self.user_cache:
return self.user_cache.id
return None
def get_user(self):
return self.user_cache
views.py:
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.template.response import TemplateResponse
from django.views.generic import DeleteView, ListView
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import never_cache
from .models import Classname, Sectionname, Teachername, Attendancename
from .forms import ClassnameForm, SectionnameForm, TeachernameForm, AttendancenameForm, UserForm, PasswordChangeForm, AuthenticationForm
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse('student:mains'))
else:
print(form.errors)
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form},)
urls.py:
from django.conf.urls import url, patterns
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^password_change/$', auth_views.password_change, {'template_name': 'password_change_form.html', 'post_change_redirect': '/stu/password_change/done/'}, name="password_change"),
url(r'^password_change/done/$', auth_views.password_change_done, {'template_name': 'password_change_done.html'}, name="password_change_done"),
url(r'^restricted/', views.restricted, name='restricted'),
url(r'^mains/', views.mains, name = 'mains'),
]
I'm new to django authentication. I'm trying to make things as per the docs I have read. As your see above I've a 'user_login' view and 'AuthenticationForm' form.
I'm tring to login the user, but don't know the way how to do it? As I tried it in my view but didn't worked.
Then I tried it in my 'can_login_allowed' form's method but doesn't work.
Is there any other method to implement it?
Please! Can Anybody help me to fix it?
Thanks in Advance....
The login function takes request as first parameter. So you have write confirm_login_allowed like this:
def confirm_login_allowed(self, request):
if self.user_cache.is_active:
login(request,self.user_cache)
else:
raise forms.ValidationError(
self.error_messages['inactive'],
code='inactive',
)
And call it in the view like this
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
form.confirm_login_allowed(request)
return HttpResponseRedirect(reverse('student:mains'))
else:
....
Also don't call the confirm_login_allowed method from clean method because it does't have the request.
I'm new with django and I finished the 4 part tutorial on djangoproject.com
My problem is I want to put a login authentication on my polls app. I've use the decorator #login_required and it works properly but under my views.py I have only vote() method.
my views.py under "polls folder"
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from django.core.urlresolvers import reverse
from django.template import RequestContext
from polls.models import Poll, Choice
#login_required
#never_cache
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render_to_response('polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
}, context_instance=RequestContext(request))
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
return HttpResponse("You're voting on poll %s." % poll_id)
my urls.py under "polls folder"
from django.conf.urls.defaults import patterns, include, url
from django.views.generic import DetailView, ListView
from polls.models import Poll
urlpatterns = patterns('',
url(r'^$',
ListView.as_view(
queryset = Poll.objects.order_by('-pub_date')[:5],
context_object_name = 'latest_poll_list',
template_name = 'polls/index.html'), name='poll_lists'),
url(r'^(?P<pk>\d+)/$',
DetailView.as_view(
model = Poll,
template_name = 'polls/detail.html'), name='poll_details'),
url(r'^(?P<pk>\d+)/results/$',
DetailView.as_view(
model = Poll,
template_name = 'polls/results.html'), name = 'poll_results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
)
under my urls.py I have use generic views.
Problem is: how will I put login required under the "index" of the polls app. So that the user will login first before he/she can view the available polls.
Current is: I have used login required under my views.py and method vote(), It will require login after voting.
anyone can help me out?
Thanks,
Justin
1nd approach
In urls.py:
urlpatterns = patterns('',
url(r'^$',
login_required(ListView.as_view(
queryset = Poll.objects.order_by('-pub_date')[:5],
context_object_name = 'latest_poll_list',
template_name = 'polls/index.html'), name='poll_lists')),
)
2nd approach
In views.py:
class IndexView(ListView):
queryset = Poll.objects.order_by('-pub_date')[:5]
context_object_name = 'latest_poll_list'
template_name = 'polls/index.html'
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(IndexView, self).dispatch(request, *args, **kwargs)
then in urls.py
urlpatterns = patterns('',
url(r'^$',
IndexView.as_view(), name='poll_lists'),
)
Just providing a potentially more up-to-date answer,
I would move them to a views file and use the LoginRequiredMixin,
from django.views.generic import (
ListView,
DetailView
)
from django.contrib.auth.mixins import LoginRequiredMixin
class PollsListView(LoginRequiredMixin, ListView):
model = Poll
template_name = 'polls/index.html'