Name error: Can not import [model name] - django

I am trying to link the model Post to the model Topic via a foreign key. When I run the makemigrations command, it raises an import error, and says that the name 'Topic' is not defined. What could be the cause of this? It certainly seems to be defined. I've pretty much ruled out that it is not a problem within the db.
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
title = models.CharField(max_length=100)
summary = models.TextField(blank=True, null=True)
content = models.TextField()
draft = models.BooleanField(default=False)
details = models.CharField(blank=True, null=True, max_length=250)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
topic = models.ForeignKey(Topic, blank=True, null=True)
thumbnail = models.ImageField(upload_to='media', blank=True, null=True)
def get_absolute_url(self):
return reverse('posts:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.title
class Topic(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
picture = models.ImageField(upload_to='media', blank=True, null=True)
isperson = models.BooleanField(default=False)
ispolicy = models.BooleanField(default=False)
positive = models.BooleanField(default=True)
percent = models.CharField(max_length=5)
def __str__(self):
return self.name
Any ideas? I don't see any problems in this code, and neither did my IDE, which recognized the model Topic

I am considering that you have indented your code for Post model properly in your file.
Solution : Try to define Topic above Post.

First, this
topic = models.ForeignKey(Topic, blank=True, null=True)
should be this
topic = models.ForeignKey('Topic', blank=True, null=True)
This way it tells django that you're setting a foreign key to a model, which isn't declared yet, but will be declared further in the code.
Second, you should properly indent your Post model and its methods:
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
title = models.CharField(max_length=100)
summary = models.TextField(blank=True, null=True)
content = models.TextField()
draft = models.BooleanField(default=False)
details = models.CharField(blank=True, null=True, max_length=250)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
topic = models.ForeignKey('Topic', blank=True, null=True)
thumbnail = models.ImageField(upload_to='media', blank=True, null=True)
def get_absolute_url(self):
return reverse('posts:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.title
Because as you have it now, django doesn't understand that the unindented fields belong to the Post model.

Related

Is there a way to update top level relationship in Django form?

I have below models and form.
Brand > Section > Category > Article.
I can pull the existing data out of the database however I have hit a wall. I am trying to create a new article or update an existing article but I'm not sure how I can update the brand, then the Section. The Category I can update and it is connected directly to the Article model. I have been thinking about this for a few days now and tried different models but ultimately i can't think of the best way to connect the models and have them update in the model.
class Brand(models.Model):
def brand_image(instance, filename):
return 'uploads/brand/{0}/{1}'.format(instance.title, filename)
title = models.CharField(max_length=50, unique=True, blank=True, null=True)
image = models.ImageField(upload_to=brand_image, null=True, blank=True)
slug = AutoSlugField(populate_from='title', unique_with='title', blank=True, null=True)
my_order = models.PositiveIntegerField(default=0, blank=False, null=False)
class Meta:
ordering = ['my_order']
def __str__(self):
return self.title or ''
def get_absolute_url(self):
return reverse('brand-list', kwargs={'brand_slug': self.slug})
class Section(models.Model):
title = models.CharField(max_length=50,unique=True, blank=True,null=True)
slug = AutoSlugField(populate_from='title', unique_with='title',blank=True,null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='section', blank=False, null=False)
my_order = models.PositiveIntegerField(default=0, blank=False, null=False)
class Meta:
ordering = ['my_order']
def __str__(self):
return self.title or ''
def get_absolute_url(self):
return reverse('section-list', kwargs={'section_slug': self.slug})
class Category(models.Model):
title = models.CharField(max_length=50, blank=True,null=True)
slug = AutoSlugField(populate_from='title', unique_with='title',blank=True,null=True)
my_order = models.PositiveIntegerField(default=0, blank=False, null=False)
section = models.ForeignKey(Section, on_delete=models.CASCADE,related_name='category', blank=False ,null=False)
class Meta:
ordering = ['my_order']
def __str__(self):
return self.title or ''
def get_absolute_url(self):
return reverse('category-list', kwargs={'category_slug': self.slug})
class Article(models.Model):
title = models.CharField(max_length=100, unique=True, db_index=True)
description = models.CharField(max_length=100, blank=True, null=False)
category = models.ForeignKey(Category, on_delete=PROTECT, related_name='article', null=False, default=1)
slug = AutoSlugField(populate_from='title', unique_with='created__month')
content = HTMLField(null=True,blank=True)
internal = models.BooleanField(default=False)
status = models.CharField(max_length=30, choices=STATUS_CHOICES, default='Draft')
author = models.ForeignKey(User, related_name='author' ,on_delete=PROTECT,null=True)
updated_by = models.ForeignKey(User, related_name='updated_by',on_delete=PROTECT,null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
video = models.FileField(blank=True, null=True, upload_to='articles/videos')
favourites = models.ManyToManyField(User, related_name='art_favourite', default=None, blank=True)
tags = TaggableManager(related_name='tags', help_text='Comma or space separated list', blank=True)
pinned = models.BooleanField(default=False)
def __str__(self) -> str:
return self.title
def get_absolute_url(self):
return reverse('articles-detail', kwargs={'article_slug': self.slug})
class ArticleForm(forms.ModelForm):
title = forms.CharField(label='Article Title', max_length=100,)
description = forms.CharField(label='Description', max_length=100,required=False)
content = forms.CharField(label='Article Content',widget=CKEditorUploadingWidget(attrs={'cols': 80, 'rows': 30}))
video = forms.FileField(help_text="Valid file Extension - .mp4", required=False, validators=[validate_file_extension])
category = GroupedModelChoiceField(queryset=Category.objects.exclude(section=None).order_by('section'),choices_groupby='section')
internal = forms.BooleanField(required=False, help_text='Is this for internal use only?', label='Internal Article')
class Meta:
model = Article
exclude = ['slug','author','created','updated','updated_by','favourites','votes','views','section']
widgets = {"tags": TagWidget(attrs={"data-role": "tagsinput"})}
Any help or guidance would be greatly appreciated.
Your Article model has a foreign key link to Section for some reason. However your stated heirarchy and models use the following one-to-many relations, which creates a direct link up the chain.
Brand < Section < Category < Article.
This means that by choosing the Category you could also choose Brand and Section. If your Article had a foreign key link to Category instead, then all the information above about groups above Article could be obtained via the article, eg, article.category__section__brand. Changing the category would, by default, update section and brand. You could do this in a single dropdown that contained Category.objects.all - perhaps with the dropdown option text also containing brand and section info for clarity and sorting purposes.

How to display one models data in another model django admin panel

I have two models: 1) SchoolProfile & 2) Content
I want to show content data in schoolprofile, But data should be display as per user foreignkey.
User foreignkey common for both the models.
School Profile Model
class SchoolProfile(models.Model):
id=models.AutoField(primary_key=True)
user=models.ForeignKey(User,on_delete=models.CASCADE,unique=True)
school_name = models.CharField(max_length=255)
school_logo=models.FileField(upload_to='media/', blank=True)
incharge_name = models.CharField(max_length=255, blank=True)
email = models.EmailField(max_length=255, blank=True)
phone_num = models.CharField(max_length=255, blank=True)
num_of_alu = models.CharField(max_length=255, blank=True)
num_of_student = models.CharField(max_length=255, blank=True)
num_of_cal_student = models.CharField(max_length=255, blank=True)
def __str__(self):
return self.school_name
Content Model
class Content(models.Model):
id=models.AutoField(primary_key=True)
user=models.ForeignKey(User,on_delete=models.CASCADE)
content_type = models.CharField(max_length=255, blank=True, null=True)
show=models.ForeignKey(Show,on_delete=models.CASCADE, blank=True, null=True)
sponsor_link=models.CharField(max_length=255, blank=True, null=True)
status=models.BooleanField(default=False, blank=True, null=True)
added_on=models.DateTimeField(auto_now_add=True)
content_file=models.FileField(upload_to='media/', blank=True, null=True)
title = models.CharField(max_length=255)
subtitle = models.CharField(max_length=255, blank=True, null=True)
description = models.CharField(max_length=500, blank=True, null=True)
draft = models.BooleanField(default=False)
publish_now = models.CharField(max_length=255, blank=True, null=True)
schedule_release = models.DateField(null=True, blank=True)
expiration = models.DateField(null=True, blank=True)
tag = models.ManyToManyField(Tag, null=True, blank=True)
topic = models.ManyToManyField(Topic, null=True, blank=True)
category = models.ManyToManyField(Categorie, null=True, blank=True)
def __str__(self):
return self.title
I have used Inline but it's show below error:
<class 'colorcast_app.admin.SchoolProfileInline'>: (admin.E202) 'colorcast_app.SchoolProfile' has no ForeignKey to 'colorcast_app.SchoolProfile'.
My admin.py
class SchoolProfileInline(InlineActionsMixin, admin.TabularInline):
model = SchoolProfile
inline_actions = []
def has_add_permission(self, request, obj=None):
return False
class SchoolProfileAdmin(InlineActionsModelAdminMixin,
admin.ModelAdmin):
inlines = [SchoolProfileInline]
list_display = ('school_name',)
admin.site.register(SchoolProfile, SchoolProfileAdmin)
Using the StackedInline to link two models is straight forward and a much clean practice, so basically this is my solution below:
class ContentInlineAdmin(admin.StackedInline):
model = Content
#admin.register(SchoolProfile)
class SchoolProfileAdmin(admin.ModelAdmin):
list_display = ('school_name',)
inlines = [ContentInlineAdmin]

Build Inline Formsets in Django Admin

So I am new to Django and I have been reading a lot of documentation to figure this out, I have a table called "Logs" that has logs of different positions (has FK of table "Position"), each position belongs to a department (has FK to table "Department") Check the image below :1
What I want to do is create a view just like this one :
2
and whenever you click on a department, it extends all the positions in it with their respective logs like this :
3
The Screenshots I have attached are my work in main app (or if you would like to call it front end), I wanted to replicate the same process in the Django Admin page, I keep seeing that I should use inlines but I can't seem to make it work, can someone help or put me in the right direction please ? much appreciated.
Here is what I have in my models.py :
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Site(models.Model):
site = models.CharField(max_length=200, blank=True, null=True)
totalHC = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.site
class Department(models.Model):
department = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.department
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
site = models.ForeignKey(Site, on_delete=models.CASCADE, null=True, default=Site(id="1").site)
department = models.ForeignKey(
"Department", on_delete=models.CASCADE, null=True)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
bio = models.CharField(max_length=2000, blank=True)
skills = models.CharField(max_length=2000, blank=True)
aoi = models.CharField(max_length=2000, blank=True)
github = models.CharField(max_length=200, blank=True)
linkedin = models.CharField(max_length=200, blank=True)
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
class Grade(models.Model):
user = models.OneToOneField(Profile, on_delete=models.CASCADE)
ut1 = models.CharField(max_length=200, blank=True)
ut2 = models.CharField(max_length=200, blank=True)
ut3 = models.CharField(max_length=200, blank=True)
ut1p = models.ImageField(upload_to='plots', blank=True)
ut2p = models.ImageField(upload_to='plots', blank=True)
ut3p = models.ImageField(upload_to='plots', blank=True)
ut1pb = models.ImageField(upload_to='plots', blank=True)
ut2pb = models.ImageField(upload_to='plots', blank=True)
ut3pb = models.ImageField(upload_to='plots', blank=True)
ut12 = models.ImageField(upload_to='plots', blank=True)
ut13 = models.ImageField(upload_to='plots', blank=True)
ut23 = models.ImageField(upload_to='plots', blank=True)
class Section(models.Model):
class Meta:
verbose_name = 'Department'
verbose_name_plural = 'Departments'
section = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.section
class Question(models.Model):
class Meta:
verbose_name = 'Position'
verbose_name_plural = 'Positions'
section = models.ForeignKey(
"Section", on_delete=models.CASCADE, null=True, blank=True)
question_field = models.CharField(max_length=2000, blank=True, null=True)
def __str__(self):
return self.question_field
class Answer(models.Model):
class Meta:
verbose_name = 'Log'
verbose_name_plural = 'Logs'
question = models.ForeignKey(Question, on_delete=models.CASCADE)
user = models.ForeignKey(Profile, on_delete=models.CASCADE)
answer_field = models.CharField(max_length=2000, blank=True, null=True)
def __str__(self):
return f"{self.user} answered {self.answer_field}"
class Position1(models.Model):
class Meta:
verbose_name = 'Position'
verbose_name_plural = 'Positions'
department = models.ForeignKey(
"Department", on_delete=models.CASCADE, null=True, blank=True)
position = models.CharField(max_length=200, blank=True)
jobID = models.CharField(max_length=200, blank=True)
class HCtype(models.TextChoices):
Staff = 'Staff', ('Staff')
IDL = 'IDL', ('IDL')
DL = 'DL', ('DL')
hctype = models.CharField(
max_length=5,
choices=HCtype.choices,
)
def __str__(self):
return self.position
class Log(models.Model):
position = models.ForeignKey(Position1, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
site = models.ForeignKey(Site, on_delete=models.CASCADE)
INN = models.IntegerField(blank=True, null=True)
OUT = models.IntegerField(blank=True, null=True)
date = models.CharField(max_length=200, blank=True)
internal = models.IntegerField(default=0, null=True)
class SiteHasPosition(models.Model):
date = models.CharField(max_length=200, blank=True)
site = models.ForeignKey(Site, on_delete=models.CASCADE)
position = models.ForeignKey(Position1, on_delete=models.CASCADE)
value = models.IntegerField(blank=True, null=True)
standard = models.IntegerField(blank=True, null=True)
turn_over = models.IntegerField(blank=True, null=True)
class SiteHasDepartment(models.Model):
date = models.CharField(max_length=200, blank=True)
site = models.ForeignKey(Site, on_delete=models.CASCADE)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
value = models.IntegerField(blank=True, null=True)
class SiteKPIs(models.Model):
site = models.ForeignKey(Site, on_delete=models.CASCADE)
date = models.CharField(max_length=200, blank=True)
staff = models.IntegerField(blank=True, null=True)
dl = models.IntegerField(blank=True, null=True)
idl = models.IntegerField(blank=True, null=True)
total_hc = models.IntegerField(blank=True, null=True)
total_in = models.IntegerField(blank=True, null=True)
total_out = models.IntegerField(blank=True, null=True)
staff_rate = models.IntegerField(blank=True, null=True)
dl_rate = models.IntegerField(blank=True, null=True)
idl_rate = models.IntegerField(blank=True, null=True)
Here is how I registred them in admin.py :
admin.site.register(Profile)
admin.site.register(Log)
admin.site.register(Position1)
admin.site.register(Department)
admin.site.register(Site)
admin.site.register(SiteHasDepartment)
admin.site.register(SiteHasPosition)
I would like to have a page in admin.py where I can select a site and for that specific site display :
all the departments(when you press a dpt all the positions will expand) for each position the standardHC, attributes from the Log table (that match that position,and that site) and attributes from SiteHasPosition( that match the site and that position)
I hope I made it clearer

Django create nested model

I want to create a Model in which I can store the same models as for example in a folder there can be several folders.
I tried like this:
class Service(models.Model):
name = models.TextField(default="")
price = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.name
class ServiceType(models.Model):
services_types = models.ManyToManyField(ServiceType, null=True, blank=True)
services = models.ManyToManyField(Service, null=True, blank=True)
name = models.TextField(default="")
But it didn't work. How can this problem be solved?
If you want to reference same model then you have to use quotation 'ModelName' like this.
So your code will be like:
class Service(models.Model):
name = models.TextField(default="")
price = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.name
class ServiceType(models.Model):
services_types = models.ManyToManyField('ServiceType', null=True, blank=True)
services = models.ManyToManyField(Service, null=True, blank=True)
name = models.TextField(default="")

I wanna create model which Before adding it must be accepted

I would like to create a model which must be accepted by the moderator before adding, after which every change in eg the title in this model must also be accepted
class MangaRequest(models.Model):
title = models.CharField(max_length=191)
type = models.CharField(max_length=30,choices=TYPE, blank=True, default='', null=True)
status= models.CharField(max_length=30, choices=STATUS, blank=True, default='', null=True)
date_start = models.DateField(blank=True, null=True)
data_end = models.DateField(blank=True, null=True)
age_restrictions = models.ForeignKey(OgraniczenieWiekowe, null=True, default='', blank=True)
volumes = models.SmallIntegerField(null=True, blank=True, default=0)
chapter = models.SmallIntegerField(null=True, blank=True, default=0)
is_accept = models.BooleanField(default=False)
delete = models.BooleanField(default=False)
This is my model and I have done it
def save(self, *args, **kwargs):
if self.is_accept == True:
manga = MangaAccept.objects.create(...)
super(MangaRequest, self).delete()
return manga
else:
super(MangaRequest, self).save()
And the same way is about deletes
My question is how can ACCEPT or REJECT for model and everyone field in this model ? Any sugestion ?