Kerberos
Kerberos

Reputation: 43

I'm having an error "ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package"

I'm creating an app directory for web scraping which is scrape inside my django_project. I'm having an an error in importing a class from my models.py module into my views.py module.

this is my project structure:

enter image description here

enter image description here

Here's my code inside models.py in scrape app

from django.db import models

# Create your models here.

# model -- headline (title, url, date)

    class Headline(models.Model):
        title = models.CharField(max_length=120)
        url = models.TextField()
        event_date = models.TextField()

            def __str__(self):
                return self.title

and this code inside views.py in scrape app

from django.shortcuts import render, redirect
import requests
requests.packages.urllib3.disable_warnings()
from bs4 import BeautifulSoup
from .models import Headline

# Create your views here.
def scrape():
    # Use the session to get the URL
    session = requests.Session()
    url = 'https://allevents.in/malacca/all?ref=cityhome-popular'
    # Content is basically grabs all the HTML that comes from the session
    content = session.get(url, verify=False).content

    soup = BeautifulSoup(content, "html.parser")

    # Return a list
    #item = soup.find_all('div', class_="event-item")
    for item in soup.find_all('div', class_="event-item"):
        title = item.find("h3").text.strip()
        linkhref = item.find("h3").find("a").get('href')
        date_posted = item.find("div", {"class":"right"})

        new_headline = Headline()
        new_headline.title = title
        new_headline.url = linkhref
        new_headline.event_date = date_posted
        new_headline.save()

    return redirect('/event/')

after try run python views.py from cmd this error is appeared

Traceback (most recent call last):
  File "views.py", line 5, in <module>
    from .models import Headline
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package

I also try this in my views.py

from scrape.models import Headline

but I get the following error

Traceback (most recent call last):
  File "views.py", line 5, in <module>
    from scrape.models import Headline
  File "C:\Users\USER\django_project\scrape\scrape.py", line 2, in <module>
    from .models import Headline
ImportError: attempted relative import with no known parent package

also if i change from models import Headline

Traceback (most recent call last):
  File "views.py", line 6, in <module>
    from models import Headline
  File "C:\Users\USER\django_project\scrape\models.py", line 7, in <module>
    class Headline(models.Model):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 103, in __new__
    app_config = apps.get_containing_app_config(module)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready
    settings.INSTALLED_APPS
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__
    self._setup(name)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\conf\__init__.py", line 64, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Upvotes: 1

Views: 4913

Answers (2)

Shilpa Shinde
Shilpa Shinde

Reputation: 994

testapp
   models.py
   serializers.py

serializers.py :

   from .models import Product

This worked for me.

Upvotes: 0

Stevy
Stevy

Reputation: 3387

When you want to import your model you should use the path to, in this case, models.py to specificy where Python should look. Then you can import one or multiple models by specifying their class names like this:

from <path_to_models.py> import <your_model_name>

To solve your problem, change:

from .models import Headline

to

from models import Headline

In all your files where you are importing your Headline model

EDIT

When you are using an IDE that has autofill, Pycharm for example. You can import the model in an easy way:

  1. Make sure the imported model is used in your file
  2. Remove the import line
  3. Put your cursor at the end of the model you want to import in the file
  4. Press alt + enter
  5. Click on import model

Upvotes: 1

Related Questions