Creating model instances inside a Django template - django

I have an upload page written in Django that uses webkit calls to enable folder upload and list all files in the uploaded folder.
In my template, I have an event handler for the "drop" event, so it can iterate through the files in the folder and process them accordingly.
It would be really nice to create model instances for each of these files as this iteration happens. Is this possible within the javascript code block inside the template?
Maybe I should write a custom tag to do this? Just not sure if there is an easier way to call MyModel.objects.create(opts) from inside a template and have it do the right thing.
Would really appreciate inputs or any examples. Thanks!

i think you cannot do that from the "Tempalte", but i recomend to you build this using AJAX, your Js code will get the data from the html and then send that data to an URL and so, your View will receive that Data and create your instances and after that your view will return a HttpResponse to your js code.

Related

How are Django custom widget assets retrieved by the browser?

I have been reading this part of the django documentation : https://docs.djangoproject.com/en/3.0/topics/forms/media/#assets-as-a-static-definition
and this raised a question for me.
I think in order for the animations and actions js files to be used by the browser they have to be referenced in a script html tag.
As defining js assets in the form widget, like shown in the documentation, does not add any tag in the html template I do not understand how these files will be retrieved by the browser.
I'll answer this question in parts.
How are the files retrieved
Remember the STATICFILES_DIRS setting in your settings.py? My take will be that Django, while rendering your files through the form, will automatically append that in front of your file name and then include it in your template (more on the next part).
In other words, Django does this the same way how it handles static files in your templates, but you don't have to manually load the tags.
Does not add any tag
Have you ever noticed that, while you were working with forms, all you type are CharFields and whatever and Django automatically loads those into the body tag? I believe Django will automatically do that (which the keyword arguments can be processed differently than the rest of your form) but loads into the script tag.

Django - Is it possible to show loader until a start page is loaded?

My view function takes a long time until returning a template. So, I'd like to show something to a user while running the function.
Is it possible to show loader until a start page is loaded?
What's important is the loader should be shown when loading the first page after first visit of a user?
Thank you for reading my question.
You would have to fetch the page using JS. You could use something like Intercooler or PJAX which provides HTML attributes that show a spinning animation while loading the content via AJAX.
A better solution would be to make your page faster. There are several things you should consider:
Check that all Model fields that you are using for filtering or sorting have set db_index=True unless the tables are small (few hundred entries) or the fields are already unique or foreign/primary keys. Also check that your DB does sorting and merging in RAM not on disk (== the DB has enough RAM resources and has also the correct configuration to use it).
Sometimes, if you show a list of model instances you end up making separate DB requests per row if you access related models in your template. Again, check which statements your DB executes and have a look at Django's select_related, prefetch_related, values and values_list methods that can dramatically increase lookup performance. Make sure your template context contains all necessary data and only the necessary data (e.g. pageing, how much, or maybe you should consider a search index like SOLR or Elastic which can be integrated nicely via Django Haystack).
Load everything except heavy data at once in your main view, which also includes JS. The JS then uses AJAX to load the rest from a second Django view which returns an HTML snippet that your JS simply adds to the DOM.
It really depends on how comfortable you are with JS and how much you want to stick to HTML to make as much use of Django as possible (thinking of Django Forms for example). But first, tune your DB setup (disclaimer: I have written that article).
it's better to make a request with javascript to your Django endpoint, until you get a response back from your server you should show your loader, and when you get the response back successfully you should make display: none for loader and mak display: block for your loaded content
Create a function in views.py and send JsonResponse. URL example: http://localhost:8000/somedata
Render any other HTMLlet's say it's index.html. URL example: http://localhost:8000/home
That index.html file need to have some JavaScript, let's say main.js
In main.js make a request to http://localhost:8000/somedata and fetch data. Use async javascript that way you can easily track fetched data or not

Internal app without public URL in Django

The ultimate aim is to have a flexible mechanism in a Django web app for rendering PDF files. To achieve this I have designed a mechanism using Jinja2 for templating a TeX input file with a given dictionary. The template is served by a custom jinja loader via the Django ORM. The TeX file is then compiled using pdflatex.
I have made a separate app in Django in which the model for the LaTeX templates is defined. In this app there is a class in which the rendering takes place. In the end a HttpResponse object is created with which the PDF is returned.
For me this sounds like a classical Django view: it takes a request and delivers a response. However I would like to prevent anybody from using this view to generate arbitrary PDFs just by calling an URL.
How do I do that? Write a view without referencing it in the URL configuration and then call it directly from other views?

Simple file upload to Django via HTTP request

I'm really confused with the process of uploading a file (image or pdf in my case) to a Django app programmatically (via HTTP POST or PUT request). I've read the doc but I must admit it hasn't helped me get through. The most confusing part to me is the template (and form) : why do I need to specify a template and form in the view ?
I just want to send a file to a directory, and I'd like to know what exactly is needed in order to do so on the Django part as well as on the request part (content-type... ?)
I'd be really grateful to anyone able to show me some direction here..
You don't say what doc you're reading, so it's hard for us to tell what you mean. But if you're planning on doing a programmatic upload, you don't need a template, of course. You do however need some code that accepts the POST and processes the upload: you can do that with a form, or simply access the data in request.FILES and do what you want with it yourself.
Edit It's true that that page doesn't make any reference to uploading programmatically, because most people's use cases are uploading through the browser, via a form. But the page does explain how to handle uploaded files, which is the only bit that you need.

Tracking number of downloads in Django

I have a website where I allow people to download files, such as Powerpoint templates that they can reuse.
I added a column to the model that stores information and location of these files called 'Downloads' and in that column I'd like to use it as a counter to track how many times the file has been downloaded.
How would I go about this? Would it be a GET request on the page? Basically I just provide a link to the file and the download starts automatically, so not sure how to relay the fact that the link was clicked back to the model.
Many thanks :-)
If you create a view that handles the GET request you could put the updating code in that view. If your Django-app is not handling the uploading itself, you can create a view that simply redirects to the download link, after updating the counter in the database.
You have several ways to do this:
create a custom view, that "proxies" all files, while keeping track of downloads
create a middleware that does pretty much the same as above, filtering which requests to record
..but none of the above will be applicable if you want to count downloads of collected static files, that will be served directly by your http server, without passing through django. In this case, I'd retrieve the downloads count from the webserver logs; have a look if your webserver allows storing logs to database, otherwise I'd create a cron-running scripts that parses the logfiles and stores the count to a db, accessible from your django application.
Like redShadow said you can create a proxie view. This view could serve the files via mod_xsendfile (if you are using apache as webserver) and set a counter for the downloads.