MIARD
MIARD

Reputation: 126

Turn Django project into MVC(Model, View, Control) Structure by move all the apps model, view file in different folder

I want to Change my project structure so that my project follows MVC structure.

Currently my project Structure:

I want to change this to:

I want to add a MVC Structure folder like above and keep all models.py in a model folder, views.py in controller folder, templates in view folder

Upvotes: 0

Views: 1201

Answers (1)

MIARD
MIARD

Reputation: 126

I have found the way to do it and I am posting this answer if someone may need it in future. All the steps that I have followed to achieve the MVC Structure:

  1. Firstly, I have created a project using django-admin command.

  2. Then I created 'MVC Structure' folder in main project folder.

                 `****************View*****************`
    
  3. I have created a 'View' folder into it and keep all my static, media, templates there.

  4. Also, create forms.py and create a init.py file in View folder.

  5. In settings.py add static, media and templates directory path accordingly.

  6. Then created an App called Model using py manage.py startapp Model Command.

                  `****************Model*****************`
    
  7. Move the app into 'MVC Structure' folder.

  8. On the settings.py add "MVC Structure.Model" to the array called "Installed_Apps"

  9. Now, keep all model related code into the Model apps models.py file.

  10. As MVC Structure folder have space in it's name, I used import function to import module or packages.

  11. After doing all the things in models.py and admin.py, I did the migrations for controller app.

              `****************Controller*****************`
    
  12. The I have create another app called Controller and do all the step from 5 to 7.

  13. After that, I keep all view code into the Controller app views.py file.

  14. I successfully change the whole structure from MVT to MVC Architecture.

Import things from different app or folder: _models = import("MVC Structure.Model.models") _models = _models.Model.models

Now, I can use _models variable for working with any model. For instance: _models.User Same goes for forms, views or any other module.

Upvotes: 0

Related Questions