Usar modelos fuera de una vista

To send emails and stuff, I use code outside the views.py file (too much code there). I created a file named "tools.py" in the app folder where I start with

from django.shortcuts import render_to_response
from django.core.mail import send_mail

from mysite.myapp.models import MyModel

With runserver, I have an error ImportError: cannot import name MyModel

This is strange as I use the same import in the views.py file and there is no problem...

Alguna idea ? Gracias

preguntado el 09 de marzo de 12 a las 15:03

2 Respuestas

Most likely, you have a circular import. Are you importing this tools.py file in your myapp/models.py?

respondido 09 mar '12, 15:03

Yes I do. I use a function defined in tools in a model, I guess I shouldn't have. - Martín Trigaux

Generally, circular imports indicate a design flaw. If tools needs models and models needs tools, then it should really be all part of the same module. So, yes, you should probably move relevant items into myapp/models.py. - Chris Pratt

Un par de cosas:

  • Asegúrate de tener tu init.py file in the folder where your "tools.py" file is located, this is a common reason why something might not be found.

I'm working on setting up something that requires something very similar to your requirements.

If you are trying to have this as a on/off process eg.) cronjob, worker etc. Do the following.

#!/usr/bin/env python
######################################################################### 
# Required DO NOT REMOVE
#########################################################################
import os
import sys

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "appname.settings")
#########################################################################

# Import My Models, or Run an Include to Handle Processing.
from app.models.model import *

# Do Stuff to Test ( I suggest a simple insert into the model or pull and return content )

Save this file in the same folder that your "manage.py" is saved in, you can call this directly and it should process, you can setup a cronjob for it to run, etc. This allows you to have a little less code as it doesn't run some of the processes that django runs prior to rendering a view from the urls.py file.

If this is unclear please feel free to comment and I will edit with correction or further details.

Todo lo mejor

Respondido 07 Feb 14, 13:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.