Can I print just the content of a html template in django? - django

I am using Django with python to create a web application, I am a beginner in this. I hope that you can help me.
I want to print this page by clicking a button.
Now, I am just trying to generate the pdf first.
I want just to print the content, like that
I tried these functions.
#views.py
from django.views.generic.detail import DetailView
from MagasinProject.views import PdfMixin
from MagasinProject.utils import generate_pdf, render_to_pdf_response, pdf_decorator
from django.contrib.auth.models import User
from django.shortcuts import render
def test_view(request):
resp = HttpResponse(content_type='application/pdf')
result = generate_pdf('demande/demande.html', file_object=resp)
return result
#urls.py
from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns=[
path('demande',views.index, name='demande'),
url(r'^test_view$', views.test_view),
]
This is what I got

You can print the HTML page with a print button like this (see w3schools):
<button onclick="window.print()">Print this page</button>

Related

How to go from one page to another in django

I'm new to Django and python (infact my first language which I've only been learning for 3 months)
I'm creating this website using Django and I'm not able to go from one page to another using the href tag. it throws at me a 404 error saying "current path didn't match any of these"
This is my code
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import off
# Create your views here.
def homepage(request):
return render(request=request,
template_name='main/home.html',
context={'toll' : off.objects.all})
def secondpage(request):
return render(request = request,
template_name = 'main/next.html')
main/urls.py
from django.urls import path
from . import views
app_name = 'main'
urlpatterns = [
path('',views.homepage,name='homepage'),
path('',views.secondpage,name='secondpage')
]
templates/mains/home.html
<div class="topnav">
Link
Link
Link
</div>
I also request the helper to simply it for me as I wouldn't be able to handle complex and advanced python terminology
Thanks In Advance From a Friend
Arvind
I think you should read this to start with Django.

How to add Django statements to Javascript

I'm trying to implement some JS code in django so anytime i click a button, it returns the current year.. how do i do this
I've tried using some JS events handler in my django based templates
from datetime import datetime
from django.template import Template, Context
from django.http import HttpResponse as toHTML
cont = Context({'dat':datetime.now()})
def say_year(request):
htm = Template("<button onclick='alert({dat})'>click me</button>")
htm = htm.render(cont)
return toHTML(htm)
i'm expecting an alert box showing full datetime.now() methods
I prefer that you do it that way in order to have full control over the template.
1 - make the views.py that way :
from datetime import datetime
from django.template import Template, Context
from django.shortcuts import render
def say_year(request):
context = {
'dat': datetime.now()
}
return render(request, 'mytemplate.html', context)
2- The urls.py should look that way :
from django.contrib import admin
from django.urls import path
from your_app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('my_template/', views.say_year )
]
3- You create a templates folder in the root directory of your project where all your templates will live.
For your question i have create my_template.html and it should be that way :
<button onclick="alert('{{dat}}')">click me</button>
If you have more questions please let me know.

How to insert seperate Python scripts in Django

I have created a webscraper in Python and now I want to insert this file into my views.py and execute them using the HTML button created on the HTML page.
My scraper name is maharera.py and it is saved in same folder where I have saved views.py
My views.py looks like this:
from django.shortcuts import render
from django.conf.urls import url
from django.conf.urls import include
from django.http import HttpResponse
# Create your views here.
def index(request):
first = {"here":"will enter more details"}
return render(request, "files/first-page.html", context=first)
#return HttpResponse("<em>Rera details will be patched here</em>")
After inserting it in views.y I want to execute that file using html HTML I created. How can I do that?
Actual answer to question
Lets say the contents of maharera.py are as follows
def scraper(*args, **kwargs):
#the scraper code goes here
then you'll need to import it as follows in the views.py file
from django.shortcuts import render
from django.conf.urls import url
from django.conf.urls import include
from django.http import HttpResponse
# Create your views here.
import maharera
def index(request):
first = {"here":"will enter more details"}
return render(request, "files/first-page.html", context=first)
#return HttpResponse("<em>Rera details will be patched here</em>")
def scraper_view(request):
maharera.scraper()
return HttpResponse("<em>Scraper started</em>")
It is advisable to not run a web scraper through a http requests like these. Http requests are supposed to return response within fraction of seconds and should not take long.
When you hit scraper_view it will start executing the code inside it. In scraper view, there is call to the scraper and we don't know how long will it take for that function to end. Till that function doesn't end, the response of the page will not be returned to the user.
For such long running tasks, you should look into task queues.
Looking into celery

Could not parse the remainder: '-save' from 'waypoints-save'

I am trying a simple app in geodjango by following http://invisibleroads.com/tutorials/geodjango-googlemaps-build.html.
My view function is
# Import django modules
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
# Import system modules
import json
# Import custom modules
from waypoints.models import Waypoint
def save(request):
'Save waypoints'
for waypointString in request.POST.get('waypointsPayload', '').splitlines():
waypointID, waypointX, waypointY = waypointString.split()
waypoint = Waypoint.objects.get(id=int(waypointID))
waypoint.geometry.set_x(float(waypointX))
waypoint.geometry.set_y(float(waypointY))
waypoint.save()
return HttpResponse(simplejson.dumps(dict(isOk=1)), mimetype='application/json')
And urls.py is
from django.conf.urls import patterns, include, url
urlpatterns = patterns('waypoints.views',
url(r'^$', 'index', name='waypoints-index'),
url(r'^save$', 'save', name='waypoints-save'),
)
It is showing an error http://dpaste.com/3EJVX0G
Template index.html is here http://pastebin.com/125Dm6Bz
Please help me.I am new to django.
The parameter to the {% url %} tag must always be in quotes if it's a literal string (this has been the case since version 1.5, which is quite a long time).
The one that's causing the error is this:
$.post("{% url waypoints-save %}"
which should be:
$.post("{% url "waypoints-save" %}"
but you make the same mistake several times in that template.

Following django form submission, redirect to page using newly created pk

I am trying to redirect the user to edit details of a task after task submission, but am having troubles redirecting to a page based on the newly created pk. Each view works without the return HttpResponseRedirect line. I have also tried arge=(instance.id) and kwargs=(instance.id) for the variable.
views.py
...
from django.http import HttpResponseRedirect, HttpResponseServerError, HttpResponseForbidden, Http404, HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, get_object_or_404,render
...
def new_task(request):
...
...
task.save()
instance = task.save()
return HttpResponseRedirect(reverse('task_values', instance.id))
def task_values(request, task_id):
...
urls.py
from django.conf.urls.defaults import patterns, include, url
from django.http import HttpResponseRedirect
from django.views.generic.simple import direct_to_template
urlpatterns += patterns('core.views_entry',
#Task viewing/editing
(r'^task/(?P<task_id>\d+)/$','task_values'),
(r'^enter/$','new_task'),
return HttpResponseRedirect(reverse('task_values', kwargs={'task_id': instance.id}))
Also note that you don't need to save the task twice.
Edit OK, there's another problem. You haven't given your URLs specific names, which means that the only way to identify them is to pass the fully qualified view name:
reverse('core.views_entry.task_values', kwargs=...)
Or, better, use the the url() function to name your URL:
url(r'^task/(?P<task_id>\d+)/$','task_values', name='task_values'),
and you can use the original version I gave above.
Note that the error isn't telling you it's going to enter/<id>/, just that in that view it's trying to create the reverse URL for the redirection and failing.