I'm trying to create a logout page for django.
This is the views.py file:
def index(request):
if not request.user.is_authenticated():
return redirect('webapp/login.html')
else:
result = Hello_World.delay()
somethingDownByCelery = result.get(timeout=2)
context = {'somethingDownByCelery': somethingDownByCelery, 'userName': request.user.username}
return render(request, 'webapp/index.html', context)
def loginUser(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('webapp/index.html')
else:
return redirect('webapp/disabled.html')
else:
condition = "Invalid Login"
context = {'condition', condition}
return render(request, 'webapp/index.html', context)
def logoutUser(request):
logout(request)
return redirect('webapp/index.html')
This is the index page after the logout is initiated.
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'WebApp/style.css' %}"/>
Hello World, this will call celery!
<html>
<br>
</html>
{{ somethingDownByCelery }}
<html>
<br>
<br>
</html>
Hello! {{ userName }}
<html>
<br>
<br>
</html>
<form action="{% url 'WebApp:logout'%}" method="post">
{% csrf_token %}
<p> Logout </p>
<input type="submit" value="Submit">
</form>
What should happen is that the user would logout, and get redirected to the index page, whereas since the user is not logged in, it will redirect the user to a login page.
However, it only shows me: The view django.contrib.auth.logout didn't return an HttpResponse object.
This is the project root urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from WebApp import views
from StripCal import views
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Dashboard_Web.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^webapp/', include('WebApp.urls', namespace="WebApp")),
)
This is the app's urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from WebApp import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^login', views.login, name='login'),
url(r'^logout', views.logout, name='logout'),
)
try this:
from django.shortcuts import HttpResponseRedirect
def logoutUser(request):
logout(request)
return HttpResponseRedirect('/loginpage/')
instead of webapp/index.html, you should give the URL of your login page like /loginpage/ inside HttpResponseRedirect
Instead of writing your own, use Djangos builtin logout view for this.
#urls.py
from django.contrib.auth.views import logout
url(r'^sign-out/$', logout, {'template_name': 'index.html', 'next_page': '/'}, name='sign-out'),
Docs are found here and now you can link to this without the use of a form and Django will take care of doing the redirection for you.
I know that this is a old post, but no answer addressed what went wrong in the code so here it is.
In the webapp urls.py file view must be pointing to logoutUser view and not logout view.
and similarly with the login view
from django.contrib import admin
from WebApp import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^login', views.loginUser, name='login'),
url(r'^logout', views.logoutUser, name='logout'),
)
Now the url function is taking the intended view method as an argument
First things first.
Your function should look similar to this one:
def logout_view(request):
logout(request)
return redirect('/login')
To use logout, you have to import logout like this:
from django.contrib.auth import logout
If you are redirecting user on the basis of User.is_authenticated, it would never redirect because if the user is not logged in, an anonymous user it created.
You can do something like ths:
def home(request):
if request.user.is_anonymous == True:
return redirect('/login')
else:
return render(request,"index.html",{'nav':request.user})
Related
I was doing some How-To tutorials about Django Forms.
But it will not display anything for me. Any ideas why? Picture below illustrates my problem.
This is my Login -> index.html
<body>
<div class="gradient-border" id="box">
<h2>Log In</h2>
<form action = "" method = "post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit">
</form>
</div>
</body>
this is forms.py
class InputForm(forms.Form):
first_name = forms.CharField(max_length = 200)
last_name = forms.CharField(max_length = 200)
password = forms.CharField(widget = forms.PasswordInput())
this is views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import InputForm
def index(request):
return render(request, 'login/index.html')
def home_view(request):
context ={}
context['form']= InputForm()
return render(request, "index.html", context)
def main(request):
return render(request, 'login/main.html')
this is urls.py
from django.contrib import admin
from django.urls import path, include
from login.views import index, main
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', index),
path('main/', main),
path('accounts/', include('django.contrib.auth.urls')),
]
Login Page
You are not passing the form context for the login route. In your index function, you don't have any context, and you put the form in home_view function which is not the view function being called by the /login route.
I'm having trouble getting my register application in Django to work. I am using the built-in UserCreationForm form. I can go to the URL and the form shows up but when I put info into the fields and click the submit button nothing happens. It should pop up an error screen saying "missing the csrf_field" (I know this because I'm following TechWithTim's tutorial and that's what happens to him). But when I click the "Register" button nothing happens.
views.py:
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def register(response):
form = UserCreationForm()
return render(response, "register/register.html", {"form":form})
register.html:
{% extends "main/base.html" %}
{% block title %}Create an Account{% endblock %}
{% block content %}
<form method="POST" class="form-group">
{{form}}
<button type="submit" class="btn btn-success">Register</button>
</form>
{% endblock %}
urls.py:
from django.contrib import admin
from django.urls import path, include
from register import views as v
urlpatterns = [
path('', include("main.urls")),
path("register/", v.register, name="register"),
path('admin/', admin.site.urls),
]
main/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("<int:id>", views.index, name='index'),
path("", views.home, name='home'),
path("create/", views.create, name='create'),
]
I added the application to my settings.py file as well.
This is my first question on here and I tried to format it properly so sorry if I didn't
In order for Django to recieve the data the user entered in the form, you need to pass the request's POST data to the form, if it exists. That would look like this:
form = UserCreationForm(response.POST)
But note that response.POST will not exist if it's not a POST request. (For example, if the user is viewing the form for the first time.) The Django docs have an example of how to process form data.
Alternatively, you can look at the tutorial you're using, which has an example of how to get the POST data out of the form:
# views.py
from django.shortcuts import render, redirect
from .forms import RegisterForm
# Create your views here.
def register(response):
if response.method == "POST":
form = RegisterForm(response.POST)
if form.is_valid():
form.save()
return redirect("/home")
else:
form = RegisterForm()
return render(response, "register/register.html", {"form":form})
(Source.)
When I go to "http://127.0.0.1:8000/restaurant/sign-in/" I get page not found (404) error. But I can go to "http://127.0.0.1:8000/restaurant/$" to access the home page.
I also tried "http://127.0.0.1:8000/restaurant/sign-in/$" but this also gives me error (init() takes 1 positional argument but 2 were given).
My urls.py is
from django.contrib import admin
from django.urls import path
from foodtaskerapp import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('restaurant/sign-in/$', auth_views.LoginView,
{'template_name': 'restaurant/sign_in.html'},
name='restaurant-sign-in'),
path('restaurant/sign-out', auth_views.LogoutView,
{'next_page': '/'},
name='restaurant-sign-out'),
path('restaurant/$', views.restaurant_home, name='restaurant-
home'),
]
And my views.py is
from django.shortcuts import render, redirect
def home(request):
return redirect(restaurant_home)
def restaurant_home(request):
return render(request, 'restaurant/home.html', {})
here is the screenshot of the error
I also have
<body>
<form method="POST">
{% csrf_token %}
{{ form }}
<button type="submit">Sign In</button>
</form>
</body>
in sign_in.html but the form don't show up, only Sign In is shown.
only sign is shown but not the form
the syntax for the function you are using has changed in the latest version of django, which is why you got that error (the code you are sharing is in a tutorial made by code4startups which uses an older version of django).
You should modify your path command to:
path('restaurant/sign-in/', auth_views.LoginView.as_view(
template_name='restaurant/sign_in.html'),
name='restaurant-sign-in'),
You have no corresponding function in views.py:
auth_views.LoginView
Also, i guess, you neither have 'restaurant/sign_in.html', so it doesn't redirect to the page.
Add this in views.py:
def restaurant_signIn(request):
return render(request, 'restaurant/sign_in.html')
And corresponding HTML page name: 'sign_in.html',in restaurant directory:
<p>SigninWorks</p>
Your urls.py must look like:
from django.contrib import admin
from django.urls import path
from foodtaskerapp import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('restaurant/sign-in/', views.restaurant_signIn,
name='restaurant-sign-in'),
path('restaurant/$', views.restaurant_home, name='restaurant-
home'),
]
After log out user in my django web app, the redirected homepage still displays the "Log Out" button instead of the "Sign in with Facebook". In the following code, I follow the django documentation to logout the user and redirect the page to homepage which is the base.html. It seems that my web app still has user.is_authenticated as True after log out? What am I missing?
I cannot find any useful hint online. Any comment is much appreciated.
Here is part of my template html
<div class="navbar-form navbar-right">
{% if user.is_authenticated %}
<a id="logout" href="/accounts/logout" class="btn btn-success">Logout</a>
{% else %}
<a id="facebook_login" href="/accounts/facebook/login" class="btn btn-success">Sign in with Facebook</a>
{% endif %}
</div>
Here is my urls.py
url(r'^$', 'homepage.views.home', name='home'),
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/logout/$', 'homepage.views.logout', name='logout'),
Here is my homepage/views.py
# Create your views here.
def home(request):
return render(request, "base.html", {})
# ensure only logged in users can access the view.
#login_required
def logout(request):
logout(request)
# Take the user back to the homepage.
return redirect('home')
There are 2 things here:
You need to reorder the URLs
from:
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/logout/$', 'homepage.views.logout', name='logout'),
to
url(r'^accounts/logout/$', 'homepage.views.logout', name='logout'),
url(r'^accounts/', include('allauth.urls')),
This way, your logout takes precedence over the allauth's logout URL pattern
You should be aliasing the imported logout, or rename your logout to something different.
Example:
from django.contrib.auth import logout as auth_logout
and then
def logout(request):
auth_logout(request)
....
I'm making a simple login app in django 1.6 (and python 2.7) and I get an error at the beggining that is not letting me continue.
This is the site's url.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
import login
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', include('login.urls', namespace='login')),
url(r'^admin/', include(admin.site.urls)),
)
And this is login/urls.py:
from django.conf.urls import patterns, url
from login import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^auth/', views.auth, name='auth'),
)
This is login/views,py
from django.shortcuts import render
from django.contrib.auth import authenticate
def auth(request):
user = authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
# the password verified for the user
if user.is_active:
msg = "User is valid, active and authenticated"
else:
msg = "The password is valid, but the account has been disabled!"
else:
# the authentication system was unable to verify the username and password
msg = "The username and password were incorrect."
return render(request, 'login/authenticate.html', {'MESSAGE': msg})
def index(request):
return render(request, 'login/login_form.html')
I have a form that has this as action:
{% url 'login:auth' %}
And that's where the problem is, when I try to load the page, I get:
Reverse for 'auth' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'$auth/']
But if I set the url pattern to
url(r'', views.auth, name='auth')
it works fine, only it sets the action as '/'.
I've been looking all around for an answer and I don't understand why it doesn't work.
I tried changing the login url pattern to url(r'^login/$', include('login.urls', namespace='login')), and it didn't change anything.
The problem is in the way you include the auth URLs in the main one.
Because you use both ^ and $, only the empty string matches. Drop the $.
I had html anchor tag: <a href="{% url 'url-name' url=someUUID %}">
in my urls.py
...
path('some_name/<slug:slug>/', views.someDetailView.as_view(), name='url-name'),
...
Solution for this:
This: <a href="{% url 'url-name' someUUID %}">
Or this: <a href="{% url 'url-name' slug=someUUID %}">
not: <a href="{% url 'url-name' url=someUUID %}">
DetailView uses slug_field = 'someUUIDField'
For some reason I wrote url instead of slug. Now it works.
Maybe you wrote wrong also, make sure you use slug=, if you use <slug:slug>.