1

I am trying to learn, "How to run standalone scripts in django". I am using python2.7 and django==1.4.3. I have created a very basic script which i am trying to run but facing import errors . I don't want to create a management command as this is just temporary stuff and my focus is to learn also.

My Code

import os
import sys
from cartridge.shop.models import HomepageUpselling


class HomepageUpsellingToBestsellers():
    """This class copy the HomepageUpselling data to BestSellers"""

    def homepageuselling_to_bestsellers(self):
        """ Data Copy """
        hu_obj = HomepageUpselling.objects.all()
        for hu_iterable in hu_obj:
            bs_obj, created = \
                BestSeller.objects.get_or_create(product=hu_iterable.product,
                                                 variation=hu_iterable.variation)
            print "BestSeller data copying %s" % bs_obj.id
        return


if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.setttings")
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from django.core.management import execute_from_command_line
    hu_to_bs_obj = HomepageUpsellingToBestsellers()
    hu_to_bs_obj.homepageuselling_to_bestsellers()
    print "Data Copied"

Error

ImportError: No module named cartridge.shop.models
djangobot
  • 257
  • 1
  • 2
  • 11
  • Is that in project folder or environment ? – Raja Simon Aug 12 '14 at 10:08
  • I have created a directory called scripts with init file just next to parent folder. So parent folder is /Users/nikhilverma/workspace/BHANE/bhane.com and scripts directory is in /Users/nikhilverma/workspace/BHANE/bhane.com/bhane/scripts – djangobot Aug 12 '14 at 10:29
  • i think you need to setup django environment first – Raja Simon Aug 12 '14 at 10:45

2 Answers2

2

The best way to do it in my opinion (especially considering your usecase) is to write your own management command. Subclass Basecommand and then run it as

 python manage.py yourcommand arguments

Django documentation for custom commands

Martol1ni
  • 4,684
  • 2
  • 29
  • 39
1

You are using Django 1.4 So here is the right way to code environ ..

import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")

# you can import your model here and the locaion of function 
from your_project_name.models import Location

# From here you can start your script..
Raja Simon
  • 10,126
  • 5
  • 43
  • 74
  • still the same :- Traceback (most recent call last): File "bhane/scripts/copy_homepageupselling_data_to_bestsellers.py", line 12, in from cartridge.shop.models import HomepageUpselling ImportError: No module named cartridge.shop.models – djangobot Aug 17 '14 at 12:52
  • @djangobot https://stackoverflow.com/a/66446394/11590791 refer this code. It works fine. – RUGVED Mar 02 '21 at 20:13