Showing a generated document using django - python

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)

Related

Loading Template in Admin Form for Custom Fields

I learned that I can add a custom button in my Admin form by adding it to
fields = ["connect"]
readonly_fields = ('connect',)
def connect(self, obj):
return format_html("<button></button>")
connect.allow_tags=True
connect.short_description = ''
However, the html I want to add to the connect is getting out of control. I was wondering if there's a proper (Django-nic) way to move that to a template and load and return the content of the template in the connect function.
I can think of reading the content of the template file (open('file.html', 'r')) to read the content, however, I am looking for a suggestion that aligns Django standards (if any).
P.S. I also tried creating a view for getting the HTML content of the connect file, but that for some reason doesn't seem to work and feels unnatural to do.
from django.template.loader import render_to_string
...
def connect(self, obj):
html = render_to_string('file.html')
return html
With file.html in templates directory

How to render in template in Django?

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.

Django: Pass arguments in View and display on the page

Say, I've got 2 views in views.py: Fetching_information_view and Processing_view.
In Fetching_information_view I am fetching information which I am displaying to the user in the tabular format on the "home.html" page. That's all okay.
Now, I get a CSV URL for each row as well. I don't want that when the user clicks on the CSV URL it should open the CSV; instead, when the user clicks on it then it should go to the Processing_view and it should be served on a different HTML page, say "process.html".
CSV URL:
/some_bucket/some_csv_file.csv?AWSAccessKeyId=some_id&Expires=1234&Signature=some_signature
Desired URL:
http://example.com/process.html?file=some_bucket/some_csv_file.csv?AWSAccessKeyId=some_id&Expires=1234&Signature=some_signature
Now, how can I call Processing_view from the Fetching_information_view view and send the file information? It should process in the backend and display results on process.html.
This is the table I am showing on the homepage:
I've wrote sample code for views.py which I'm using:
def process_data(request):
# what should come here?
# Display in process.html
def home(request):
some_data = SomeTable.objects.filter(user = request.user)
args = {"some_data": some_data}
# display as table on home.html, including URLs it is carrying
return render(request, "home.html", args)
If you don't want to expose the URL of your CSV files, then don't add it (and also don't expose the URL parameters) to the context of your home view and template.
So assuming you've created a urlpattern named process_view for your process_data view, in your home.html template you can just use href="{{% url 'process_view' %}?id={{ id }}" to append the id of the object to your request's URL parameters.
Then in the process_data view, you can get this id by id = request.GET.get('id'), fetch the model with this id and reconstruct the CSV url and file parameters.

How to execute script python when i click button in form html?

hello how can i run script that i build on python when i click button on form html
i saw examples like this but i dont get it:
Html code: index.html
<form action="{% url my_view %}" method="post">
<input type="submit" value="Ok">
</form>
views.py
import django.shortcuts import render
def my_view(request):
if request.method == 'POST':
import set_gpio
#my url is "templates/load.py"
return #How can i return?
You need to return an HttpResponse object from your view. You can return one response inside your if statement, and another outside of it (so anything but a POST). Usually the render shortcut is used to render a response from a template. So your view would be something like:
import django.shortcuts import render
def my_view(request):
if request.method == 'POST':
# The user clicked the button (POST)
return render(request, "load.html")
# The user is just loading the view for the first time (GET)
return render(request, "index.html")
I highly suggest going through the django tutorial.
You have to realise that Django is a HTTP based framework meaning that when an HTTP request is sent to a url, Django will be allowed to perform an action. So, every function is actually a reaction to the HTTP requests that the user sends to your urls.
Also, if you are using Django template system, the html file should be rendered by Django in the first place. So, you cannot have a standalone html file with {% url my_view %} in it.
First, you have to configure the main urls.py which is in a folder with the same name as your project.
Second, in your app, create an urls.py file and configure it.
At the end, you connect your my_view to a specific or set of urls and will be triggered when a request is sent to that url, whether GET or POST.
These are somewhat large (and easy) topics for which you have to watch a tutorial or read the Django documentations.

Django html interacts with views

I have a html that contains some forms and buttons. One button corresponds to a file that I have uploaded. I want to achieve when I click on a button, my views will act on the corresponding file, and shows the results in another html like picture below.
How can I give each button specific parameters from my models? and how to get the parameter in my views.
I tried this code, but failed to get it. is this right?
<button type="submit" class="btn btn-info btn-xs" name={{item.description}}></button>
You must do something like that:
You should add new route for your new page to routes.py:
from . import views
urlpatterns = [
...
url(r'^new-page/$', views.new_page_view, 'new_page'),
]
after that your views.py must have your view function, that will execute when you go to url /new-page/
views.py:
from django.shortcuts import render
def new_page_view(request, question_id):
return render(request, 'path/to/your/template')
You can read more about render() there
In your template (When you want to add your link button) you must add following string:
Link to new Page
Something loke that you must do with your project.
More about this you can read there
I hope this answer will help you

Categories