django logout() doesn't show template - python

Im using the Django function for loggin out and it doesnt show my template. the codes here:
Views.py
class Logout(View):
#import pdb; pdb.set_trace()
template_name = ['cost_control_app/logout.html']
def get(self, request, *args, **kwargs):
return render(request, self.template_name)
def logout_view(request):
logout(request)
print ("ya")
return render(request, self.template_name)
Urls.py
urlpatterns = patterns(
'',
url(r'^logout/$', views.Logout.as_view(), name = "logout"),
)
And the template:
logout.html
{% extends 'base_cost_control.html' %}
{% block contentsubbase %}
<head>
<body>
<div>
<h2> Logged out succefully </h2>
<br>
Iniciar sesión
</div>
</body>
</head>
{% endblock contentsubbase %}
in my main page im using an a href layer to point a that url :
Logout
but itś not working, it only redirects me to a complete empty page called logout and if i go back in my browser im still logged in.

define your template_name as string
template_name = "cost_control_app/logout.html"
Your template should be place in your project app_folder/templates/app_name
You can also define template_dirs in settings.py as follows
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
now create a folder in your project named templates and put your templates on each app in a folder correspond to app_name
Step 3 is not necessary and is just an alternate

Django 3.1: If you don't need to control the logout process, you can let Django's standard authentication system take care of it. No need to write a view or modify urlpatterns, simply direct the user to a template you specify in the GET request:
Logout now
This assumes you have the default settings ('django.contrib.auth' in installed apps, 'django.contrib.auth.middleware.AuthenticationMiddleware' in middleware, and 'django.contrib.auth.context_processors.auth' in template context processors) in settings.py.

Related

How to redirect to 'http://127.0.0.1:8000/profile/' instead of 'http://127.0.0.1:8000/accounts/login/?next=/profile/'

I'm trying to edit user profiles. The user edits a form on profile.html and when they submit it, they should be redirected back to profile.html (the same page). Even though I changed my LOGIN_REDIRECT_URL, I'm still redirecting to accounts/login (the default).
views.py
#login_required
def profile(request):
user = request.user
if request.method == "POST":
signupform = SignUpForm(data=request.POST, instance=request.user)
if signupform.is_valid():
signupform.save()
return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
return render(request, 'profile.html', "context stuff here")
settings.py
LOGIN_REDIRECT_URL = '/profile'
urls.py
url(r'^profile/$', views.profile, name='profile')
How can I successfully redirect to profile.html?
Try this replacing APPNAME with your app's name (same as the app name you declared in INSTALLED APPS section in settings.py) in the code below
return HttpResponseRedirect(reverse('APPNAME:profile'))
and don't forget to import at the top of your page
from django.urls import reverse
You use #login_required decorator but you are not logged in. So that it redirects you to the login page. If you login then it redirect to /profile.
You can do this,
#login_required
#...
if signupform.is_valid():
signupform.save()
return redirect('profile') # or 'app_name:profile' if you have app_name before your urlpatterns.
Your login_required will redirect you to settings.LOGIN_URL
So in your settings add LOGIN_URL = '/login/'
If the user is logged in the views will work perfectly.
Addition to that, (template level)
You can also check authentication in html,
{% if user.is_authenticated %}
#html
{% else %}
show something
{% endif %}

Django 1.10: Setting admin.site.site_header and using default admin login view

I'm trying to (at the project level):
Use the default admin view (auth.views.login) as my login view
Set the admin.site.site_header within ulrs.py so that it appears on the both the login and admin pages
First, doing this does update the site_header on the admin page...
# urls.py
admin.site.site_header = "my header name"
urlpatterns = [
url(r'^admin/?', admin.site.urls),
url(r'^', include('django.contrib.auth.urls')),
...
]
From here it would appear I should be able to either do this:
# registration/login.html
{% extends "admin/login.html" %}
Or this (copy/paste from django/admin/templates/login.html):
# registration/login.html
{% extends "admin/base_site.html" %}
{% load i18n static %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/login.css" %}" />
{{ form.media }}
{% endblock %}
...
Neither employ the header with "my header name" like the admin view does.
Why doesn't my registration/login.html get the admin.site.site_header I'm setting in urls.py?
Thanks.
Update:
I see that auth/view.py doesn't have site_header in its context by default:
# auth/view.py
def login(...
current_site = get_current_site(request)
context = {
'form': form,
redirect_field_name: redirect_to,
'site': current_site,
'site_name': current_site.name,
}
...
And that admin/sites.py is responsible for defining AdminSite which sets site_header for the admin site
class AdminSite(object):
...
def each_context(self, request):
"""
Returns a dictionary of variables to put in the template context for
*every* page in the admin site.
For sites running on a subpath, use the SCRIPT_NAME value if site_url
hasn't been customized.
"""
script_name = request.META['SCRIPT_NAME']
site_url = script_name if self.site_url == '/' and script_name else self.site_url
return {
'site_title': self.site_title,
'site_header': self.site_header,
'site_url': site_url,
'has_permission': self.has_permission(request),
'available_apps': self.get_app_list(request),
}
...
I see how I could create my own base_site.html (hardcoding {{ "my header name }}) to use in the copy/pasted login.html above, but that seems messy. I'd like to set this variable in one place and use as much of admin directly as possible.
My high-level interest is to basically piggy-back the admin app for regular user accounts. Am I going about this wrong?
My high-level interest is to basically piggy-back the admin app for
regular user accounts. Am I going about this wrong?
Unfortunately, yes, you are.
https://docs.djangoproject.com/en/1.10/intro/tutorial02/
The admin isn’t intended to be used by site visitors. It’s for site
managers.
It's so easy to add an authentication system using one of the many tried and tested registrion/auth packages available (example django-allauth) that trying to re-purpose django admin as a user level app is wastefull and not very secure either.

python Django repeat url many times

I'm a starter of Django1.10. I just started play around with it. I am trying to show an image on website.
This is myproject/settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
and myproject/urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^poster/', include('poster.urls')),
url(r'^admin/', admin.site.urls ),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
myproject/app/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Info
# give a set of summary of items
def index(request):
latest_item_list = Info.objects.all()
context = {'latest_item_list': latest_item_list}
return render(request, 'poster/index.html', context)
def detail(request, item_id):
return HttpResponse("This function will return detail info for items %s" % item_id)
myproject/app/models.py
from django.db import models
class Info(models.Model):
def __str__(self):
return self.info_text
info_text = models.CharField(max_length=50)
pub_date = models.DateTimeField('date published')
info_image = models.ImageField(upload_to='images/%Y%m/%d')
myproject/app/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# ex:/poster
url(r'^$', views.index, name='index'),
# ex: /poster/5
url(r'^(?P<item_id>[0-9]+)/$', views.detail, name = 'detail'),
]
myproject/app/templates/app/index.html
{% if latest_item_list %}
<ul>
{% for item in latest_item_list %}
{{forloop.counter}}.{{ item.info_text }}
{% endfor %}
</ul>
{% else %}
<p>No poster are available.</p>
{% endif %}
If I run python manage.py runserver, and go http://127.0.0.1:8000/poster/. I can see one object I created before, when I click it, the url it points to get repeated many times
I believe there is something wrong in the url.py, but I am not sure. Can someone help?
First of all I think you are missing a forwardshals in your models.py on line :
info_image = models.ImageField(upload_to='images/%Y%m/%d')
Unless it's your intention, I think it should be like this:
info_image = models.ImageField(upload_to='images/%Y/%m/%d')
^
Next thing is that you are not providing the right url for href attribute in the <a> tag of your index.html template.
{{forloop.counter}}.{{ item.info_text }}
This line will point to the image itself. So you can use it example in the <image src="{{ item.info_image.url }}" /> but not in a link tag. So I guess this is what you were looking for.
To point to your detail view of specific image you would want to ideally create get_absolute_url method on your Info model class.
Model.get_absolute_url()
Define a get_absolute_url() method to tell Django how to calculate the canonical URL for an object. To callers, this method should appear to return a string that can be used to refer to the object over HTTP.
For example:
# models.py
class Info(models.Model):
...
info_image = models.ImageField(upload_to='images/%Y%m/%d')
def get_absolute_url(self):
return reverse('detail',
args=[self.id])
Then you could use that in your template like this:
{{forloop.counter}}.{{ item.info_text }}
and display your image, wherever you want, using:
<image src="{{ item.info_image.url }}" />
Have you checked how the URL looks in the generated HTML code? E.g. does the URL look correct when the HTML is loaded, and when you click it, it starts repeating it?

Redirecting the django built-in logout view after successfull logout

I am using django to build a login and logout page , below are my codes
urls.py
from django.conf.urls.defaults import *
from django.conf import settings
from django.core.urlresolvers import reverse
urlpatterns = patterns('',
url(r'^$', 'learn_django.views.home_page'),
url(r'^login/$', 'learn_django.views.login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'template_name': 'logout.html'}),
)
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth import authenticate, login as main_login, logout as main_logout
def home_page(request):
return render_to_response("home_page.html")
def login(request):
.....
.....
return render_to_response("login.html")
logout.html
{% extends 'base.html' %}
{% block title %}Logout Page{% endblock %}
{% block body %}
<div>
<p style='color:#092E20;font-size:25px;font-weight:bold;padding-top:20px;padding-left:15px;'>
You have been successfully logged out......
</p>
<p>Redirecting to login page.....</p>
</div>
{% endblock %}
So in the above codes, i will have a login url which will display a login form and redirects to another url after successfull login which is working fine
Also i will have a logout url for which i am using the django built-in logout view , by supplying it a template logout.html which is also working fine and displaying the above html code successfully when i clicked the logout url
So now i want to redirect to the login page after displaying the logout page(after some time period....). I mean first the logout view should render the logout.html code and next should redirect to login page ....
Can anyone please let me know how to redirect to login html page after rendering logout.html as above ......
You can use setTimeout() function to redirect to another page after specified amount of time.
{% block extrahead %}{{ block.super }}
<script type="text/javascript">
setTimeout(function() {
window.location.href = "/login/";
}, 2000);
</script>
{% endblock %}
Add this after {% block title %}Logout Page{% endblock %}.
Put this in your logout.html
<script>
function redirect(){
window.location.href = "supply_url_here";
}
setTimeout(redirect, 2000); //2000 is equivalent to 2 seconds
</script>
as an alternative to javascript redirect, you can also do HTTP Refresh Header:
# in views.py
from django.contrib.auth import logout as main_logout
def logout(*args, **kwargs):
resp = main_logout(*args, **kwargs)
resp['Refresh'] = '3;URL=/account/login/' # redirects after 3 seconds to /account/login
return resp
modify your urls.py as appropriate.
The advantage of this is that it will work even when javascript is disabled. The disadvantage is that it is only standard header by de facto, it's not specified in the HTTP standard.

Adding redirect for Django admin detail view

I'm trying to set up a redirect so that when Django CMS users are accessing a detail view for one of the admin models, they get redirected to the listing view.
I was able to successfully override the detail view within the admin.py file:
class MyAdmin(MyModelAdmin):
change_form_template = u"admin/myadmin/change_form_content.html"
within the template, I'm creating a redirect back to the list view:
{% block content %}
<meta http-equiv="REFRESH" content="0;url=/myadmin/">
{% endblock %}
This works fine, but it's messy. How can I move the redirect to the admin.py file instead?
You can directly override the method responsible for displaying that view: changeform_view.
class MyAdmin(MyModelAdmin):
def changeform_view(self, *args, **kwargs):
return redirect('/admin/')

Categories