为什么我在Django中得到ModuleNotFoundError

bihw5rsg  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(135)

x1c 0d1x我创建了一个自定义Django命令,在其中导入了如下所示的模型

# myapp/management/commands/send_birthday_emails.py
from django.core.management.base import BaseCommand
from django.utils import timezone
from Employeetable.EVENTS.models import Event, EmailTemplate
from django.core.mail import send_mail

class send_birthday_emails(BaseCommand):
    help = 'Send birthday emails to employees'

    def handle(self, *args, **options):
        today = timezone.now()
        current_month = today.month

        # Get employees whose birthday is in the current month
        employees = Event.objects.filter(event_type='Birthday', event_date__month=current_month)

        for employee in employees:
            # Get the email template for birthday greetings
            email_template = EmailTemplate.objects.get(event=employee)

            # Compose and send the email
            subject = email_template.subject
            body = email_template.body
            recipient_email = employee.email

            send_mail(subject, body, '[email protected]', [recipient_email])

            self.stdout.write(self.style.SUCCESS(f'Successfully sent email to {recipient_email}'))

我使用了models.py的完整路径,正如您在上面的导入模块列表中所看到的

from Employeetable.EVENTS.models import Event, EmailTemplate

我已经使用IDE对路径的选择给出了给予建议,但我得到了以下错误

from Employeetable.EVENTS.models import Event, EmailTemplate
ModuleNotFoundError: No module named 'Employeetable.EVENTS'

根据规则,我将自定义命令文件send_birthday_emails放在app/management/commands中。
我已经附上了屏幕截图供您参考,以显示文件的确切路径。

(venv) babu@babu-All-Series:~/PycharmProjects/Employeedata/Employeetable$ ll
total 168
drwxrwxr-x 5 babu babu   4096 Oct  2 15:58 ./
drwxrwxr-x 5 babu babu   4096 Oct  2 11:57 ../
-rw-r--r-- 1 babu babu 147456 Oct  2 15:58 db.sqlite3
drwxrwxr-x 3 babu babu   4096 Oct  2 15:45 Employeetable/
drwxrwxr-x 5 babu babu   4096 Oct  2 16:44 EVENTS/
-rwxrwxr-x 1 babu babu    669 Oct  1 15:10 manage.py*
drwxrwxr-x 3 babu babu   4096 Oct  2 12:17 templates/

这是我运行下面的自定义命令的位置

python manage.py send_birthday_emails

请指出哪里可能出错。
谢谢你

bkkx9g8r

bkkx9g8r1#

我试着在我自己的系统里复制你的目录。
如果我使用绝对导入从项目目录我得到同样的错误

from EmployeeTable.EVENTS.models import Event, EmailTemplate
ModuleNotFoundError: No module named 'EmployeeTable.EVENTS'

但是如果我从应用程序级别导入它,如下所示:

from EVENTS.models import Event, EmailTemplate

对我来说很好,给予一次试试。

相关问题