Django iframe gview from fileSystem/Storage not loading - html

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)

Related

Forbidden (CSRF token missing or incorrect.): /

So i want to make models form to upload file mp3. I was copy the code from website, but suddenly it goes error. Here's error message on the website :
Forbidden (403) CSRF verification failed. Request aborted.
Help Reason given for failure:
CSRF token missing or incorrect.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used
correctly. For POST forms, you need to ensure:
Your browser is accepting cookies. The view function passes a request
to the template's render method. In the template, there is a {%
csrf_token %} template tag inside each POST form that targets an
internal URL. If you are not using CsrfViewMiddleware, then you must
use csrf_protect on any views that use the csrf_token template tag, as
well as those that accept the POST data. The form has a valid CSRF
token. After logging in in another browser tab or hitting the back
button after a login, you may need to reload the page with the form,
because the token is rotated after a login. You're seeing the help
section of this page because you have DEBUG = True in your Django
settings file. Change that to False, and only the initial error
message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
and at my terminal there's error message :
[12/May/2022 14:19:43] "GET / HTTP/1.1" 200 8824 Forbidden (CSRF token
missing or incorrect.): / [12/May/2022 14:19:46] "POST / HTTP/1.1" 403
2513
please help me to fix it. i will give my code :
views.py:
from django.shortcuts import render, redirect
from django.views.decorators.csrf import ensure_csrf_cookie
from .forms import AudioForm
from .models import Audio_store
from MusicLockApp.forms import AudioForm
#ensure_csrf_cookie
def homepage(request):
# return HttpResponse('homepage')
return render(request, 'homepage.html')
def decode(request):
# return HttpResponse('about')
return render(request, 'decode.html')
def upload(request):
if request.method == "POST":
form = AudioForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect("main:upload")
form = AudioForm()
audio = Audio_store.objects.all()
return render(request=request, template_name="homepage.html", context={'form':form, 'audio':audio})
urls.py :
from django.contrib import admin
from django.conf.urls import url
from . import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import path, re_path
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^decode/$', views.decode),
url(r'^$', views.homepage),
path('audio', views.Audio_store),
]
urlpatterns += staticfiles_urlpatterns()
models.py:
from django.db import models
class Audio_store(models.Model):
record=models.FileField(upload_to='media/mp3')
forms.py:
from django import forms
from .models import Audio_store
class AudioForm(forms.ModelForm):
class Meta:
model = Audio_store
fields=['record']
add settings.py:
INSTALLED_APPS = [
'MusicLockApp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
{% block content %}
{% load crispy_forms_tags %}
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="row" style="margin-top: 20px; margin-right: 10px;">
<button type="button" class="dsnupload">
<i class="large material-icons" style="font-size: 50pt; margin-top: 10px;">file_upload</i>
<p style="font-weight: bold; color: white;">Insert file password</p>
</button>
</div>
<br>
<div class="row" style="margin-right: 10px;">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %^}
{{form|crispy}}
<button type="submit" class="dsnupload">
<i class="large material-icons" style="font-size: 50pt; margin-top: 10px;">audiotrack</i>
<p style="font-weight: bold; color: white;">Insert file audio (mp3)</p>
</button>
<p id="message"></p>
</form>
</div>
<br>
<div class="row" style="margin-right: 10px;">
<div class="col-1">
<label class="labels" style="color: white;">Key:</label>
<button type="submit" class="dsnupload"></button>
</div>
<div class="col-11">
<input type="text" class="form-control" placeholder="insert your key here">
</div>
<br> <br>
<a class="dsnhide" type="button" href="#" role="button">Hide it!</a>
</div>
</div>
<div class="col-md-6">
<div class="row" style="margin-top: 20px;">
<div class="card" style="height: 13rem;">
<div class="card-body">
<h5 class="card-title" style="text-align: center;">
Progressing now
</h5>
<br>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 75%">75%</div>
</div>
<br> <br>
<div class="text-center">
<button id="obfuscate-button" onclick="obfuscate()">Play song</button>
<a class="dsnbtn" type="button" href="#" role="button">Download</a>
</div>
</div>
</div>
</div>
<br>
<div class="row">
<div class="card">
<div class="card-body">
<h5 class="card-title">Information Music</h5>
<p class="card-text">Song :</p>
<p class="card-text">Artist :</p>
<p class="card-text">Album :</p>
<p class="card-text">Year :</p>
<p class="card-text">Genre :</p>
<p class="card-text">Duration :</p>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
what i want is = when i click button insert audio file, we can choose file from local and when clicked button hide it, it will upload it to local folder.
website
Easiest way
Try to change this url url(r'^$', views.homepage), in your urls.py file to this url(r'^$', views.upload),
Effective way
Or instead of that, delete your " homepage " view and rename your " upload " view to " homepage ".
Then check if it work. You'll normally see a form appear in your webpage to select your file.

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 can I display PIL image to html with render_template flask?

I tried to display my edited image with PIL package, when I tried to make it to display on the html <img src=''></img> it doesn't appear anything, but I see the file name on inspect elements was <img src="<_io.BytesIO object at 0x000001EDA8F76E00>">. How do I make the edited image display properly?
app.py
#app.route("/api/games/shipper/image/", methods=["GET"])
def games_shipper():
... # My stuff up here
image_io = BytesIO()
img.save(image_io, "PNG")
image_io.seek(0)
return render_template('image.html', image_data=image_io)
image.html
... // My stuff up here
<body>
<center>
<image src="{{ image_data }}"></image>
</center>
</body>
You can read the data from the buffer with the getvalue() function and then convert it. The base64 encoded data can then be passed to the src parameter as a data url.
from base64 import b64encode
#app.route("/api/games/shipper/image/", methods=["GET"])
def games_shipper():
... # My stuff up here
image_io = BytesIO()
img.save(image_io, 'PNG')
dataurl = 'data:image/png;base64,' + b64encode(image_io.getvalue()).decode('ascii')
return render_template('image.html', image_data=dataurl)
If you pass the image as a dataurl, there is no way to shrink the string. However, there is the possibility of serving the file as pure image data. You can use send_file in another endpoint for this. You serve the page (template) in one endpoint and the image file in a second.
from flask import send_file
#app.route('/')
def index():
return render_template('index.html')
#app.route('/image')
def game_shipper():
# ...
image_io = io.BytesIO()
img.save(image_io, format='PNG')
image_io.seek(0)
return send_file(
image_io,
as_attachment=False,
mimetype='image/png'
)
<body>
<center>
<img src="{{ url_for('game_shipper') }}" />
</center>
</body>
You'll need to encode your image in Base64 to display it in the img tag directly, see e.g. How to display Base64 images in HTML
The traditional way to display images in Flask templates is to save the image in Flask's static folder and link to it in your template like so
<body>
<center>
<image src="/static/{{image_name}}.png"></image>
</center>
</body>

Django Render HTML to PDF

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.

how to use dash_html_components.Script command

i would like to convert the code below into dash-plotly code.
may i know how to translate the second script tag in the HTML code into dash-plotly?
.summary:hover+.detail,
.detail:hover {
display: block;
}
.show.detail {
display: block;
}
.detail {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<a class="summary" href="javascript:void(0);">Sample1</a>
<div class="detail">Detail of this summary</div>
</div>
<div class="wrapper">
<a class="summary" href="javascript:void(0);">Sample2</a>
<div class="detail">Detail of this summary</div>
</div>
<div class="wrapper">
<a class="summary" href="javascript:void(0);">Sample3</a>
<div class="detail">Detail of this summary</div>
</div>
<script>
$(".summary").on("click", function() {
$(this).next().toggleClass("show");
})
</script>
You can build up the same html structure within plotly.
The following code is an working example.
Requirement: Your CSS code must be stored in static/stylesheet.css
Example:
import dash
import dash_core_components as dcc
import dash_html_components as html
from flask import send_from_directory
import os
app = dash.Dash(__name__)
server = app.server
# Configure Samples
sample1 = html.Div([
dcc.Link('Sample1', href='javascript:void(0);', className='summary'),
html.Div('Details of this summary', className='detail')
], className='wrapper')
sample2 = html.Div([
dcc.Link('Sample2', href='javascript:void(0);', className='summary'),
html.Div('Details of this summary', className='detail')
], className='wrapper')
sample3 = html.Div([
dcc.Link('Sample3', href='javascript:void(0);', className='summary'),
html.Div('Details of this summary', className='detail')
], className='wrapper')
# Define layout
app.layout = html.Div([
sample1,
sample2,
sample3
])
app.scripts.append_script({"external_url": [
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"
]})
# Add css file (locally hosted)
app.css.append_css({"external_url": [
"static/stylesheet.css"
]})
# Serving local static files
#app.server.route('/static/<path:path>')
def static_file(path):
static_folder = os.path.join(os.getcwd(), 'static')
return send_from_directory(static_folder, path)
if __name__ == '__main__':
app.run_server(debug=True)
try to add a custom-file.js in your assets forlder :
https://dash.plotly.com/external-resources
The example with the "altert" works for me, and the script appears in html / body / footer / script when I inspect the page of my app.