-2

Context: I am trying to import 2 classes located in models.py into another python file called admin.py. The django docs say to use this syntax: from .models import Question, Choice.

This is the file structure: file structure

Question: Why is it, when I use from . import models and then in the same file call models.Question and models.Choice I get an error for: "ModuleNotFoundError: No module named 'models' "

In another file in the same directory, this syntax is used to import a file and call a function within the file without any issues: from . import views ... views.index

1 Answers1

0

I recommend you to import models in this way.

from .models import *

Now, during your python coding, when you want to use some specific model, you just write the name of that model.

For example, in on of my project, I have a utils.py file, I imported all the models, and in one of my function I call one of these models.

import json
import datetime
from .models import *

def cookieCart(request):
    try:
        cart = json.loads(request.COOKIES['cart'])
    except:
        cart = {}
        
    print('Cart:', cart)
    items = []
    order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
    cartItems = order['get_cart_items']

    for i in cart:
        try:
            cartItems += cart[i]['quantity']
            product = Producto.objects.get(id=i)
            total = (product.price * cart[i]['quantity'])

            order['get_cart_total'] += total
            order['get_cart_items'] += cart[i]['quantity']

            item = {
                'product':{
                    'id':product.id,
                    'name':product.name,
                    'price':product.price,
                    'imageURL':product.imageURL,
                    },
                'quantity':cart[i]['quantity'],
                'get_total':total,
            }
            items.append(item)

            if product.despacho == True:
                order['shipping'] = True
        except:
            pass
    return {'cartItems':cartItems, 'order':order, 'items':items}
Dharman
  • 30,962
  • 25
  • 85
  • 135
southernegro
  • 384
  • 4
  • 20