MVC and django fundamentals - python

Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before. Any insight / help would be greatly appreciated!

"data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before"
Django imposes best practices on you. You don't have a lot of choices and can't make a lot of mistakes.
MVC (while a noble aspiration) is implemented as follows:
Data is defined in "models.py" files using the Django ORM models.
urls.py file maps URL to view function. Pick your URL's wisely.
View function does all processing, making use of models and methods in models
Presentation (via HTML templates) invoked by View function. Essentially no processing can be done in presentation, just lightweight iteration and decision-making
The model is defined for you. Just stick to what Django does naturally and you'll be happy.
Architecturally, you usually have a stack like this.
Apache does two things.
serves static content directly and immediately
hands dynamic URL to Django (via mod_python, mod_wsgi or mod_fastcgi). Django apps map URL to view functions (which access to database (via ORM/model) and display via templates.
Database used by Django view functions.
The architecture is well-defined for you. Just stick to what Django does naturally and you'll be happy.
Feel free to read the Django documentation. It's excellent; perhaps the best there is.

first, forget all MVC mantra. it's important to have a good layered structure, but MVC (as defined originally) isn't one, it was a modular structure, where each GUI module is split in these tree submodules. nothing to use on the web here.
in web development, it really pays to have a layered structure, where the most important layer is the storage/modelling one, which came to be called model layer. on top of that, you need a few other layers but they're really not anything like views and controllers in the GUI world.
the Django layers are roughly:
storage/modelling: models.py, obviously. try to put most of the 'working' concepts there. all the relationships, all the operations should be implemented here.
dispatching: mostly in urls.py. here you turn your URL scheme into code paths. think of it like a big switch() statement. try hard to have readable URLs, which map into user intentions. it will help a lot to add new functionality, or new ways to do the same things (like an AJAX UI later).
gathering: mostly the view functions, both yours and the prebuilt generic views. here you simply gather all the from the models to satisfy a user request. in surprisingly many cases, it just have to pick a single model instance, and everything else can be retrieved from relationships. for these URLs, a generic view is enough.
presentation: the templates. if the view gives you the data you need, it's simple enough to turn it into a webpage. it's here where you'll thank that the model classes have good accessors to get any kind of relevant data from any given instance.

To understand django fundementals and the django take on MVC, consult the following:
http://www.djangobook.com/
As a starting point to getting your hands dirty with ...
"...trying to find some comparable data / architectural models"
Here is a quick and dirty way to reverse engineer a database to get a models.py file,
which you can then inspect to see how django would handle it.
1.) get an er diagram that closely matches your target. For example something like this
http://www.databaseanswers.org/data_models/product_catalogs/index.htm
2.) create an sql script from the er diagram and create the database,
I suggest Postgre, as some MySQL
table type will not have forgien key constraints, but in a pinch MySQL or SQLITE
will do
3.) create and configure a django app to use that database. Then run:
python manage.py inspectdb
This will at least give you a models.py file which you can read to see how django attempts
to model it.
Note that the inspect command is intended to be a shortcut for dealing with legacy
database when developing in django, and as such is not perfect. Be sure to read the
following before attempting this:
http://docs.djangoproject.com/en/dev/ref/django-admin/#ref-django-admin

Related

Is there any non-trivial library for reducing boilerplate in Django CRUD apps?

I've been working with web2py during the last time, but for my new web application I want to experiment with Django. However, I've found that trivial CRUD forms require a lot of boilerplate. I understand that generic views give me all the logic for input to or output from a model, but I still have to do heavy HTML work and add my own logic to support filters, ordering, pagination, etc.
For example, in web2py I can just use the following code (consider it as the function-based view in Django's world) to get a feature-rich and highly-customizable CRUD view.
def manage_users():
grid = SQLFORM.grid(db.users)
return {"grid": grid}
Is there any de-facto way (apart from the admin application) or library you Django folks use to reduce the boilterplate of writing ~200 lines of code to achieve the same thing that web2py gives you for free?
Note: this is not a web2py vs. Django question. I understand they propose different philosophies and that Django is much more flexible than web2py, while web2py gives you more features out of the box. I'm just asking how is this resolved in the Django world.
Thanks in advance guys!

Django - How to port scripts to django

Before I ask my question I need to give some context:
I wrote a simple python script that read linux's syslog file and search for certain strings. I have other similar scripts like these (scripts that do file system stuff, scripts that interact with other servers and so on). Most of these scripts write simple write stuff to stdout.
I would like to port these scripts to a web-server so I could simple browser to https://server/syslog and get the same output that I would get by running the script on the command line interface.
According with my research Django seems to be a great choice. I followed some Django tutorials and I was capable of developing some basic django web apps.
My question is: Since django does not have a "controller" where should I place the scripts code? My best bet in the view, but according with djangos documentation it does not make sence.
Extracted from django doc: In our interpretation of MVC, the “view” describes the data that gets presented to the user. It’s not necessarily how the data looks, but which data is presented. The view describes which data you see, not how you see it. It’s a subtle distinction.
The description of MVC is not so important. The typical use of django is for database backed web applications. And this describes a design pattern or paradigm for that. It's completely possible to use django in other ways as well.
If you want to build a django app that is a web interface for your existing scripts, you might not even need the django ORM at all. In any case, you can put as much or as little logic in your view as you want. Your use case might just not fit neatly into the MVC or MVT paradigm. Django views are just python functions (or classes, but Django class based views are more tightly coupled with the ORM).
I would recommend:
leaving your scripts largely as they are, but wrap the parts you want to reuse as
functions. You can keep them functional as standalone scripts with an
if __name__=='__main__':
block to call the functions.
Import the functions to views.py - it doesn't matter where they are as long as your server will always be able to find them. I put mine right in the app directory.
Call the function(s) in your view(s), and return the text to a HttpResponse object which you return from the view. (I think this is more direct than creating a template and a context and calling render, but its not what I usually do so there may be some issues?)
Thats bit old code - but you will get enough idea to start - check https://github.com/alex2/django_logtail (Django_LogTail)

Django application decomposition advice

I am a Django developer with some experience. I am familiar with different best practices and controversial points of view.
Recently, while working on one project, I struggled for a while when I came upon one giant existing app. The issue isn't resolved and I'm still in progress of thinking.
The issue itself: project has a giant application, let's name it "Directory". The application is big and serves to multiple purposes:
1) Provides basic content types for the whole project
2) Provides some helping structure entities (like, Categories, Attributes etc)
3) Handles User Area dashboard views.
4) Handles basic front-end public views.
5) Handles search.
I really don't like how big it is right now. While thinking on possible way of decomposition, I came up with multiple variants. Most likely it'll be the best to do it like this:
I can create a dashboard app, a search app, a frontend functionality app (serves for displaying public content).
The biggest stopper right now is the model layer. The thing is, all of the possible apps mentioned above depend literally on the same models. In my opinion, it'll be wrong to put these models to some of the apps above and leave others without models, as it'll be non-obvious where the mentioned models should live.
The possible solution, in my opinion, will be to create a separate app like "Content Types" or something like that, where I should put these models. But if I do it, I'll come up with apps that:
1) Do nothing but only provide models and admin. 2) Apps that don't have models and only provide functionality (views etc)
So, basically, I'm lost as I'm not sure that app that does nothing has a right to live separately (while the second point is more or less imaginable).
Can anyone please give me possible advice on how should I decompose my app to still follow the django-way of development and have a nice structure? I suspect that the issue I have appeared due to wrong design of the db-layer as well. But, unfortunately, it's too late to save it at the moment and I have to do my best at least with other parts.

Where does my controller logic go in Django?

I'm coming from an iOS background to Django. As an app developer, I'm used to clearly defined MVC architecture. My storyboard contains my views. My view controllers contain my logic, and my model exists in an object-relational mapper (ORM) framework or database.
On the web, the separation of responsibility seems less clear cut. Sure, databases and ORMs exists. HTML seems to be my views. Django Models seem to be just that. But where is the controller?
Where does my business logic live?
As the Django FAQ itself points out, Django doesn't quite follow an MVC approach, at least not in a straightforward way. (They argue that Django itself is the controller, but that's not really how I think about MVC.)
The "controllers" in Django are basically what Django calls views. So you have your model classes, which are the M obviously. The templates/HTML are basically the V in MVC. Django views (either functions or classes) are effectively callbacks that run for a particular URL, and they tend to be where a lot of the logic is. So for example, you'll have a Django view called get_foo_bar that runs when someone makes a GET request to /foo/bar, and the Django view effectively becomes the C in MVC.
So long story short, your logic often goes in your Django views.
Django has controllers that are stored in views.py files, this naming leads to some confusion for newbies with some sort of MVC background, you can read about it here: https://docs.djangoproject.com/en/1.8/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names

Is MVC a good design pattern for a GAE app?

my GAE app is currently setup with the following filenames
main.py (2 main models and logic for creating and updating the models)
i18n.py (user interface logic how to view objects with i18n)
reports.py (cron-based reporting script)
I think the names are clear enough but I am considering to follow a model-view-controller pattern so renaming these three files to model.py view.py controller.py is what I consider an option to follow a more standardized convention. Do you agree that this type of modularlization towards a MVC convention is the reasonable way to go in this case, do you need more information what's my app: I've got a lot of code that's functional towards the user which is code I feel is right to refactor in a way that follows a generally accepted design pattern such as MVC, publisher-subscriber, factory and more. In this case I think the MVC design pattern is appropriate. Do you agree or suggest other code and data treatment? Thanks for any comments and discussion.
You are miss-understanding MVC. Model, View, Controler is in three parts.
Model - contains the business logic. Knows how to read/write to the database.
View - Contains the display logic. Knows how to fetch data from model and display it to the user.
Controller - understands user gestures, loads/finds the correct model and view and tells them what to do.
(In a web environment, the view should unpack the data from POSTs, and the model should validate it).
You have M and C in main.py, and propably V in i18n.py and main.py (hard to tell). The cron-run reports are external to MVC.
Just renaming the files will not gain you anything, but will confuse any other maintainer.
If you are proposing to make significant changes to your code without a test suit to proptect you from introducing errors, then I must point out that such an action is not wise.

Categories

Resources