Django/Python: Show pdf in a template - python

I'm using django 1.8 in python 2.7.
I want to show a pdf in a template.
Up to know, thanks to MKM's answer I render it in a full page.
Do you know how to render it?
Here is my code:
def userManual(request):
with open('C:/Users/admin/Desktop/userManual.pdf', 'rb') as pdf:
response = HttpResponse(pdf.read(), content_type='application/pdf')
response['Content-Disposition'] = 'inline;filename=some_file.pdf'
return response
pdf.closed

The ability to embed a PDF in a page is out of the scope of Django itself, you are already doing all you can do with Django by successfully generating the PDF, so you should look at how to embed PDFs in webpages instead:
Therefore, please check:
Recommended way to embed PDF in HTML?
How can I embed a PDF viewer in a web page?

views.py
from django.shortcuts import render
from django.http import FileResponse, Http404
def pdf(request):
try:
return FileResponse(open('<file name with path>', 'rb'), content_type='application/pdf')
except FileNotFoundError:
raise Http404('not found')
def main(request):
return render(request,'template.html')
url.py
from django.urls import path
from django.conf.urls import url
from . import views
urlpatterns =[path('', views.main, name='main'),url(r'^pdf', views.pdf, name='pdf'),]
template.html
<embed src={% url 'pdf' %}'#toolbar=0&navpanes=0&scrollbar=0'style="width:718px; height:700px;" frameborder="0">

Related

How to solve NoReverseMatch at / (Error during template rendering) in django 3.2?

Here is the screenshots of error i am getting.
and
App Name is greeting_app
Now greeting_app/urls.py has the following code
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('about/<int:id>/', views.about, name="about"),
]
greeting_app/views.py has the following code
from django.shortcuts import render, HttpResponse
from .models import basicinformation
# Create your views here.
def home(request):
information = basicinformation.objects.all()
return render(request, 'index.html', {"info":information})
def about(request, id):
data = basicinformation.objects.get(id=id)
return render(request, 'about.html', {"data":data})
templates/index.html has the following code. I have included only the url part in index.html file.
Description
data.id does not contain an ID. From the error message it contains ('',) (or possibly (",) - it's hard to tell from an image. Please don't use images!).
You do for all in info, then reference all in every other template line, then suddenly try and use data.id.
Since you haven't posted your whole template, it's hard to tell, but I suspect you want to use all.id in your URL here, and not data.id.
Add this to urls.py above urlpatterns
app_name=“ greeting_app”
Fix template url to this:
<a href="{% url "greeting_app:about" data.id %}">Description

How to reload configurations in Django (Python)

I'm new to Django.
I made a URL shorter website like bitly for a test, and when users upload new URL, my program upload data to DB.
The problem is that Django doesn't reload urls.py. So if users upload their URL, data is saved in DB, but urls.py doesn't reload, so 404 shows because urls.py is not reloaded, because there are no data about new URL in urls.py.
I've searched in Google, I almost visited every website searched, but I couldn't find the answer.
How do I reload Django configurations without turning off and on the django server?
#root/url/urls.py
from django.urls import path
from django.http import HttpResponse #HttpResponse
from . import views
from . import models
urlpatterns = [
path("", views.Index),
path("urlprocess/", views.Process)
]
for i in models.Urllist.objects.all():
data = path(i.custom, lambda request: HttpResponse("<script>location.href = '{}'</script>".format(i.url)))
urlpatterns.append(data)
#views.py (Uploading Code)
def Process(request):
if request.method == "POST":
data = json.loads(request.body)
custom = data["custom"]
urllist = models.Urllist.objects.all()
for i in urllist:
if i.custom == custom:
return HttpResponse("customerror")
#upload
new = models.Urllist(url=data["url"], custom=custom)
new.save()
#reload(sys.modules[settings.ROOT_URLCONF])
return HttpResponse(custom)
else:
return HttpResponse(status="500")

Rendering an XML value to HTML within Python-Django project

I am trying to load a value within a XML file in my project to a HTML page so that is renders in the browser. The value that I want to display is the version number of my project and it is in the format "v2.0.0". This XML file is named 'build.xml' and is contained with the 'templates/' folder in my Python-Django project. The problem I am having is that my Python code just opens the XML file when I hit the index "/" page. I want the value to be passed to the HTML.
File: myproject/urls.py
from django.urls import path
from . import views
urlpatterns = [path('', views.index, name='index')]
File: myproject/views.py
from django.http import HttpResponse
def index(request):
#return HttpResponse('Hello, welcome to the index page.')
return HttpResponse(open('templates/build.xml').read(), content_type='text/xml')
File: myproject/templates/build.xml
<version>v2.0.0</version>

Django error templates in custom path

I have dir template with all templates, and I have dir errors, with all templates with errors 404.html.
I found the following old solution:
In urls.py my app I wrote
from django.conf.urls import (handler400, handler403, handler404, handler500)
handler404 = 'my_app.views.page_not_found'
And in view my app
from django.shortcuts import (render_to_response)
from django.template import RequestContext
def page_not_found(request):
response = render_to_response(
'errors/404.html',
context_instance=RequestContext(request))
response.status_code = 404
return response
But I use Django 1.11 and this doesn't work.
If you follow the docs
You should return HttpResponseNotFound which is the same as HttpResonse except for status code. It worked for me.
def bad_request(request):
response = render_to_response(
'errors/404.html'
)
return HttpResponseNotFound(response.content)

Django urls straight to html template

Learning django & python.
Just set up a new site after doing the tutorial. Now for arguments sake say I want to add a bunch of About us, FAQ basic html pages with very limited dynamic elements do you go ahead and write a new line in my urls.py file for each page? or is their some neat way to say map all * *.html to the relevant .html file directly?
In general even if it does require a view will I have to write a new line in the url.py file for every page?
As long as there is some uniquely identifying section in the URL, you will not need to create an entry in urls.py for each direct-template url.
For example, you could say that all urls ending in ".html" are referencing a direct file from the templates.
urlpatterns = patterns('django.views.generic.simple',
(r'(.+\.html)$', 'direct_to_template'),
# ...
)
Take a look at http://docs.djangoproject.com/en/1.2/ref/generic-views/#django-views-generic-simple-direct-to-template for details.
Currently the best way to do this is using TemplateView from generic class-based views:
from django.views.generic.base import TemplateView
url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'),
Write a url which grabs the static pages you're interested in
url(r'^(?P<page_name>about|faq|press|whatever)/$', 'myapp.staticpage', name='static-pages')
The staticpage view function in myapp
from django.views.generic.simple import direct_to_template
from django.http import Http404
def staticpage(request, page_name):
# Use some exception handling, just to be safe
try:
return direct_to_template(request, '%s.html' % (page_name, ))
except TemplateDoesNotExist:
raise Http404
Of course, you need to follow a naming convention for your templates, but this pattern can be expanded upon as needed.
This is better than the .+\.html pattern because it will treat templates which don't exist as 404s, whereas .+\.html will blow up with 500 errors if the template doesn't exist.
If you're using the class based views because direct_to_template has been deprecated, you can create a simple wrapper that renders your own templates directly:
from django.views.generic import TemplateView
from django.template import TemplateDoesNotExist
from django.http import Http404
class StaticView(TemplateView):
def get(self, request, page, *args, **kwargs):
self.template_name = page
response = super(StaticView, self).get(request, *args, **kwargs)
try:
return response.render()
except TemplateDoesNotExist:
raise Http404()
and in your router:
from myapp.static.views import StaticView
urlpatterns = patterns('',
url(r'^(?P<page>.+\.html)$', StaticView.as_view()),
# ...
)
One way to do this would be to write a single custom view that wraps the direct_to_template generic view. The wrapper could accept a parameter and accordingly form the name of the template and pass it to direct_to_template. This way you can route multiple pages with a single URL configuration.
Something like this:
url(r'^foo/(?P<page_name>\w+).html$', 'my_static_wrapper', name = 'my_static_wrapper'),
def my_static_wrapper(request, page_name):
# form template name and call direct_to_template
That said I suspect that there are better solutions out there though.
Slight Changes for latest versions of Django.
from django.views.generic.base import TemplateView
urlpatterns = [
path('',TemplateView.as_view(template_name='index.html'), name='home'),
]

Categories