NameError: name 'Model' is not defined after importing models in a newly created file

10,277

Solution 1

To fix your trouble(cross imports) you need to make import inside functions:

def process_bill(bill_type, liquor_license, cost_centre, account_number_list, description, license_category,user,amount,schedule_type):
    from .models import LiquorCostCentre, LiqourBillTrack
    # YOUR CODE HERE

and REMOVE import * from top of the utilities.py and of cause if you need some others models in your utilities code, put they import inside functions.

Solution 2

Issue is of circular import.

You are importing from .utilities import (calc_expiry_date,convert_date) in models.py and then in utilities.py, you are importing

This is a classic case of circular import.

Solution is to import locally i.e

def process_bill(bill_type, liquor_license, cost_centre, account_number_list, description, license_category,user,amount,schedule_type):
    from models import LiquorCostCentre, LiqourBillTrack
    cost_centre_obj, _ = LiquorCostCentre.objects.get_or_create(cost_centre_id=cost_centre)
    bill = LiqourBillTrack.objects.create(
        fee_choice=schedule_type,
        bill_type=bill_type,
        cost_centre=cost_centre_obj.cost_centre_id,
        balance=float(              amount),
        description=description,
        created_by=user,
        year=CURRENT_YEAR,
        liquor_license= liquor_license

    )
    [bill.accounts.add(account_number) for account_number in account_number_list]
    account_values = []
    account_list = bill.accounts.all()
    account_total = [account_values.append(acc_value.amount) for acc_value in account_list ]

    bill_total =sum(account_values)
    bill.total = bill_total
    bill.balance = bill_total
    bill.ref_no = 'LIQ-' + str(NOW.year) + str(NOW.month)+ str(bill.id)
    bill.bill_no = bill.ref_no
    bill.save()
    return bill
Share:
10,277

Related videos on Youtube

Philip Mutua
Author by

Philip Mutua

BY DAY: compose python/typescript/javascript stuff @ work I do different diverse projects. An interesting project recently caught my eye involving blockchain tech. I help people on all the company's projects where I can. BY NIGHT: with fam, friends, enjoying the simple things in life, coding python/typescript/javascript stuff, sometimes I'll find myself answering StackOverflow questions.

Updated on June 04, 2022

Comments

  • Philip Mutua
    Philip Mutua almost 2 years

    I have created a file called utilities.py within a Django app but I'm getting errors after importing a model from the same app in the file. This is weird because the same file is within the app, I should not be getting that error. Please advise on this.

    Here is a screenshot showing where the file is located.

    enter image description here

    Models

    from django.utils import timezone
    from django_smalluuid.models import SmallUUIDField, uuid_default
    from django.db import models
    import pytz
    from .utilities import (calc_expiry_date,convert_date)
    from monthdelta import monthdelta
    
    
    class LiquorCostCentre(models.Model):
        cost_centre_id = models.CharField(max_length=250,null=True,blank=True,default="0304-05-05")
        cost_centre_name = models.CharField(max_length=250,null=True,blank=True)
    

    utilities.py

    from .models import *
    
    def process_bill(bill_type, liquor_license, cost_centre, account_number_list, description, license_category,user,amount,schedule_type):
        cost_centre_obj, _ = LiquorCostCentre.objects.get_or_create(cost_centre_id=cost_centre)
        bill = LiqourBillTrack.objects.create(
            fee_choice=schedule_type,
            bill_type=bill_type,
            cost_centre=cost_centre_obj.cost_centre_id,
            balance=float(              amount),
            description=description,
            created_by=user,
            year=CURRENT_YEAR,
            liquor_license= liquor_license
    
        )
        [bill.accounts.add(account_number) for account_number in account_number_list]
        account_values = []
        account_list = bill.accounts.all()
        account_total = [account_values.append(acc_value.amount) for acc_value in account_list ]
    
        bill_total =sum(account_values)
        bill.total = bill_total
        bill.balance = bill_total
        bill.ref_no = 'LIQ-' + str(NOW.year) + str(NOW.month)+ str(bill.id)
        bill.bill_no = bill.ref_no
        bill.save()
        return bill
    

    Error

    eb_1         |   File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    web_1         |     __import__(module)
    web_1         |   File "/app/core/wsgi.py", line 16, in <module>
    web_1         |     application = get_wsgi_application()
    web_1         |   File "/usr/local/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
    web_1         |     django.setup(set_prefix=False)
    web_1         |   File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
    web_1         |     apps.populate(settings.INSTALLED_APPS)
    web_1         |   File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate
    web_1         |     app_config.import_models()
    web_1         |   File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models
    web_1         |     self.models_module = import_module(models_module_name)
    web_1         |   File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
    web_1         |     return _bootstrap._gcd_import(name[level:], package, level)
    web_1         |   File "/app/liquor/models.py", line 10, in <module>
    web_1         |     from .utilities import (calc_expiry_date,convert_date)
    web_1         |   File "/app/liquor/utilities.py", line 2, in <module>
    web_1         |     from liquor.models import LiquorCostCentre
    web_1         | ImportError: cannot import name 'LiquorCostCentre' from 'liquor.models' (/app/liquor/models.py)
    web_1         | [2020-02-17 11:19:23 +0300] [17] [INFO] Worker exiting (pid: 17)
    web_1         | Sentry is attempting to send 0 pending error messages
    web_1         | Waiting up to 2 seconds
    web_1         | Press Ctrl-C to quit
    web_1         | [2020-02-17 11:19:26 +0300] [14] [INFO] Shutting down: Master
    web_1         | [2020-02-17 11:19:26 +0300] [14] [INFO] Reason: Worker failed to boot.
    
    • Sachin
      Sachin about 4 years
      Did you try importing that specific model instead of "*"?
    • Brown Bear
      Brown Bear about 4 years
      show code where you define the models, and please put the error output as text
    • asad_hussain
      asad_hussain about 4 years
      Error log says File "/app/liquor/utilities.py", line 2, in <module> web_1 | from liquor.models import LiquorCostCentre
    • Philip Mutua
      Philip Mutua about 4 years
      @Sachin Imported without the asterisk "*" but I'm getting the same error
    • Brown Bear
      Brown Bear about 4 years
      you have cross import error
    • Philip Mutua
      Philip Mutua about 4 years
      @BearBrown How can this be resolved? I have a different branch that is working perfectly and I'm importing the same way using from .models import * in utilities.py
  • Philip Mutua
    Philip Mutua about 4 years
    issued resolved, it's working! learned something valuable today :)
  • Brown Bear
    Brown Bear about 4 years
    glad to help you!