Django: Should I separate the web pages into different apps? - django

I am developing a business directory website, and it has
Home page
Search Result page
Listing page
I am currently at the design stage and someone suggested to separate the pages/functions into different apps, eg.
home
search_result
listing
Is this the best practise in the Django community? Or what would you do?

No. These sound like different views within a single business app.
You definitely don't want a new app per DetailView, ListView, or SearchView. That would quickly become confusing...
Think of what the app structure actually does: it adds database database table prefixes (appname_), splits models.py files and encourages its own views.py file and tests.py file.
The differences between the home, search_result, and listing views don't justify the above in my opinion.
If you want a directory/file structure that separates your distinct views, you could build a views directory in your app which contains individual search_result.py views... if they are long.

Related

Utilizing Blue prints most effectively in Flask?

I'm want to try remaking my the software I build at work which is a java/jython/python 2.5 personal hellscape of my everyday existence to a single page app (if possible) using Flask.
I'm pretty familiar with flask in terms of routing, posting forms to databases and reading from databases to template a page. But so far every time I've made a blueprint it seems to have been mostly done for separation of concern concerns, I've never reused a blueprint with a different suffix, but now I think it might appropriate for this context.
I have multiple business entities that all just have to follow a CRUD cycle. Invoices, sales orders, quotes, etc. Each of these should have exactly four routes
<entity name>/create would have a GET to return the appropriate HTML web page, and a POST that would send the form fields to the appropriate columns of the appropriate database table.
<entity name>/read/<id> would only have a GET to return the HTML page with the entity form already filled out with info from the database.
<entity name>/update/<id> would only have a POST, to update the page served in the read route if the action is take.
<entity name>/delete/<id> would only have a POST route.
With these 4 routes being the only ones required for every entity, would it be 1) recommended to use one general blue print for all these entities? If so, 2) how would I set up database table names/the folder structure to best utilize the generic blueprint?
It's worth noting too that some of the entities need not only to update the database table that shares their name, but also some multi-key tables, while others do not. I know this is somewhat a generic question so I tried adding detail, I can add further detail where requested.
Best way to set up for Blueprints:
Put all python files for routes, forms, background utils, and a templates folder for applicable html templates into separate folders for each of the CRUD sections you mention above.
For each folder (e.g. 'folder_name'), its init.py contains:
from flask import Blueprint
from flask_breadcrumbs import default_breadcrumb_root
bp = Blueprint('folder_name', __name__, template_folder='templates')
default_breadcrumb_root(bp, '.')
from app.folder_name import routes
The various routes.py should contain routings such as:
#bp.route('/read', methods=['GET'], strict_slashes=False)
#register_breadcrumb(bp, '.this.that', 'My Breadcrumb')
One folder up at 'app', the create_app function in 'init.py' should contain:
from app.folder_name import bp as one_bp
app.register_blueprint(one_bp, url_prefix='/<entity_name>')
# etc, for each app/<folder>
I've included Breadcrumbs into this app structure. Menu can be similarly included.

Structuring Django application

I am currently working on designing a web application to be used by researchers to conduct reviews. In this application there are two groups of users - participants and administrators.
Only administrators can start a review and can assign any user or administrator to participate in the review as an admin or a screener. The general workflow for each review will be:
Search medical databases and import thousands of references.
Screen references based on title (number of reviewers/admins Screening can be 1 or multiple). Each reviewer will screen all references. Mark each reference as included or excluded.
Screen included references based on abstract. Same as above applies.
Source full-text as PDF and store for included references.
Screen included references based on full text. Same as above applies.
Create custom forms.
Extract data from included references.
Export data
Throughout the progress of the review machine learning on all of the references will be done. We will also require comprehensive logging throughout the review.
My question is this, how can I best split these sections into django apps and how should I structure the required databases.
Provisionally, I've thought about having these databases:
Users. Stores info on screeners and reviewers and which projects a tenner and admin in.
Project. Stores basic info on each project including data extraction form. One to many relationship with references table.
References. Stores info about each reference including inclusion status and data extraction.
I don't know how to deal with the logging. How can I do this?
Is this a sensible split and if so how should I accordingly split the steps into apps.
The best thing about Django is apps that you create with manage.py startapp <myapp> . Apps gives good control of modularising the code. You are on the right track in modularising the code.
Regarding your tables users, projects and references sounds reasonable from your explanation.
If I were you, I would structure apps into something like this.
apps/
userprofile/ (users table )
project/ (projects and references tables)
activity/ (activity and notifications tables)
Regarding logging
Each activity like user edits , project edits or deletes can be captured via a post_ or pre_ signals https://docs.djangoproject.com/en/1.10/topics/signals/. User them to create an activity and based on the activity you can publish the single activity to multiple users as notifications ie., a single activity will trigger each notification to multiple users who are participants in the event.
In each app
I prefer to use following structure inside each app :
userprofile/
__init__
views.py
tests.py
signals.py # write the post_save pre_save post_delete pre_delete logics here
managers.py # take full leverage of managers, and custom querysets
forms.py
models.py
urls.py
admin.py
tasks.py # for celery or tasks which will be used by queuing systems
apps.py
Regarding version the data
Try the one which suites your requirement from here https://djangopackages.org/grids/g/model-audit/

Moving from PHP/Laravel to Python/Django

I want some clarity. I want to learn more about django and use it as replacement for php/laravel. But the default structure and convention of django confuses me a bit.
My PHP/Laravel project has 3 parts:
- Administration
- Core (Web app for regular users)
- API Service (REST-API for mobile apps)
However all of controllers, models and views are contained in a single Laravel application. I separated Auth, Admin, Api controllers into their own folders/namespaces.
One thing that confuses me is the default Django structure 1 view 1 model file. How should i go about reworking this application in Django should each of my controllers be a separate app in my django project or should I have same approach as in Laravel. 3 Django apps in one project one for admin one for core and one for api ? Where should I keep my models than since in Laravel all models are used by all 3 parts ?
My current structure:
./
./controllers/
./auth/
LoginController.php
RegistrationController.php
...
./admin/
ReportsController.php
UserController.php (Admins overview of all users)
...
./api/
HealthController.php (API CRUD for Health resource)
ExerciseController.php
HomeController.php
UserController.php (Regular users profile page CRUD)
...
./models/
User.php
Health.php
Exercise.php
...
One thing to remember about Django is that an app in Laravel doens't necessary translate to an app in Django. In Django, there are projects, and each project can have any number of apps. For example, I have a "Backup Admin" project where I manage a lot of the day-to-day issues of managing a tape backup environment. I have an app for media (that has 3 models, one for regular media, one for cleaning media, and one for media that we want to exclude from tape ejections). I have an app that represents the backup images, and another for backup jobs (to check status codes). Each sub-piece of my project goes into another app.
If I wanted to do another Django project that had nothing to do with backups, I'd make that a completely separate project, which would have a separate directory structure from my backup project. It'd have it's own urls.py, settings.py, etc.
Regarding the models piece, I put all of one app's models in the same file. For example, in my media app, I have models.py, which contains all three models that I mentioned above. This is completely optional, but I do it just so while importing these models into other parts of the project, I don't have to remember what the file names are, instead I can just do this:
from media.models import CleaningMedia,Media,EjectExclusions
Otherwise I'd have to have 3 different import statements if they were in different files. It's completely possible, but based on your preferences.
Regarding the controller, Django lets you do it either way. You have a project-wide urls.py file that you can use to control all of the traffic, or you can have separate urls.py files in each app to control that app's traffic. I prefer a single file, but that's just me. Personally if you have a lot of controller entries, you should probably split them up into app-specific urls.py files, just to keep it clean, but again, either method would work. I think of maintainability (especially with respect to teammates having to support it) when I make these types of decisions.
The admin interface is built-in, so there's not really an app for that, but you can decide which models and which apps have entries on the admin interface quite easily. Each app has an admin.py file that controls this.
A side note, for a RESTful API, you also might want to consider Django Rest Framework. It's a great piece of software, and the documentation (and tutorials) are very helpful.
Edit:
The 1 view/1 model thing again is just preference. You can have as many files as you want. The only trade off is when you import them into other files, you have to specify the file you're importing it from. That's really all there is to it. I know people who have a views/ directory, and inside there, have separate files for each view, keeping each class/function separate. Totally a matter of preference.

Where is recommended spot for storing admin customizations for Django contrib apps?

I want to add Django Sessions to my Django Admin, and I am following an SO post about this, but it is unclear where I store this code. Do I put it in an admin.py file? Under what directory?
In short, it doesn't matter. You can put the code into any of your apps' admin.py files. However, in situations like these I tend to use a generic app in my project, usually named something like utils, that exists for the sole purpose of housing code that doesn't belong to one specific app or could be used by multiple apps.
If you want to be more specific, you can create a sessions app in your project specifically devoted to this code and any other code related to session management for your project, or perhaps an existing app that is somewhat related. For example, I put customizations to the User admin in my accounts app that holds the UserProfile model.

Using django models across apps?

So in my Django project I have a few different apps, each with their own Models, Views, Templates, etc. What is a good way (the "Django" way) to have these Apps communicate?
A specific example would be a Meetings App which has a model for Meetings, and I have a Home App in which I want to display top 5 Meetings on the home page.
Should the Home App's View just query the Meetings App's Model?
It feels like that is crossing some line and there might be a more de-coupled way to do things like this in Django.
At some point your apps will have to couple in order to get any work done. You can't get around that.
To achieve decoupling as much as possible,
You need to have a Project specific app, that does all the hooking up things between each other.
Using signals from models to create new models in a decoupled apps helps. But doing too much of this, is foolish.
Should the Home App's View just query the Meetings App's Model?
Yep, that's how it's done. If you really want to decouple things, you could make your Home app use generic foreign keys, and some sort of generic template system, but there's not really a good reason to, unless you have grand plans for your home app being pluggable and working with a bunch of other different Django apps.
Writing tightly coupled Django apps is really easy, and writing decoupled Django apps is really hard. Don't decouple unless you have a reason to, and you'll save yourself a lot of work (and happiness!).
If it were me, I would make a template tag in your meeting app that produces the desired output and include that template tag in the home app's template.
That way you are only coupling them in the View portion of the MVC and makes it easier to maintain if you change your models in the meeting app.
For your specific example, I would use a Django templatetag.
Having a templatetag "display_top_meetings" in your Meetings app, and calling it with {{ display_top_meetings 5 }} from your index template, loading it first.
You can read more about templatetags here:
Django Official documentation about TemplateTags
B-List's article on writting 'better template tags'
I hope this help!
yes. I think thats a design feature. All models share a backend, so you'd have to do extra work to have two models with the same name in different apps.
Projects should not share Models