Im coming from using other MVC based frameworks, and going into Django, it seems a little awkward to what im used to. For example, in other MVC based frameworks. my layout might be like so:
root:
- config (houses the config files (like settings), url.conf, db connections, etc.)
- controllers (houses the main logic of each section of the site. The middle ground between views and models)
- models (handles all the data to be validated and anything that interacts with the database. declares the DB structure. each model a class, each attribute a db field. in django, a template?)
- views (the html displayed to the end user, put together by the controllers)
- tests (all the tests)
- plugins (3rd party apps you install into yours.)
- uploads (user uploaded files)
- public_html (the actual public facing files)
-\ css|js|img (the various static file types for page manipulation)
-\ index.html
That is what im used to, and it seems like django does things very differently. Where before if I had a poll app i would have:
controllers/PollController.py
models/Poll.py
views/poll/index.py
and that would create the poll table in the db. But in Django, how would I do this? Is this an acceptable layout? From what I have read, the above would be more like this:
root:
- project (this would be the main app, and what glues everything together)
--/ settings.py
--/ urls.py
--/ templates/
- apps
-/ Poll
--/ models.py (i would have no Poll.py model, so it would all go in here)
--/ urls.py (any url.conf specific to this model would go in here)
--/ templates/ (the various views for this app)
while this does makes sense in some ways, it just feel alien to me. Is there any benefit to this type of layout over a traditional mvc layout described in the first example? Is there another preferred layout beyond this? The purpose of this 'project' is that the core will be a basic framework for my own use and I have a few different 'apps' that i will create for each use of this framework. in the old version each application would just extend the main one by being a plugin in that directory.
As a background note, most of my experience is in php and the various frameworks from that worls (cakephp, yii, mostly), if that makes a difference. This will be my first main project in python/django. i just want to get it right.
The biggest benefit is that apps are modularized. You can remove your Poll application by deleting one directory instead of hunting through several directories deleting each piece. The flip side is if you found a Poll application somewhere that you wanted to use you can just drop in the one folder and you're good to go.
If you approach the idea of a site being a conglomeration of several individual and mostly distinct "apps" with some glue to hold them together then this organization makes much more sense.
Is there any benefit to this type of layout over a traditional mvc layout described in the first example?
Yes.
What you appear to be calling "Traditional MVC" is just another framework. It's not magically better or more right. It's just different.
Is there another preferred layout beyond this?
There are probably hundreds of ways to do this. Django chose one that fits nicely with Python and web applications.
i just want to get it right.
Then do this.
Discard your preconceptions left over from other things you've done.
Start fresh and empty with Django like a complete beginner.
After you've learned your 6th framework, you can then (and only then) compare and contrast the six frameworks you've learned. Until you've learned six, each one has to be taken as new, complete, different and unique.
Don't compare and contrast yet.
Just take Django as Django and do things the Django way.
(For more metaphorical advice, read about the music of Django Reinhardt; he had a unique view and a unique approach to the guitar.)
Notes
root # doesn't mean anything
config -- Doesn't exist.
controllers -- Doesn't exist.
models -- A Python module with the class definitions for the persistent objects. Maps to RDBMS schema. Can have model-specific tests.
views -- A Python module with view functions that respond to requests and create responses.
test -- A Python module with View-specific and template-specific tests.
plugins -- Doesn't exist.
uploads -- Runtime, not development of the application.
public_html -- Does not exist.
css|js|img -- Static "Media" files. Runtime, not development.
index.html -- Does not exist.
Stuff you omitted
templates -- your HTML template pages, used by the view functions.
admin -- admin bindings for the default admin site. Relies on modules and forms.
forms -- form definitions; these are classes that produce forms used for input validation.
urls -- mappings from URL paths to view functions.
settings -- module with default database configuration, middleware, etc.
Related
After some years developing web apps using ruby on rails, I decided to give Django a try, however it seems that I'm missing something, which is how to structure large project, or any project in general.
For example, in rails we have a models folder which contains model classes, each in a separate ruby file, a controllers folder which contains controller classes, again each in a separate ruby file.
However, in Django it split the project into independent apps, which can be installed independently in other Django project, each app has a models.py file which contains all the models classes, a views.py file which contain all the views functions.
But then how to group functions in views like rails? That is one controller per each model.
In general how to structure my project when it contains one large app that can't be separated into multiple independent apps? I want for example to have a view index function for each model, but how to do this if all functions are in one file?
If my project is about selling cars for example. I should have index function that maps to /cars, another index function to map to /users, etc...
I searched the web but couldn't find a suitable answer.
It is unclear to me how to structure Django app, so any help will be appreciated.
As mentioned in #shanksfk's answer, Django is very flexible in folder arrangements. You don't have to follow the default app structure. When I create a purely backend Django project (with DRF), I usually have 3 base apps:
api - where modules, serializers, and urls are stored
core - the default app (the one that has the name of your Django project)
db - where models are stored
Then as I expand, I can add a folder dedicated for the helpers, utils, and possibly abstraction layers for external services. I recommend reading more about Domain-driven Design to get an idea on how to structure your project. You can also check other Django projects for inspiration:
django CMS
Baserow
Django API Domains
In short, Django is a Model-View-Template framework and Rails is a Model-View-Controller framework.
In Django we store controllers(sort of) in views.py for each specified app, while in MVC framework such as Rails store it in controllers. In Django, you also have to create your own HTML template separately which some people may find it tedious but its easier to work with other frameworks such as Vue or React due to that separation.
This is general comparison I found on the net.
However, to answer your questions on folder structure. Basically Django is very flexible on folder arrangements, it really depends how you want to design the project structure. Normally what I'd do is keep every app in the main folder (project folder). This way you wont mess with the venv setup
I want to replace the default Django Admin templates with a completely revamped bootstrap version. The data in the Dashboard should be populated from the DB. How do I work with templated files ? Which files should be overriden ? In which template tag does HTML code go ?
From django docs on admin:
The admin’s recommended use is limited to an organization’s internal management tool. It’s not intended for building your entire front end around.
It's possible to change templates to do what you want, but that will be very complex - you have to basically rewrite most of the templates, get to know how it is working internally and probably change that too to your own design (after all, you are going to show specific details, like charts, data and so).
You will faster to achieve results if you going to build your own app, that will work exactly like you need without multiple fixes. Does it have to use js frameworks depends entirely on your requirements. Usually they are much more simple for admin backends, that are going to be used by owners, not clients. Anyway, if you don't have experience or knowledge in this, you will probably better off with just plain static django templates.
Django admin is just a same app as the ones you build, so limitations will be the same. Security wise, it doesn't offer much that you can't do yourself - make sure you have permissions set in models/views. Read more about security in django.
From functionality point of view, django admin just comes with CRUD access to your models, which can be done quite quickly. Once you past that, you will have much easier time adding functionality to your own app instead of overriding django admin.
Overall, I advise you to build your app for CMS-like admin panel. JS frameworks is neat, but that require burden of multiple additional tests (with api mocks), constant swapping between adding api / writing a component and much higher time consumption overall.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Note: I am not a proper python programmer... but I use python extensively. I do things like write classes with inheritance, use iterators and comprehension, etc. My point is that I do not have a full grasp of the language, e.g. what exactly constitutes an python object, why __init__.py is needed other than to specify a module, etc. In relation to Django, I have written multi-app sites (with the help of S.O.) and have really enjoyed Django's templating system, blocks, and how they can be nested. Now are my apps fully decoupled and reusable? That this is subject of this post.
I state this disclaimer because a lot of the Django resources seem to assume that one knows these things. This makes understanding some of the documentation and S.O. questions difficult for a person who is just an (subpower)-user. So please answer this question with that in mind.
Question
These questions are inspired by both the question When to create a new app with startapp in django? by #håkan and the answer given by #antti rasinen which links to James Bennett's 2008 PyCon presentation
A few key points from Bennett's presentation are:
sites are a collection of apps
an app does one thing and one thing well
Which directs me to his section "Project coupling kills re-use" that mentions:
Single module directly on Python path (registration, tagging, etc.)
Related modules under a package (ellington.events, ellington.podcasts, etc.)
Question 0
A "module" in this case is just an app made of other apps?
Question 1
(Apps with related functionality and shared models )
What should I do when apps share models?
In Barrett's slides he implies that user registration and user profiles are distinct and should be distinct apps. (He certainly states that profiles have nothing to do with user registration).
So if I wanted both, would my project have two apps like:
user-registration
user-profile
even though the app user-profile will need the user model from user-registration? Or do I make a single app (module):
user-app
registration
profile
which contains both?
Question 2
(Apps with distinct functions but shared models)
Extending the example from question 1, lets say that my main app (or some other app that is used by the main app) utilizes some aspect of the user model (e.g. recently active members if it was a chat site).
Clearly my main app gets this information from the user model. Does my main app now get bundled under the user-app module?
This may not be the best example, but the point is as follows:
I have two apps app-dependency and app-needs-dependency, where each app does its one thing and one thing well... It is just that app-needs-dependency needs information from app-dependency. What do I do in this case, if everything else about app-needs-dependency is completely decoupled from app-dependency (so it could be used in other projects)?
Question 3
(writing apps for flexibility)
Now I have my site with its couple of apps. Each app does its one thing and does it well. The main app serves as the landing page/ overview in this case.
I want all my other apps to use / inherit the static and template files of the main app.
Where do I store all the static files and templates? In the main app and set that as the default for the other apps? Or where should these static files / templates (e.g. base.css, base.html) go?
Do I make a copy of these files for each other app, so they can be run even though this is redundant?
Which makes my app more flexible?
Question 0
A "module" in the Python context is simply a file that contains definitions and statements. So "related modules under a package" really just means "split your code into separate files based on what the code is doing".
Describing it as "an app made of other apps" is to start confusing Django's concept of an app with Python's concept of a module (which, as stated above is just a file that houses some code).
Question 1
What should I do when apps share models?
You should still try and stick to the "apps do one thing and do it well" maxim. In this case separate profile and registration apps seems like a good idea - because they have quite different functions. A registration app is going to contain the logic for allowing users to register on your site. A profile app is all about what information you will store about a user.
There is nothing wrong with these two apps having a relationship to each other - see below.
Question 2
Let's say that my main app (or some other app that is used by the main app) utilizes some aspect of the user model (e.g. recently active members if it was a chat site). Clearly my main app gets this information from the user model. Does my main app now get bundled under the user-app?
No. It should still be a separate app, with links to the other app.
The user model is actually a good example. Django allows you to specify a custom user model that lets you store whatever additional data you want about a user.
Now, there are loads of third party apps out there that do things like registration, authentication, etc for users. They are designed to work with any user model, not just Django's default one. The way they do that is to use get_user_model() wherever they need to reference the User model, instead of directly importing django.contrib.auth.models.User.
This means that you can use those third party apps with whatever user model you have defined for your own project.
Django's get_user_model() utility is there to serve a very common use case. However the same principle can be extended to your own apps. If there is a dependency between your apps that you think should be swappable, then you can provide a way to swap it out - e.g., a setting/configuration that allows any other project using your app to specify an alternative.
There are hundreds of examples of this kind of configurability in the Django ecosystem. For example, Django itself ships with its own django.contrib.auth authentication app. However if you want to implement your own authentication logic, you don't have to reimplement the entire auth app again yourself (that would be a huge pain). Instead you specify an an authentication backend that it's auth app will use to authenticate. The auth app is designed to allow any project to swap out a core piece of its functionality with minimal effort.
So in your main app, you might define a setting that controls which profile model to use. This means that if someone else wants to use a different profile model, they simply change this setting and they're all set. They are no longer tied to your profile app.
For example - let's say you have a main app that has a view that displays some user data, but also provides a link to a registration view that is provided by a different app. You want anyone else to be able to use that app regardless of what registration app they are using. So you can make this view resuable like so:
In main/views.py:
from django.contrib.auth import get_user_model
from django.conf import settings
from django.urls import reverse
class UserDetailView(DetailView):
# First of all, we're using get_user_model so that a project
# can specify whatever user model it wants, and still use this
# view.
model = get_user_model()
def get_context_data(self, *args, *kwargs):
ctx = super().get_context_data(*args, **kwargs)
# We want to add a link to a registration view into this template context.
# But we want this to be configurable.
# Your REGISTRATION_URL would be something like 'profile:registration'
ctx['registration_link'] = reverse(settings.REGISTRATION_URL)
return ctx
Question 3
The main app serves as the landing page/ overview in this case. I want all my other apps to use / inherit the static and template files of the main app. Where do I store all the static files and templates?
You should store the templates in each respective app. If your main app is providing the base templates, then those should reside in the main app.
If your profile app is then providing a registration view, then the template for that should live in the profile app. There is nothing wrong with it extending the base template from the main app - this can easily be overridden by a project that wants to.
It's fine to make assumptions about how two apps are related to each other - as long as you're careful to allow overriding of those assumptions.
I have to admit your question is not a technical one but rather a conceptual and dogmatic one.
No answer is absolute and universally valid and every detail about how you project is structured and should behave can change the perspective.
As you wrote, each Django app does one thing and it does it well.
I would extend that to the point that each app should contain no more than one Model and at most, it's closets dependents.
Ex: the Product with it's Category, Color, Image
"What Changes together, stay together"
You will have plenty of logic to cover inside that app with only these ones.
Try to look at Django framework as a tool to create your project..this is the final goal...but if you want also to create reusable apps try to create them as independent as possible, or at least dependent to some Django features:
ex: a reusable app and totally independent would be an app that only requires User Model, Sessions, Groups included in Django. You get the idea of dependent but still autonomous app.
An app is part of a project after all...either here or in other part after you build it. Look at it as if it would be a simple function...can run alone or can depend on other functions result...at what point you keep everything inside one function and when you decide to split them in 2 separate ones.
So:
Question 0:
An app is the smallest piece that can run by it's own...having models, views, templates, urls, static files.
It can depend also on other apps...so answer is YES
Question 1:
Always keep things separate by functionality...
User Auth is dealing with user creation and their authentication
User Profile is dealing with personal data of the User
Question 2:
Nothing gets bundled. Everything stays at the same level as 2 different but dependents apps
Question 3:
You can do as you wish.
You can do static as a central place and templates specific for each app or everything central.
No right answer here but only what scales well for your project.
This is a great question and it covers all the questions associated to structuring the project I asked myself when i started working with Django.
Question 0:
Yes, in that case, a module is an app which consists of serveral apps (ellington.events, ellington.podcasts).
Question 1, Question 2, Question 3:
Django is a general purpose, full stack web framework. Since it is general purpose, a lot of it depends on your particular use case. You need not have an entire Django project follow a particular structure (if you want to achieve code reuse AND functional decoupling AND relational decoupling).
With that said, if you can prioritize what you want to achieve, you can go with one pattern over the other.
Let's take the example of Blog.
Code Reuse:
For achieving maximum code reuse, you have to identify what parts of your project is worthy of reuse. Once you have done that, you can set your project structure accordingly.
Project Structure:
BlogProject
-CommonApps
--AbstractUser(abstract class (just like it's java counterpart) )
--AbstractActivity
--AbstractComment
--AbstractArticle
-ProjectApps
--BlogUser (extends AbstractUser)
--BlogActivity (extends AbstractActivity)
--BlogComment (extends AbstractComment)
--BlogArticle (extends AbstractArticle)
The functionalities that can be shared across multiple projects should be implemented in abstract apps, and the ones specific to project can be implemented in Project apps.
Relational Decoupling:
You can create apps to represent the relations between two other apps, and implement all the functionality involving two different apps in that relation.
Project Structure:
BlogProject
-User
-UserActivityRelation
-Activity
-Article
-ArticleCommentRelation
-Comment
-UserCommentRelation
-and so on
Functional Decoupling:
This is the most common practice - create apps for particular functionality.
Project Structure:
BlogProject
-Article
-Activity
-User
-Comment
The point I am trying to make here is that the choice is yours. In more complex projects, it won't be so white and black.
You, depending on what an "app" means to you, and what you want it to do in a particular project and other projects, can decide on a particular structure.
Django keeps it abstract to give you the ability to do that.
I always go for an app setup that makes sense to that particular project. In a project not all apps are reusable. And having flexible/reusable apps does not make sense in all the cases.
As a general rule of thumb, Django devs say an App should be something whose functionality can be described with one sentence. But Django is designed so that you can bend the rules for your projects if you have to.
DISCLAIMER: Functional decoupling and relational decoupling aren't textbook terms. I just used them to describe what I meant here.
I have been reading some django tutorial and it seems like all the view functions have to go in a file called "views.py" and all the models go in "models.py". I fear that I might end up with a lot of view functions in my view.py file and the same is the case with models.py.
Is my understanding of django apps correct?
Django apps lets us separate common functionality into different apps and keep the file size of views and models to a minimum? For example: My project can contain an app for recipes (create, update, view, and search) and a friend app, the comments app, and so on.
Can I still move some of my view functions to a different file? So I only have the CRUD in one single file?
First, large files are pretty common in python. Python is not java, which has one class per file, rather one module per file.
Next, views, even as the standard used, is a python module. A module need not be a single file. It can be a directory containing many files, and __init__.py
And then, views.py is only a convention. You, the application programmer are referring to it, and django itself doesn't refer anywhere. So, you are free to put it in as many files and refer appropriate functions to be handed over, the request to, in the urls.py
They don't have to go in views.py. They have to be referenced there.
views.py can include other files. So, if you feel the need, you can create other files in one app that contain your view functions and just include them in views.py.
The same applies to models.py.
Django apps lets us separate common
functionality into different apps and
keep the file size of views and models
to a minimum? For example: My project
can contain an app for recipes
(create, update, view, and search) and
a friend app, the comments app, and so
on.
I don't know about the "to a minimum" part - some apps are just big in views, others big in models. You should strive to partition things well, but sometimes there is just a lot of code. But other than that, this is a fair summary of Django apps, yes.
I also very much dislike long files.
Of course what you read in the other answers is true, but I exploit some very nifty python equivalence:
views.py
and
views/__init__.py
are pretty much functionally equal - by that I mean that if the both contain def my_view() then
from views import my_view
will work the same in both cases!
From there it's easy to structure your long files into smaller ones, yet keeping the naming convention that every django developer is used to:
views/__init__.py
views/largemodel_view.py
then in __init__.py don't forget to import the views from largemodel_view.py.
With large applications I do the same with models though you must remember to set the Meta.app_name:
class MyModel(models.Model):
...
class Meta:
app_name = 'yourappname'
because django will not pick it up magically otherwise for the Admin (but it will still load it, thanks to Python!)
so my apps usually end up looking something like:
project/settings/__init__.py
/..othersettings..
/app_1/models/__init__.py
/...
/views/__init__.py
/...
/templates/
/static/
urls.py
/urls.py
etc.
though of course there's no limit (urls could be split too, etc.etc.)
I just wanted to try to build a project with django. Therefore I have a (basic) question on how to manage such a project. Since I cannot find any guidelines or so on how to split a project into applications.
Let's take a kind of SO as an example. Which applications would you use?
I'd say there should be the applications "users" and "questions". But what if there was a topic system with static articles, too. Maybe they also could receive votes.
How to build the apps structure then? One app for "questions", "votes" and "topics" or just one app "content"?
I have no idea what to do. Maybe it's because I know not very much about Django yet, but I'm interested either...
There aren't hard-and-fast rules, but I would say it's better to err on the side of more specialized applications. Ideally an application should handle just one functional concern: i.e. "tagging" or "commenting" or "auth/auth" or "posts." This type of design will also help you reuse available open source applications instead of reinventing the wheel (i.e. Django comes with auth and comments apps, django-tagging or django-taggable can almost certainly do what you need, etc).
Generic foreign keys can help you decouple applications such as tagging or commenting that might be applied to models from several other applications.
You should try and separate the project in as much applications as possible. For most projects an application will not contain more than 5 models. For example a project like SO would have separate applications for UsersProfiles, Questions, Tags (there's a ready one in django for this), etc. If there was a system with static pages that'd be a separate application too (there are ready ones for this purpose). You should also try and make your applications as generic as possible, so you may reuse them in other projects. There's a good presentation on reusable apps.
Just like any set of dependencies... try to find the most useful stand-alone aspects of the project and make those stand-alone apps. Other Django Apps will have higher level functionality, and reuse the parts of the lowest level apps that you have set up.
In my project, I have a calendar app with its own Event object in its models. I also have a carpool database set up, and for the departure time and the duration I use the calendar's Event object right in my RideShare tables. The carpooling database is calendar-aware, and gets all the nice .ics export and calendar views from the calendar app for 'free.'
There are some tricks to getting the Apps reusable, like naming the templates directory: project/app2/templates/app2/index.html. This lets you refer to app2/index.html from any other app, and get the right template. I picked that one up looking at the built-in reusable apps in Django itself. Pinax is a bit of a monster size-wise but it also demonstrates a nice reusable App structure.
If in doubt, forget about reusable apps for now. Put all your messages and polls in one app and get through one rev. You'll discover during the process what steps feel unnecessary, and could be broken out as something stand-alone in the future.
A good question to ask yourself when deciding whether or not to write an app is "could I use this in another project?". If you think you could, then consider what it would take to make the application as independent as possible; How can you reduce the dependancies so that the app doesn't rely on anything specific to a particular project.
Some of the ways you can do this are:
Giving each app its own urls.py
Allowing model types to be passed in as parameters rather than explicitly declaring what models are used in your views. Generic views use this principle.
Make your templates easily overridden by having some sort of template_name parameter passed in your urls.py
Make sure you can do reverse url lookups with your objects and views. This means naming your views in the urls.py and creating get_absolute_url methods on your models.
In some cases like Tagging, GenericForeignKeys can be used to associate a model in your app to any other model, regardless of whether it has ForeignKeys "looking back" at it.
I'll tell you how I am approaching such question: I usually sit with a sheet of paper and draw the boxes (functionalities) and arrows (interdependencies between functionalities). I am sure there are methodologies or other things that could help you, but my approach usually works for me (YMMV, of course).
Knowing what a site is supposed to be is basic, though. ;)