Circular imports django - python

I have wrote this code in my models.py file.
As you see the code, I have a class called File and also I have imported in models.py the same class.
Now it gives me this error while migration:
Cannot import name "File" from 'uploadapp.models'
I understand it's the error for circular (recursive) import. But how can I solve this?
from django.db import models
from .models import File
class File(models.Model):
file = models.FileField(blank=False, null=False)
def __str__(self):
return self.file.name

You remove the from .models import File. It makes no sense to import the module in the same module:
from django.db import models
# from .models import File
class File(models.Model):
file = models.FileField(blank=False, null=False)
def __str__(self):
return self.file.name

Related

Django can't import module due to a circular import

Following a tutorial and am have the module
views.py file
#attempt2/src/products/views.py
from django.shortcuts import render
from .forms import ProductForm, RawProductForm
from .models import Product
def product_create_view(request):
#this creates an instance of that form
my_form = RawProductForm()
context = {
"form": my_form
}
return render(request, "product/product_create.html", context)
But I get the following error
File "C:\Users\dancc\dev2\attempt2\src\products\views.py", line 2, in <module>
from .forms import ProductForm, RawProductForm
File "C:\Users\dancc\dev2\attempt2\src\products\forms.py", line 4, in <module>
from products.views import product_create_view
ImportError: cannot import name 'product_create_view' from partially initialized module 'products.views' (most likely due to a circular import) (C:\Users\dancc\dev2\attempt2\src\products\views.py)
I've tried searching to see where it might be importing a different product_create_view but there is not another one, none of the files or folders' names repeat
this is forms.py
#attempt2/src/products/forms.py
from django import forms
from products.views import product_create_view
from .models import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = [
'title',
'description',
'price'
]
#This is what product_create_view is using
class RawProductForm(forms.Form):
title = forms.CharField()
description = forms.CharField()
price = forms.DecimalField()
This is models.py file
#attempt2/src/products/models.py
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=120) #max_length required
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=10000)
summary = models.TextField()
This is views.py file
#attempt2/src/products/views.py
from django.shortcuts import render
from .forms import ProductForm, RawProductForm
from .models import Product
...
def product_create_view(request):
#this creates an instance of that form
my_form = RawProductForm()
context = {
'form': my_form
}
return render(request, "product/product_create.html", context)
Here are the folders
You are importing the product_create_view from the products.views module, but in your forms.py, you do not use that function. Since the products.forms module imports the products.views module, and vice versa, this creates a cycle when importing one of the two.
You can remove the from products.views import product_create_view line from the forms.py file, and thus simply let the view use the forms you defined, not in the opposite direction.

Why 'django.contrib.admin.sites' has no attribute 'register'?

i make the model in app but when i call this function 'admin.sites.register(modal_class_name)' in admin.py file. i got an error
here is my modal class
from django.db import models
# Create your models here.
class Topic(models.Model):
top_name=models.CharField(max_length=256,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic=models.ForeignKey(Topic,Topic)
name=models.CharField(max_length=256,unique=True)
url=models.URLField(unique=True)
def __str__(self):
return self.name
class AccessRecord(models.Model):
name=models.ForeignKey(Webpage,Webpage)
date=models.DateField()
def __str__(self):
return str(self.date)
and Here is my admin.py file code
from django.contrib import admin
# Register your models here.
from first_app.models import AccessRecord, Topic, Webpage
admin.sites.register(AccessRecord)
admin.sites.register(Topic)
admin.sites.register(Webpage)
and when i run the project the error appears,which is following
error snapshot
There is typo in your code. Its site instead of sites.
admin.py
from django.contrib import admin
# Register your models here.
from first_app.models import AccessRecord, Topic, Webpage
admin.site.register(AccessRecord)
admin.site.register(Topic)
admin.site.register(Webpage)

How to import auth.User on django-import/export

I can't import a CSV file into model on Django.
I made a column 'author' and put the superuser's id which I am login to the admin site.
But there was an error like this when I import the CSV file.
Line number: 1 - null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (10, abc, blahblah, null, ).
5, abc, blahblah, , nah,wha,blah
csv file
author,title,text,file,free_tags
5,abc,blahblah,,"nah,wha,blah"
models.py
from django.db import models
from django.urls import reverse
from taggit.managers import TaggableManager
class KnowHow(models.Model):
author = models.ForeignKey('auth.User',on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField(blank=True)
file = models.FileField(blank=True,upload_to='explicit_knowhows')
free_tags = TaggableManager(blank=True)
def __str__(self):
return self.title
admin.py
from django.contrib import admin
from import_export import resources
from import_export import fields
from import_export.admin import ImportExportModelAdmin
from .models import KnowHow
# Register your models here.
class KnowHowResource(resources.ModelResource):
class Meta:
model = KnowHow
exclude = 'id'
import_id_fields = ('title', )
#admin.register(KnowHow)
class knowHowAdmin(ImportExportModelAdmin):
resource_class = KnowHowResource
The error says that author_id is missed.
Django adds a postfix to all the ForeignKey fields, so you should try to modify the file renaming the column:
author_id,title,text,file,free_tags
5,abc,blahblah,,"nah,wha,blah"
It fixed when I saved the CSV by encoding in UTF-8. This will not support non-alphabet letter so I recommend using .xlsx file instead.
Thank you to everyone who tried to fix my problem.

How do I import a model into my console so that I can lookup instances of it from my db?

I'm using PyCharm 2018.2 and Python 3.7. How do I import a model into my console so that I can lookup instances of it from the db? I thought this would do it
from .models import Article
but when I run this on a console, I get the below errors. I'm not sure what they mean
>>> from .models import Article
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import
module = self._system_import(name, *args, **kwargs)
KeyError: "'__name__' not in globals"
Below is my models.py file ...
from django.db import models
# Create your models here.
from datetime import datetime
from django.utils import timezone
class Webpage(models.Model):
path = models.CharField(max_length=100)
def __str__(self):
return self.path
def create(cls, path):
Webpage = cls(path=path)
return Webpage
class Article(models.Model):
webpage = models.ForeignKey(Webpage, on_delete=models.CASCADE,)
path = models.CharField(max_length=100)
url = models.TextField
time = models.DateTimeField(default=datetime.now)
votes = models.IntegerField(default=0)
comments = models.IntegerField(default=0)
front_page = models.BooleanField(default=False)
def __str__(self):
return self.path
#classmethod
def create(cls, webpage, path, url, votes, comments):
article = cls(webpage=webpage,path=path,url=url,votes=votes,comments=comments)
return article
Try putting your app name in your import statement:
from <name of your app>.models import Article
The Django shell runs in your project directory, but models.py is in your app directory.
Try the command python manage.py shell and then include your model classes.
It's all explained here: https://tutorial.djangogirls.org/en/django_orm/

Why are my django model fields not working?

I don't think that it is recognizing the existence of my fields. Here's my models.py:
from django.db.models import *
from django.contrib import admin
from django.forms import *
class Stock(Model):
name = CharField(max_length=60)
class Meta:
ordering = ["name"]
def __unicode__(self):
return self.name
admin.site.register(Stock)
When I run it, I get this error: "portfolio.stock: "ordering" refers to "name", a field that doesn't exist." When I comment the meta function out and run it, it works fine until the admin site, where when I try to create a stock object, the fields don't show up.
I'm completely confused by what's going on.
The problem is your * imports.
django.db.models.CharField is being replaced by django.forms.CharField:
>>> from django.db.models import *
>>> CharField
<class 'django.db.models.fields.CharField'>
>>> from django.forms import *
>>> CharField
<class 'django.forms.fields.CharField'>
So, actually name = CharField(max_length=60) defines a form field instead of a model one - it breaks everything and makes this bug subtle.
Solution: remove unnecessary forms import and be explicit in your imports:
from django.db import models
from django.contrib import admin
class Stock(models.Model):
name = models.CharField(max_length=60)
class Meta:
ordering = ["name"]
def __unicode__(self):
return self.name
admin.site.register(Stock)

Categories

Resources