Hyu
Hyu

Reputation: 11

import views.py from app directory

In setting up Django app, I want to import main_app/views.py in the url.py

of the main project folder. main_app folder is located parallel to the main project folder.

Here is how I am referencing to import views.py in main project folder\url.py:

import sys 
sys.path.append('../main_app')

from django.conf.urls import url 
from  django.contrib import admin
from  django.urls import path 
from  main_app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^', 'main_app.urls'), 
]

However, I am receiving ModuleNotFoundError: No module named 'main_app'

Upvotes: 1

Views: 1385

Answers (3)

Hyu
Hyu

Reputation: 11

I still get the same error of ModuleNotFoundError, but the project url dispatcher is now able to call main_app url dispatcher and I am able to load webpage.

I have updated settings.py to include main_app.

INSTALLED_APPS = [
    'main_app',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

and also updated main_app\urls.py and added from . import views

from django.conf.urls import url
from . import views

urlpatterns= [
    url(r'^$',views.index),
]

Upvotes: 0

schrodingerscatcuriosity
schrodingerscatcuriosity

Reputation: 1860

If you used

https://docs.djangoproject.com/en/2.0/intro/tutorial01/#creating-the-polls-app

python manage.py startapp main_app

You should not have a problem with the code you posted since inside a project each app created is available automatically.

As per the documentation, it should look like this:

main_project/
    main_app/
        __init__.py
        admin.py
        apps.py
        migrations/
            __init__.py
        models.py
        tests.py
        views.py

Then you add the app in settings.py:

# Application definition

INSTALLED_APPS = [
    'main_app.apps.FooConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

In case you created a custom folder, for whatever reason, for it to be accesible in the project, you have to add an __init__.py file at he root of the folder.

main_project/
    my_custom_lib/
        __init__.py
        my_custom_methods.py

Then if you want to call it

from my_custom_lib import my_custom_methods

Upvotes: 1

Jonathan DEKHTIAR
Jonathan DEKHTIAR

Reputation: 3536

You can remove it, it is useless

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from django.conf.urls import include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('main_app.urls')),
]

This should be perfectly working

Upvotes: 1

Related Questions