django powering multiple shops from one code base on a single domain - django

I am new to django and python and am trying to figure out how to modify an existing app to run multiple shops through a single domain.
Django's sites middleware seems inappropriate in this particular case because it manages different domains, not sites run through the same domain, e.g. : domain.com/uk domain.com/us domain.com/es etc.
Each site will need translated content - and minor template changes. The solution needs to be flexible enough to allow for easy modification of templates.
The forms will also need to vary a bit, e.g minor variances in fields and validation for each country specific shop.
I am thinking along the lines of the following as a solution and would love some feedback from experienced django-ers:
In short: same codebase, but separate country specific urls files, separate templates and separate database
Create a middleware class that does IP localisation, determines the country based on the URL and creates a database connection, e.g. /au/ will point to the au specific database and so on.
in root urls.py have routes that point to a separate country specific routing file, e..g
(r'^au/',include('urls_au')),
(r'^es/',include('urls_es')),
use a single template directory but in that directory have a localised directory structure, e.g. /base.html and /uk/base.html and write a custom template loader that looks for local templates first. (or have a separate directory for each shop and set the template directory path in middleware)
use the django internationalisation to manage translation strings throughout
slight variances in forms and models (e.g. ZA has an ID field, France has 'door code' and 'floor' etc.) I am unsure how to handle these variations but I suspect the tables will contain all fields but allowing nulls and the model will have all fields but allowing nulls. The forms will to be modified slightly for each shop.
Anyway, I am keen to get feedback on the best way to go about achieving this multi site solution. It seems like it would work, but feels a bit "hackish" and I wonder if there's a more elegant way of getting this solution to work.
Thanks,
imanc

There's no reason you can't the sites framework with multiple Django installations served from different subdirectories under the same domain.

OK I have done some further digging and it seems that the Django sites framework is not suitable for the same domain but with different paths:
www.mydomain.com/uk
www.mydomain.com/au
etc.
The two other options are an apache/wsgi set up where a separate wsgi and settings.py is referenced for each subdirectory. This seems a bit cumbersome; I don't really want to have to be reconfiguring apache each time I deploy a new shop. Also it'd make maintaining the local dev, online dev, staging and live versions of the site more hassle.
I think given this situation the best solution is to look at a middleware class that keeps track of country code and somehow changes database settings and root urls.py. Then each app is going to have to be aware of its current base url for things like form actions and links and so on.

Related

How do I get two different Django projects to communicate?

Like the title says, I have two Django projects. Unlike other SO questions, these are totally different projects, meaning they do not share database, hosting environment, domain name, etc. This is what I want and need, total decoupling between the projects.
However, they have certain models (let's say UserProfile) from one app which I required in both projects. Also, I would like to have only one of the projects to allow sign-in, log-in, forgot/reset password functionality.
My idea is to have RESTful APIs for both of them, but I still have some questions about how to correctly achieve this:
what do I do with the duplicate models to keep them in-sync? Do I create endpoints which can be modified by the other project?
how do I proceed with single-sign-on ? Do I need a specialised server for this? I would also like to take advantage of the tools provided by Django, such as having my current user on my request object.
I have yet to find a good tutorial or some detailed explanations as to how to achieve all of these, so if anyone has any resources, please let me know.
If my question is not clear enough, please let me know with a comment.
Thank you.
Firstly, if you require the UserProfile model in both of them, and if you are not sharing the databases, then you are putting redundant data in your database i.e., same data in both database d1 and d2.
The only possible solution I could think of is have two separate databases d1 and d2 accessible by both. So this way, even if changes take place in say d1 using app1, then also you can detect these change in app2 and hence the same goes for app1 detecting changes of d2 as well.
This way when your user logs in app1, changes take place in d1 which is also read by app2 and hence app2 doesn't requires user authentication separately.
See this -> https://docs.djangoproject.com/en/1.9/topics/db/multi-db/
And this too -> Can I have two django projects sharing the same authentication model?

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.

How to setup groups (sub-sites) in Django

I'm new to Django and I come from Drupal family. There we have Organic Groups with which we can create groups of content and subsites; how do I do something like that with Django?
Say I'm making this site for my company using Django and every department in my company needs a private section on the site. For example, the design people have their own part of the website into which the back-end developers can not come in. And the back-end developers will have the same thing too.
I want to build the site in such a way that I just login into Django admin and add a new category or subsite or group (whatever the Django term is) with the same settings from other groups or with similar settings.
It depends on what you mean by "private section". You should probably try looking at it from a different angle:
Django splits a site's functionality by means of "apps". Each app does its specific thing, and gets a set of tables in the database. Apps can access each others' tables. For example, it's common for other apps to access the Auth app's user, group, and permissions tables. Is this what you mean by "sub sites"?
As for access control, users can be assigned to groups and they can have various administrative permissions assigned to them. Add, change, and delete permissions are automatically generated for each model (i.e. database table). You can also add your own permissions.
I don't think you'll be able to separate the designers from the back-end developers at the Django level. You'll need to do something else, such as maintain separate source repositories for each and merge them to create the usable site (each group would have read-only access to the other). It really depends on your teams' discipline, because these elements can get intertwined.
Django recommends that static files be served by something else, say directly from your web server, or from another machine with a simple HTTP server (no CGI/WSGI/whatever). This is because Django can only slow down static files compared to direct service. However, for testing, ther is a static page server you can enable.
Given all that, static files usually amount to CSS, images, media, and JavaScript. Of these, the back-end people might want to mess with the JS, but that's it, so this could be in the designers' repo.
The Django tree itself has the code for the site and the apps. It's almost all back end stuff. The exception is the HTML template files, located in the "templates" directory in each app. These are the files that are filled in with the context data supplied by the back-end view code. I have no idea if this is front or back end for you guys; it could be mostly back end if there's a lot of CSS discipline, but I think that's unlikely.
There are a lot of things that you can do in Django that make life easier for one side or the other. For example, template tags allow custom Python code to generate HTML to insert into the page. I use these to generate tab bars and panes, for example.
I really can't help much more without getting a better picture of what your needs are. The question is still vague. You're probably best off taking a day or two going through the tutorial, seeing what the Django perspective is, and then working out how (or if!) it fits into your needs.

Django Sites - Different urls.py for two sites

I maintain a Django webapp for a client of mine. We built it out in Django and for computer users, it's great. We now want to cater to mobile device users.
On top of a template switch, we also need things to work differently. The application will have views that work in a subtly different way but also the URL structure needs to be simplified.
I realise what I'm about to ask for violates the DRY ethos but is there a good way to split the urls.py so that half of it is for ourdomain.com and the other half is for m.ourdomain.com? If I can do that, I can add a mobile_views.py and write the new views.
Django's Sites is enabled in the project but I'm happy to use a hard-coded request.domain.startswith('m.')-style hack. Seems like that might perform better - but I've no idea how one gets the request from the URLs file.
Use middleware to detect the access to the other site and set request.urlconf to the other urlconf that you want to use.

How to host 50 domains/sites with common Django code base

I have 50 different websites that use the same layout and code base, but mostly non-overlapping data (regional support sites, not link farm). Is there a way to have a single installation of the code and run all 50 at the same time?
When I have a bug to fix (or deploy new feature), I want to deploy ONE time + 1 restart and be done with it.
Also:
Code needs to know what domain the request is coming to so the appropriate data is displayed.
The Sites framework comes to mind.
Apart from that we have Django running for multiple sites by symlinking Django to various docroots. Works like a charm, too.
I can see two quite distinct ways to do this:
Use one database and the sites framework. Every post/picture/whatever model is connected to a Site and you always filter on Site. This requires a separate settings file for every database.
Use one database for each and every site. This allows different users for every site, but requires duplication of everything that is stored in the database. It also requires a separate settings file pointing to the correct database.
Either way, you do not duplicate any code, only data.
--
If you need to do site-specific, or post-specific changes to ie. a template, you should read up on how Django loads templates. It allows you to specify a list, ie ["story_%d.html", "story_site_%d.html", "story.html"] and django will look for the templates in that order.
I just ran into this and ended up using a custom middleware class that:
Fetch the HTTP_HOST
Clean the HTTP_HOST (remove www, ports, etc.)
Look up domain in a Website table that's tied to each account.
Set the account instance on the HTTPRequest object.
The throughout my view code I do lookups based on the account stored in the HTTPRequest objects.
Hope that helps someone in the future.