How to add Django statements to Javascript - django

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.

Related

Django dev server using old version of views.py

For some reason, the changes I make on the views.py file are not being reflected. I initially made a function inside view.py to return HttpResponse(request.POST.items()). Even after making changes to the function, it's still performing the same thing. I tried clearing the cache of the browser, restarted the server, and also tried deleting the pyc files. Nothing worked. Any guess on why this is happening?
urls.py
from . import views
urlpatterns = [
path('',views.index, name='index'),
path('proceedaction/<str:pk>/',views.ProceedAction.as_view(),name='proceedaction'),
path('uploadct/<str:pk>/',views.UploadCT.as_view(),name='uploadct'),
]
views.py
from django.shortcuts import render,redirect
from django.views import View
from .models import CreatePatient,PatientRecord,FileData
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from .filters import RecordFilter
from django.http import HttpResponse
import json
# Create your views here.
def index(request):
return render(request,'index.html')
class UploadCT(View,LoginRequiredMixin):
def get(self,request,pk):
records = PatientRecord.objects.filter(id=pk)
context={
'record' : records,
}
return render(request,'ct_upload.html',context=context)
def post(self,request):
dbdata = FileData()
return redirect('index')
I had not specified method=POST in the corresponding HTML file. Solved this issue by doing that.

Pass a file path as a URL parameter in Django

I'm using Django to create a webapp. When a user press on a certain button, it needs to pass a file path as parameter and a string parameter to one of my views. I can't simply use the parameter in the URL since the path contains several '/'. The way I have it setup right now is as follows:
parameters.py
class FilePathConverter:
regex = '^[/]'
def to_python(self, value):
value=str(value)
return value.replace("?", "/")
def to_url(self, value):
value=str(value)
return value.replace("/", "?")
urls.py
from django.urls import path
from . import views
from django.contrib import admin
from django.views import generic
from django.urls import path, register_converter
from . import converters, views
register_converter(converters.FilePathConverter, 'filepath')
urlpatterns = [
path('', views.index, name='webpanel-index'),
path('controlserver/<filepath:server_path>/<str:control>', views.index, name='controlserver'),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Server
from django.contrib.auth.decorators import login_required
import subprocess
def controlserver(request, server_path, control):
if request.POST:
subprocess.call(['bash', server_path, control])
return render(request, 'index.html')
However, with this method, I get this error:
Reverse for 'controlserver' with keyword arguments '{'server_path': 'rien/', 'control': 'start'}' not found. 1 pattern(s) tried: ['controlserver/(?P<server_path>[^/]+)/(?P<control>[^/]+)$']
you can use Slug to resolve this patterns by :
from django.utils.text import slugify
path('controlserver/use slug .....', views.index, name='controlserver'),
but you need to put slug at views and templates So check this list of slug and pk :
https://github.com/salah-cpu/migration/blob/master/PATH_slug_pk

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.

Can I print just the content of a html template in 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>

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.