How to execute python script passing an argument from html page in django views and want to get output from the python script and display it in the same html page.
My views.py file
from django.shortcuts import render
def index(request):
context = {}
shortdes = request.GET.get('shortdes')
context['shortdes'] = shortdes
return render(request, 'webapp/ttgeniehome.html', context)
Want to pass shortdes variable as an argument to python script (eg: script.py which is available on the same directory where views.py file exists.
Related
I’m trying to get a variable into a html document with python and django
def nombrarVariables(request):
nombre="juan"
doc_externo=open("SeleccionGrafica2.html")
template=Template(doc_externo.read())
doc_externo.close()
contexto=Context({"variable": nombre})
documento=template.render(contexto)
return HttpResponse(documento)
Can you try this snippet in a more concise way:
from django.shortcuts import render
def nombrarVariables(request):
nombre = 'juan'
context = {'nombre': nombre}
return render(request, 'SeleccionGrafica2.html', context)
In your template you can access your variable with {{nombre}} and in the render function change the path of your templates regarding your file structure
I am trying to display my data on the HTML file but I am unable to display, I have a function in views.py file and i render this function data on my HTML file, but it's not going to the HTML path, please let me know how I can display data in Django default template.
Here is my app appname and its have a views.py file and this file has a function that displays my data on the HTML page...
please have a look at the views.py file...
def mydata():
var1=Mymodel.objects.all()
template_name='../templates/admin/appname/modelname/change_list.html'
context={'var1':var1}
return render(request, template_name, context)
Note: this template folder is that which Django provides in default, it's not available inside my app (appname), it's available outside of my app
so main issue is in thsi path template_name='../templates/admin/appname/modelname/change_list.html', because it's getting the correct path
Create folder templates inside you app, put there template.html. Then in views.py:
def mydata(request):
you code
return render(request, 'template.html', locals())
locals will collect all variables that you created inside function.
I have a Django site and want it so that when the user presses a button on the site that a python file makes a word document and shows it to the user in the browser.
I am getting an error saying that context must be a dict rather than set.
my document seems to be made in my pycharm project folder but it doesn't want to show itself for some reason.
my process is as follows: user clicks a html button. urls.py then points the browser to a function in my view.py called making_the_doc. This making_the_doc function runs a function in my the plot.py file which will generate the document and returns it to view.py for presentation to the user.
Firstly i created the code that will generate the document. This file is known as theplot.py.
THEPLOT.PY
def making_a_doc_function(request):
doc = docx.Document()
doc.add_heading('hello')
doc.save('this is doc.docx')
generated_doc = open('this is doc.docx', 'rb')
response = FileResponse(generated_doc)
return render(request, 'doc.html', {response})
Then I linked this function to my views.py
VIEWS.PY
def making_the_doc(request):
return making_a_doc_function(request)
Then i created my url paths to point to the views.py
URLS.PY
path('making_a_doc', views.making_the_doc, name='doc'),
finally I generate my html button so the whole process can start off when the button is clicked:
INDEX.HTML
<input type="button" value="generating" onclick="window.open('making_a_doc')">
You are not passing a dict to your render function. A change like this should make it work
def making_a_doc_function(request):
doc = docx.Document()
doc.add_heading('hello')
doc.save('this is doc.docx')
generated_doc = open('this is doc.docx', 'rb')
response = {"generated_doc": FileResponse(generated_doc)}
return render(request, 'doc.html', response)
I would like to create a website-app to run a bash script located in a server. Basically I want this website for:
Upload a file
select some parameters
Run a bash script taking the input file and the parameters
Download the results
I know you can do this with php, javascript... but I have never program in these languages. However I can program in python. I have used pyQT library in python for similar purposes.
Can this be done with django? or should I start learning php & javascript?
I cannot find any tutorial for this specific task in Django.
This can be done in Python using the Django framework.
First create a form including a FileField and the fields for the other parameters:
from django import forms
class UploadFileForm(forms.Form):
my_parameter = forms.CharField(max_length=50)
file = forms.FileField()
Include the UploadFileForm in your view and call your function for handling the uploaded file:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
my_parameter = form.cleaned_data['my_parameter']
# Handle the uploaded file
results = handle_uploaded_file(request.FILES['file'], title)
# Clear the form and parse the results
form = UploadFileForm()
return render(request, 'upload.html', {'form': form, 'results': results})
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
Create the function to handle the uploaded file and call your bash script:
import subprocess
import os
def handle_uploaded_file(f, my_parameter):
file_path = os.path.join('/path/to/destination/', f.name)
# Save the file
with open(file_path, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
# Call your bash script with the
output = subprocess.check_output(['./my_script.sh',str(file_path),str(my_parameter)], shell=True)
return output
Check out https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/ for more examples and instructions on how the handle file uploads in Django.
I'm (new to) working in Django and would like to create two features that do not rely upon models/database tables. The basis of this app is as a web-based wrapper to a Python application.
The features are:
I would like to be able to load a ConfigObj text file into a page and edit it's configuration prior to saving again.
I would like to be able to call command line python/bash scripts and display their output on a page - like exec in PHP.
At the moment I'm working on simple custom admin pages without model as described here:
Django admin, section without "model"?
Would this be the right direction to go in? I'm not sure proxy tables apply as the features I desire have nothing to do with any data.
So far I have looked at is it possible to create a custom admin view without a model behind it and a few other links. At the moment I have:
main/urls.py
url(r'^admin/weectrl', include('weectrl.urls')),
which links with weectrl/urls.py
from weectrl import views
urlpatterns = patterns('',
(r'^admin/weectrl/manage/$', weectrl_manage_view),
(r'^admin/weectrl/config/$', weectrl_config_view),
)
which points to weectrl/views.py
def weectrl_manage_view(request):
r = render_to_response('admin/weectrl/manage.html', context, RequestContext(request))
return HttpResponse(r)
def weectrl_config_view(request):
r = render_to_response('admin/weectrl/config.html', context, RequestContext(request))
return HttpResponse(r)
The current error message is name 'weectrl_manage_view' is not defined
Ok, found something that works.
In the main url.py
url(r'^admin/weectrl/', include('weectrl.urls')),
In app/urls.py
urlpatterns = patterns('',
url(r'^config/$', views.config, name='config'),
url(r'^manage/$', views.manage, name='manage'),
)
and in app/views.py
def config(request):
context = ""
return render(request, 'weectrl/config.html', context)
def manage(request):
context = ""
return render(request, 'weectrl/manage.html', context)
html files are in app/templates/app/...