Error: relative import with no known parent package

Viewed 114

[Newbie] Good evening, I'm a newbie using python I just created a project in Django and I want to save a basic record as the first and last name of an employee. I created a "seed.py" file within my "employee" application that should create a new record in the database with the employee's first and last name.

I'm instantiating my "Seed" object inside "manage.py" which would be the main class, every time I start my application, the seed.py code has to be executed, but it gives me an error when trying to execute the code.

"An exception occurred: ImportError relative import attempt without a known parent package File "C: \ GitHub \ django \ backend \ api \ manage.py", line 5, in from .employee.seed import Seed

django project (folder) C: \ GitHub \ django \ backend \ api \

django app (folder) C: \ GitHub \ django \ backend \ api \ employee

What am I doing wrong?

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here

c:\GitHub\django\backend\api\manage.py

#!/usr/bin/env python

"""Django's command-line utility for administrative tasks."""
import os
import sys
from .employee.seed import Seed


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)
    seed = Seed()
    seed.employee_register()
    seed.employee_list()


if __name__ == '__main__':
    main()

c:\GitHub\django\backend\api\employee\seed.py

from .models import Employee


class Seed:

    def employee_register(self):
        emp = Employee()
        emp.name_one = "ejemplo nombre"
        emp.surname_one = "ejemplo apellido"
        emp.save()
        print("Nuevo registro guardado.")

    def employee_list(self):
        emp_list = Employee.objects.all()
        print(emp_list)

c:\GitHub\django\backend\api\employee\models.py

from django.db import models
# Create your models here.


class Employee(models.Model):
    name_one = models.CharField(max_length=20, blank=False, null=False)
    surname_one = models.CharField(max_length=20)
    date_joined = models.DateField(auto_now_add=True)

    class Meta:
        verbose_name = "employe_information"
1 Answers

You have to remove the . in .employee.seed. The syntax should be <app_name>.<file_name>.

Putting the dot there tells python to search in the current directory(manage.py directory) instead of the app's directory.

Related