I am trying to handle a 404 http response error on the site. I want my 404.html content to be displayed, but for some reason when I run my local host I do get the response displayed, but my site doesn't look the same as in my contents aren't being displayed as they should. I don't know why this is happening, but I want to make sure I am properly calling in my handler. Any suggestions would be appreciated.
My views.py
def handler404(request, exception):
return render(request, 'webpage/404.html')
My 404.html
{% extends "webpage/base.html" %}
{% block content %}
{% load static %}
<h1>404 Error</h1>
{% endblock %}
My Url.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('webpage.urls')),
]
handler404 = views.handler404
Here is the ref to handle the custom error page: https://docs.djangoproject.com/en/3.0/topics/http/views/#customizing-error-views
In the main py:
handler404 = 'app_name.views.handler404'
In the views add :
def handler404(request, exception):
return render(request, "webpage/404.html", {})
Related
Is it possible to render an HTML page without having a view model in Django if a page is going to display only static HTML?
Basically, I want to delete an issue from a webpage and then show a 'successfully deleted' static HTML page after deleting.
But I got blew error, anyone could help?
NoReverseMatch at /project/1/issue/14/delete_issue/
Reverse for 'nice_delete.html' not found. 'nice_delete.html' is not a valid view function or pattern name.
view.py
def delete_issue(request,project_id,issue_id):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
issue = get_object_or_404(Issue,id=issue_id)
issue.delete()
return redirect(reverse('project:issue_tracker:nice_delete.html'))
urls.py
urlpatterns =[
path('',views.list_of_issue,name='list_of_issue'),
path('<int:issue_id>/',views.issue_detail,name='issue_detail'),
path('<int:issue_id>/comment',views.add_comment,name='add_comment'),
path('new_issue/',views.new_issue,name='new_issue'),
path('<int:issue_id>/edit_issue/',views.edit_issue,name='edit_issue'),
path('<int:issue_id>/delete_issue/',views.delete_issue,name='delete_issue'),
]
nice_delete.html
{% extends 'base.html' %}
{% block content %}
<p>Successfully delete this issue</p>
{% endblock %}
You can use TemplateView for this. Just add to your urlpattern:
from django.views.generic import TemplateView
urlpatterns =[
path('',views.list_of_issue,name='list_of_issue'),
path('<int:issue_id>/',views.issue_detail,name='issue_detail'),
path('<int:issue_id>/comment',views.add_comment,name='add_comment'),
path('new_issue/',views.new_issue,name='new_issue'),
path('<int:issue_id>/edit_issue/',views.edit_issue,name='edit_issue'),
path('<int:issue_id>/delete_issue/',views.delete_issue,name='delete_issue'),
path('deleted/', TemplateView.as_view(template_name="nice_delete.html"), name='success_deletion'),
]
And use success_deletion url in delete_issue view for redirection:
def delete_issue(request,project_id,issue_id):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
issue = get_object_or_404(Issue,id=issue_id)
issue.delete()
return redirect('success_deletion')
I am new to Django and have gone through the first Django App tutorial.I understand the separate bits but am not able to form a complete solution.
My requirement is to add a custom button to a Model's Change List Page in Admin, redirect it to a confirmation page, execute a function on confirmation and then redirect to the change list page with execution status.
I have added the custom button but am lost after that.
Currently this is what I am doing:
Changed the admin class list template
class ReconciliationAdmin(admin.ModelAdmin):
change_list_template = 'SalesReconciliation/change_list.html'
This is my change list template:
{% extends "admin/change_list.html" %}
{% load i18n admin_static %}
{% block object-tools-items %}
{{ block.super }}
<li>
Run Reconciliation
</li>
{% endblock %}
Changed the urls.py in the main app as follows:
urlpatterns = [
url(r"^reconcileConfirm/", include("SalesReconciliation.urls")),
]
Changed the urls.py in the child app as follows:
urlpatterns = [
url(r'^reconcileConfirm/', views.ReconcileConfirm, name='ReconcileConfirm')
]
In the views.py of the child app added the follows:
def ReconcileConfirm(request):
return HttpResponse("..something")
I am hoping that this would work like:
Click on Run Reconciliation link -> Main urls.py routes to child
urls.py -> child urls.py routes to views.py -> function in views py
performs some operations
But I am getting the following errors:
NoReverseMatch at /SalesReconciliation/reconciliation/ Reverse for 'reconcileConfirm' not found. 'reconcileConfirm' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/SalesReconciliation/reconciliation/
Django Version: 2.0.4
Exception Type: NoReverseMatch
Exception Value: Reverse for 'reconcileConfirm' not found.
'reconcileConfirm' is not a valid view function or pattern name.
Also I would like to know whether it is the correct approach.
In your template:
{% url 'admin:reconcileConfirm'%}
in urls.py:
urlpatterns = [
url(r'^reconcileConfirm/', views.ReconcileConfirm, name='ReconcileConfirm')
]
Note that ReconcileConfirm is different from reconcileConfirm. This is probably the first error to fix in order to achieve what you want to.
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.
I recently started to work with Django-cms. I just created two templates base.html and home.html (this latter extends base.html), registered them into settings.py like this :
CMS_TEMPLATES = (
('base.html', 'Default'),
('home.html', 'Homepage'),
)
I've created my home page within the admin and selected the Homepage template but the content of this file is never shown.
I have followed the instructions from the documentation, but I don't understand where my mistake.
Anyone has any idea ?
Did you check your urls.py?
You have to make sure that you make a regualr expression that maps your views to your url and in your views you then call/load the template.
https://docs.djangoproject.com/en/dev/intro/tutorial03/
Little example on Kyle Calica's post:
in your urls.py you add something like this: (in your myproject/ folder where also your settings.py file is)
urlpatterns = patterns('',
url(r'^', include('myapp.urls')),
)
then in myapp.urls you need something like:
urlpatterns = patterns('',
url(r'^$', views.myview, name='myview'),
)
and then in your view:
def test(request):
return render(request, "my template.html")
and last in your template extend your base:
{% extends "base.html" %}
edit:
These are simple basics of django. if you dont grasp them i suggest you run the tutorial again and try to understand what they are actually doing.
Hi Hans (and #Kyle Calica-St), Thanks for your answer, but I have a correct urls configuration. I just created a new Blog app and I encountered the same problem. Here is my files :
settings.py
CMS_TEMPLATES = (
('base.html', 'Default'),
('home.html', 'Homepage'),
('news/home_news.html', 'News'),
)
urls.py
urlpatterns = i18n_patterns('',
# Homepage
url(r'^$', home_view),
# News
url(r'^news/', include('apps.news.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('cms.urls')),
)
views.py
def home_view(request):
return render(request, 'home.html')
home.html
{% extends "base.html" %}
{% load cms_tags %}
{% block base_content %}
{% placeholder home_content %}
<p>Hello World !</p>
{% endblock %}
Idem for news app
When I access to the homepage, I don't see the "Hello World !" p HTML tag.
I tried to change the order of the urls matches with no results.
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.