Tree in generic template - python

I am new with Django but I understand that the aim is to never reinvent the wheel. I am developing an application to supervise a factory and in all the html file I need to implement a tree representing the structure of the factory.
-> Factory
-> Production Area
-> Machine 1
-> Machine 2
etc
So I decided to put this tree structure in the base.html file and extend it on every others html files.
The problem is that I need to extract the element from my database, using the views.py files in order to call the render function to send it to the html file.
My question is how to access this data in the base.html, because he dont got any views.py to use a render function.
Thanks, Baptiste.

If you want something to show up in every template of your website (a tree in your case), you can put it in a base template and inherit from that template.
I personally (and many others as well) use a 3-level template structure. You can find an example/explanation in this GitHub repo and this post. Feel free to adapt the idea to your needs.
So in your case you could put your tree structure (the factory structure/layout) in your base template. If the data of the tree has to be fetched from the database, then you could use a custom context processor so that you don't have to repeat the tree-fetching-code in every view.

Related

Proper project structuring

I've recently started as the sole developer on a Django project. I'm currently working on updating an endpoint to including validation for incoming PDF documents.
The simple validation function follows:
def is_valid_certification(stream: BytesIO) -> bool:
pdf = PdfFileReader(stream)
page: PageObject
for page in pdf.pages:
if page.extractText().find(<search string>) != -1:
return True
return False
My question is, where is the most pythonic place to store this bit of code? Keeping all the logic within the POST handler seems messy and it's not generic enough to be considered a utility.
You can follow the fat model concept and have this function in the model that is responsible for this.
You could also create a services.py file in your app for functions and services that are specific to that particular app.
Any functions that are generic to the the project can go into the app named after project
I don't think there's a single correct answer for this, but I find that as my views.py files grow, the best way to keep them lean is just to move the business logic to other files as makes sense. Code doesn't necessarily have to be reusable to be abstracted; sometimes you just don't want a file to be 2,000 lines long, and you want a logical separation of functionality (e.g., views.py really just focuses on collecting data for rendering and all the heavy lifting is done in other modules).
For larger apps, especially with a lot of admin site customization, I'll often have the following files for a single app:
admin_form_processing.py
admin_forms.py
admin_inline_forms.py
admin_utils.py
form_processing.py
forms.py
urls.py
utils.py
views.py
some_file_that_processes_view_logic_1.py
some_file_that_processes_view_logic_2.py
etc.
I also often create an app called core or utils that has no urls/views but contains modules for general utility functionality (e.g., form_utils.py for form-related utilities that are used across multiple apps).

Pelican: customizing index.html by reading metadata from YAML

I am looking to build a personal CV site using Pelican. Since I am not really targeting a blog site, I want a somewhat different index.html and it should be easy to maintain. I know I can directly make the template the way I want at the very least, but then it involves directly modifying html which defeats the purpose of using a static content generator.
I am thinking to represent the data using a YAML file, and pass in extra data to jinja2 only when index.html is being generated. So my question is, how should I configure a plugin so that it only applies to some specific files and alters the output?

Creating reusable forms/views in Flask

I am not sure what would be the best route to go down, or I may be missing something obvious.
Example I can give is I have 'person' model and associated form, and view created to add a new 'person'. This all works great. What I would like to do though is use this 'view/form' in a master page with other similar 'views/forms'. With each part being able to add/edit or delete a record from each sub view/form.
So I have all functionality done, just don't know how I can create this master page with child objects, but these child objects can be their own page as well, type of thing.
The idea being that the master page structure is flexible and can accommodate various elements based on the context the user is in.
Should I be looking at blueprints or Jinja2 and its template structure. Or is it how I am handling routes within the main app.
Apologies if this is too vague.
I have done this using AngularJS ng-include directive. You can include whatever html you want, but be careful with Jinja2. If the html you are trying to include contains any script tag it will crash. See my question here. If you need to import a form that needs a script tag you will need to make sure it is not loaded when you are pushing it with Angular. Since it makes a xhr request, you can use flask.request.is_xhr to check if it is angular or the user that is requiring the form. You cannot forget to add this to your angular app
Otherwise is_xhr will always return false.
myAppModule.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);
Be careful with base_ templates as well, since they usually load script tags. You can pass the base template through your flask route, and make it extend a blank base html when the request is made through angular. I wish I had my example here, but I am on the bus. Let me know how far you got.

How to implement Symfony Partials or Components in Django?

I've been developing in the Symfony framework for quite a time, but now I have to work with Django and I'm having problems with doing something like a "component" or "partial" in Symfony.
That said, here is my goal:
I have a webpage with lots of small widgets, all these need their logic - located in a "views.py" I guess. But, how do I tell Django to call all this logic and render it all as one webpage?
It sounds like what you're looking for is something like custom template tags...
You can write your own set of tags that process custom logic and return template chunks that are reusable in a very widget-like way.
Assuming you are going to be using the components in different places on different pages I would suggest trying {% include "foo.html" %}. One of the (several) downsides of the Django templating language is that there is no concept of macros, so you need to be very consistent in the names of values in the context you pass to your main template so that the included template finds things it's looking for.
Alternatively, in the view you can invoke the template engine for each component and save the result in a value passed in the context. Then in the main template simply use the value in the context.
I'm not fond of either of these approaches. The more complex your template needs become the more you may want to look at Jinja2. (And, no, I don't buy the Django Party Line about 'template designers' -- never saw one in my life.)

Django.contrib.flatpages without models

I have some flatpages with empty content field and their content inside the template (given with template_name field).
Why I am using django.contrib.flatpages
It allows me to serve (mostly) static pages with minimal URL configuration.
I don't have to write views for each of them.
Why I don't need the model FlatPage
I leave the content empty and just supply a template path. Therefore I can take advantage of having the source in a file;
I can edit the source directly from the file system, without the help of a server (such as admin).
I can take advantage of syntax highlightning and other editor features.
With the model I have to maintain fixtures for flatpages.
So the data for the same entity is in two seperate places.
If I move the content inside the fixture it'll be more difficult to edit.
Even if fixture maintenance was a non-issue I'd still need to dump and load these fixtures again and again during development.
What I am looking for
Basically; getting rid of FlatPage model while maintaining contrib.flatpages functionality. I don't have a clear idea how this should be solved. If there's a clean way of modifying (like add_to_class) FlatPages to get the information somewhere other than the database I'd prefer that. Maybe the metadata can be inserted to the templates and then a special manager that reads this data would replace the default manager of FlatPages.
If I don't prefer manual editing over admin functionality for flatpages, how can take the database out of the equation?
Using the direct_to_template generic view would be a lot simpler. You could use the passed in parameters on one view to specify the actual template in urls.py, if you don't want to add an entry for each page:
r'^foo/(?P<template_name>.+)/$','direct_to_template', {'template': 'foo_index.html'}),
Then import the template in your foo_index.html:
{% include template_name %}

Categories