Django ImportError: cannot import name ‘ReporterProfile’ from partially initialized module ‘accounts.models’ (most likely due to a circular import)

I have two apps named collection, accounts. Both apps have models defined. I am importing a model ReporterProfile from accounts app to collection. Similarly, a model Report from the app collection to accounts.

The Report model from collection app is called in a model class method in accounts app like this:

from collection.models import Report

class ReporterProfile(models.Model):
    ....

    def published_articles_number(self):
        num = Report.objects.filter(reporterprofile=self.id).count()
        return num

Similarly, I am importing ReporterProfile and User models from accounts app to collection app model like this:

from accounts.models import ReporterProfile, User
from <project_name> import settings

class Report(models.Model):
    reporterprofile = models.ForeignKey(ReporterProfile, on_delete=models.CASCADE, verbose_name="Report Author")
    ...

class Comment(models.Model):
    report = models.ForeignKey(Report, on_delete=models.CASCADE, related_name='comments')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Comment by")
    ...

When running the server or makemigrations, I'm getting the error:

File "F:\project_name\accounts\models.py", line 8, in from collection.models import Report

File "F:\project_name\collection\models.py", line 2, in from accounts.models import ReporterProfile, User

ImportError: cannot import name 'ReporterProfile' from partially initialized module 'accounts.models' (most likely due to a circular import) (F:\project_name\accounts\models.py)

I think the error is coming because of wrong importing pattern. What should I do?



Read more here: https://stackoverflow.com/questions/62100550/django-importerror-cannot-import-name-reporterprofile-from-partially-initiali

Content Attribution

This content was originally published by Strange_air at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: