Django Render HTML to PDF - html

I'm trying to render an html file to pdf however while the pdf functionality is working fine the rendering is working properly, no css. Also it renders the whole page, how can i render specific sections of the html page. I'm using xhtml2pdf.
views.py file
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from django.views import View
from xhtml2pdf import pisa
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
data = {
"company": "Name",
}
#Opens up page as PDF
class ViewPDF(View):
def get(self, request, *args, **kwargs):
pdf = render_to_pdf('listings/listing.html', data)
return HttpResponse(pdf, content_type='application/pdf')
urls.py file
path('pdf_view/', views.ViewPDF.as_view(), name="pdf_view"),
html file
<section class="p0">
<div class="container">
<div class="row listing_single_row">
<div class="col-sm-6 col-lg-7 col-xl-8">
<div class="single_property_title">
<span class="flaticon-photo-camera"></span> View Photos
</div>
</div>
<div class="col-sm-6 col-lg-5 col-xl-4">
<div class="single_property_social_share">
<div class="spss style2 mt10 text-right tal-400">
<ul class="mb0">
<li class="list-inline-item"><span class="flaticon-transfer-1"></span></li>
<li class="list-inline-item"><span class="flaticon-heart"></span></li>
<li class="list-inline-item"><span class="flaticon-share"></span></li>
<li class="list-inline-item"><span class="flaticon-printer"></span></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</section>
Thank you!

Ans 1.) If you want to style your html than directly use style property in tag. If you make class and use template inheritance than it is not going to work as it is independent html. Use style directly in html.
Ans 2.) if you want specific section of html in pdf than write content which you need in html or use style = “display: none ;” on section which you dont want in pdf.

Related

I cannot send a variable to template in django

I am trying to send data to a template but it doesn't get rendered. The html file loads but the field {{patient}} is blank and doesn't show 'abcde'.
Here is my code:
views.py
def exam_table(request):
context = {'patient': 'abcde'}
return render(request, 'examtable.html', context)
examtable.html
<div class="row d-flex align-items-center">
<div class="col-9">
<h3 class="f-w-300 d-flex align-items-center m-b-0">
<i class="feather icon-arrow-up text-c-green f-30 m-r-10"></i>$
<p>{{patient}}</p></h3>
</div>
urls.py
urlpatterns = [
# The home page
path('', views.index, name='home'),
path('insert_patient',views.insert_patient,name='insert_patient'),
path('nurse_patient',views.nurse_patient,name='nurse_patient'),
path('examtable',views.exam_table,name='examtable'),
# Matches any html file
re_path(r'^.*\.*', views.pages, name='pages'),
]
it should pass a dictionary value
def exam_table(request):
context = {'patient': 'abcde'}
return render(request, 'yourpage.html', {'context': context})

Dynamic URL routing is not working in django web application

A am working on a simple application, where trying to generate Dynamic URl and routing take place as per the ID in the url.
Dynamic value is getting populated in the URL, but it not performing action that needed.
prop_listings.html HTML Page:-
<div class="row text-secondary pb-2">
<div class="col-6">
<i class="fas fa-clock"></i> {{ listing.list_date | timesince }}
</div>
</div>
<hr>
More Info
</div>
</div>
</div>
URL.py in App Listings:-
from django.urls import path
from . import views
urlpatterns = [
path('',views.PropListings,name="prop_listings"),
path('<int:listing_id>', views.mlisting, name="morelisting"),
]
Views.py :-
def mlisting(request, listing_id):
# listingDetl = get_object_or_404(Listing, pk=listing_id)
listingDetl = Listing.objects.get(pk=listing_id)
print(listingDetl.username, listingDetl.address,listingDetl.city)
context = {
'listingDetails': listingDetl
}
return render(request,'listings/detail_listing.html', context)
URL.py in MainProject:-
urlpatterns = [
path('', include('static_pages.urls')),
path('user_account/', include('user_account.urls')),
path('listings/', include('listings.urls')),
path('feedback/', include('feedback.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Am trying to redirect the page from prop_listings.html to detail_listing.html, based on the below tag URL generated on listing.id
More Info
It's not working as expected on-click of above tag.
But when i did inspect on the same, URL is getting generated properly and when i click on the url, it will work as expected.
Inspect on the html page, URL populated
I looked into similar issue threads and tried to make changes, but not able to fix it.
Not getting what the issue and how to correct it.

how to show external media in template in django

Hi i'm currently new to Django and i'm trying to populate a product page.
I'm having problem with the img to show the image(which uses an image url online instead of a file) for example an img src="media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg"
The url already in my database with the text media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg
But when i tried to render it in template the image doesn't show
I tried to used the but it still not work
Any help would be appreciate!
My template
{% for discount in discounts|slice:":8" %}
<div class="col-md-3 product-men women_two">
<div class="product-googles-info googles">
<div class="men-pro-item">
<div class="men-thumb-item">
<img src="{{STATIC_URL}}{{discount.product_image}}" alt="" />
<div class="men-cart-pro">
<div class="inner-men-cart-pro">
Quick View
</div>
</div>
<span class="product-new-top">New</span>
</div>
<div class="item-info-product">
<div class="info-product-price">
<div class="grid_meta">
<div class="product_price">
<h4>
{{discount.product_name}}
</h4>
<div class="grid-price mt-2">
<span class="money">{{discount.product_old_price}}</span>
</div>
</div>
<div>
<h3>{{discount.product_sit}}</h3>
</div>
<div><h2 style="color: red;">Only {{discount.product_price}}!</h2></div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
{% endfor %}
EDIT
Seems like the image src trying to get is "http://127.0.0.1:8000/media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg" which i don't want "http://127.0.0.1:8000/" in the link. Is there a way to remove this when using {{discount.product_image}} tag ?
Main project urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('frontend.urls')),
]
frontend app urls.py:
from django.urls import path
from .import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'frontend'
urlpatterns = [
#index
path('',views.index, name='index')
]
Try using .url like this.
<img src="{{ discount.product_image.url }}" alt=""/>
Also add the MEDIA and STATIC url to your project url patterns.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URL pattern goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
EDIT:
From the discussion in chat, I understood that I had misunderstood your problem first. The images are external and not in your db, you are just storing the URL to the images. And you are using a TextField not ImageField. I assumed ImageField previously. So, all you have to do is to replace {{STATIC_URL}} from in front of the actual URL and put http:// there. The reason behind this is, as the src is missing http:// it's assumed the image to be in the same host domain. So it goes to http://127.0.0.1/your_url.
<img src="http://{{ discount.product_image }}" alt=""/>

HTML how to structure form-groups and bootstrap classes to catch single form data, pass to Python Flask

I have a "GET" / "POST" split on my html page courtesy of a python flask script:
def home(name=None):
if request.method == "GET":
return render_template('home.html', name=name)
if request.method == "POST":
files = request.form["file[]"]
do things with the files
On my home.html page, I have added in some bootstrap code to make everything pretty, but the flask module is now not taking in the form data properly. Here's my html code:
<form id="uploadbanner" enctype="multipart/form-data" method="post" action="{{ url_for('home') }}">
<div class="form-group">
<div class="container">
<div class="page-header">
<br>
<h1>Title</h1>
<br>
<br>
</div>
<div class="row">
<div class="col-lg-6 col-md-6 col-s-6 col-xs-12">
<h4>File Control</h4>
<div class="jumbotron">
And my form data is here:
<input type="file" name="file[]" id="inputnameid" multiple=""/>
</div>
</div>
Second Column
</div>
New Row, etc etc
Each new row has buttons and inputs that I want to match with the form data using the name field.
I know I'm not structuring this properly, but I can't seem to find any info on how to mesh bootstrap and forms.
I think in order to get the files, you should use request.files["file[]"] instead of request.form["file[]"] .

Django iframe gview from fileSystem/Storage not loading

Im trying to load with gview a PDF file from the filesystem
The file its storage and when I call "{{documento.adjunto.url}}" it doesnt shows me 404 error, but still the PDF its not show.
Trying using one from web, it works.
<iframe src="http://docs.google.com/gview?url=https://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf&embedded=true" style="width:600px; height:450px;" frameborder="0"></iframe>
HTML
<div class="container">
<div class="row">
<div class="col-lg-12">
<iframe src="http://docs.google.com/gview?url={{documento.adjunto.url}}&embedded=true" style="width:600px; height:450px;" frameborder="0"></iframe>
</div>>
</div>
</div>
Viws.py
#login_required
def CurriculumDetailView(request, pk):
documento = Curriculum.objects.get(pk=pk)
return render(
request,
"INTRANET/curriculum_detail.html",
context = { 'documento':documento,
},
)
Model
class Curriculum(models.Model):
rut_candidato = models.ForeignKey(Candidato, on_delete=models.CASCADE)
adjunto = models.FileField(upload_to=UPLOAD_CVS)
fecha_ingreso_cv = models.DateField(_("Date"), auto_now_add=True)
URL.py
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)