function in models is unrecognizable - django

I trying extend existed models so I added 'thumbnails' in to it. Unfortunately function related to this is not recognized and django console gives me:
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)
NameError: name '_get_upload_image' is not defined
Could someone help me with this issue?
Django 1.6.5 models.py (short version)
class Feed(models.Model):
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)
class Meta:
unique_together = (
("url", "user"),
)
def _get_upload_image(instance, filename):
return "images/%s_%S" % (str(time()).replace('.','_'), filename)

I solved this through placing function on top of class
class Feed(models.Model):
def _get_upload_image(instance, filename):
return "images/%s_%S" % (str(time()).replace('.','_'), filename)
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)

Related

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

Column core_event.hometask does not exist

When I run my Django project on production server, I have this error:
ProgrammingError at /admin/core/event/
column core_event.hometask does not exist
LINE 1: ..._event"."is_approved", "core_event"."event_type", "core_even...
What I should do to fix it? Now I haven't "hometask" field in my model:
class Event(models.Model):
name = models.CharField(max_length=100, null=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
description = models.TextField(max_length=1000, blank=True, null=True)
date_start = models.DateTimeField(null=True, blank=True)
date_finish = models.DateTimeField(null=True, blank=True)
image = models.ImageField(
upload_to="event_images/", default='event_images/default.png', blank=True, null=True)
is_approved = models.BooleanField(null=True)
TYPE_CHOICES = (
('Event', "Мероприятие"),
('Lesson', "Урок"),
)
event_type = models.CharField(choices=TYPE_CHOICES, max_length=200, default="Мероприятие")
topics = ArrayField(models.CharField(max_length=200), blank=True, null=True)
materials = ArrayField(models.URLField(), blank=True, null=True)
possible_users = models.ManyToManyField("core.User", blank=True, related_name='possible_users')
actual_users = models.ManyToManyField("core.User", blank=True, related_name='actual_users')
classes = models.ManyToManyField("core.Class", blank=True, related_name='classes')
From what you posted, looks like the field existed in the model before but not anymore. However, your admin.py still has reference to the old field of hometask.
So, go to admin.py, search for hometask, and remove it.

Django - error message: IndentationError: unindent does not match any outer indentation level

enter image description here
I'm having trouble solving this portion of my code.
This is the model.py inside my app.
The "image = models.ImageField(null=True, blank=True)" keeps giving me an error. I install Pillow library but didn't solve the problem
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField()
digital = models.BooleanField(default=False,null=True, blank=False)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True, blank=False)
def __str__(self):
return str(self.id)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, blank=True, null=True)
date_added = models.DateTimeField(auto_now_add=True)
class ShippingAddress(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
address = models.CharField(max_length=200, null=True)
city = models.CharField(max_length=200, null=True)
state = models.CharField(max_length=200, null=True)
zipcode = models.CharField(max_length=200, null=True)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.address
This type of error could mean that you have mixed spaces and tabs in you indentation, or other whitespace issues.
Is the line below it (line 19) empty or does in have some whitespace?

Django Need to add two serializers data together in one response

I have a two models, Person and Video.
Below viewset allows me all methods like POST, PATCH, DELETE, GET.
class PersonViewSet(viewsets.ModelViewSet):
queryset = apis_models.Person.objects.all()
serializer_class = apis_serializers.PersonSerializer
permission_classes = [HasPermPage]
Video model is associated with person model through Target model which is my main problem. Each person has few videos.
Now what I need is when I do "/person/{id}/" I should get person details along with all videos details it associated with.
Please let me know what change needs to be done to above ViewSet.
Models and Serializer:
class Video(DFModel):
source = models.ForeignKey(Source, models.DO_NOTHING)
creator = models.ForeignKey(
Creator, models.DO_NOTHING, blank=True, null=True)
title = models.CharField(max_length=500)
views = models.IntegerField(blank=True, null=True)
likes = models.IntegerField(blank=True, null=True)
dislikes = models.IntegerField(blank=True, null=True)
tags = models.TextField(blank=True, null=True)
upload_date = models.DateTimeField(blank=True, null=True)
page_url = models.TextField(blank=True, null=True)
video_url = models.TextField(blank=True, null=True)
thumb_url = models.TextField(blank=True, null=True)
sfw = models.BooleanField(blank=True, null=True)
category = models.CharField(max_length=20, blank=True, null=True)
reviewed = models.TextField(blank=True, null=True)
severity = models.CharField(max_length=10, blank=True, null=True)
origin = models.CharField(max_length=20, blank=True, null=True)
organization_id = models.IntegerField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
class Person(models.Model):
name = models.CharField(unique=True, max_length=45)
nationality = models.CharField(max_length=50, blank=True, null=True)
profession = models.CharField(max_length=50, blank=True, null=True)
avatar = models.CharField(max_length=100, blank=True, null=True)
active_scraping = models.BooleanField(blank=True, null=True)
vuln_score = models.FloatField(blank=True, null=True, default=None)
reviewed = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
class Target(DFModel):
person = models.ForeignKey(
Person, models.DO_NOTHING, blank=True, null=True)
video = models.ForeignKey(
'Video', models.DO_NOTHING, blank=True, null=True)
reviewed = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
class Meta:
db_table = 'target'
class PersonSerializer(CustomSerializer):
class Meta:
model = apis_models.Person
fields = '__all__'
class TargetSerializer(CustomSerializer):
class Meta:
model = apis_models.Target
fields = '__all__'
extra_fields = ['monthly_growth', 'vulnerablility_score']
class VideoSerializer(CustomSerializer):
source = SourceSerializer(read_only=True)
creator = CreatorSerializer(read_only=True)
class Meta:
model = apis_models.Video
fields = '__all__'
It looks like you have a ManyToMany relation between Person and Video, so, I suggest you to change your models to be like:
class Person(models.Model):
name = models.CharField(unique=True, max_length=45)
nationality = models.CharField(max_length=50, blank=True, null=True)
profession = models.CharField(max_length=50, blank=True, null=True)
avatar = models.CharField(max_length=100, blank=True, null=True)
active_scraping = models.BooleanField(blank=True, null=True)
vuln_score = models.FloatField(blank=True, null=True, default=None)
reviewed = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
videos = models.ManyToManyField(Video, through='Target', related_name="people") # Field that will have the videos of a Person
Once you have that, I suggest you to change your PersonSerializer object to be:
class PersonSerializer(CustomSerializer):
videos = VideoSerializer(source='videos', many=True)
class Meta:
model = apis_models.Person
fields = '__all__'
If you can't change your models to support ManyToMany fields I suggest you to do the following:
class Person(models.Model):
name = models.CharField(unique=True, max_length=45)
nationality = models.CharField(max_length=50, blank=True, null=True)
profession = models.CharField(max_length=50, blank=True, null=True)
avatar = models.CharField(max_length=100, blank=True, null=True)
active_scraping = models.BooleanField(blank=True, null=True)
vuln_score = models.FloatField(blank=True, null=True, default=None)
reviewed = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
def videos(self):
return Video.objects.filter(
id__in=Target.objects.filter(person=self).values('video')
)
And use the same serializer I used in the first part of the answer.

Make a query to django models

How is "translation" for following query to django queryset?
SELECT guid FROM feedme_feeditem
WHERE feed_id IN
(SELECT id FROM feedme_feed WHERE country_id IN
(SELECT id FROM feedme_country WHERE name='NL'))
models.py
class Country(models.Model):
name = models.CharField(max_length=250, blank=True)
class Category(models.Model):
name = models.CharField(max_length=250, blank=True)
slug = models.SlugField(blank=True, null=True, editable=False)
user = models.ForeignKey(User, blank=True, null=True)
country = models.ForeignKey(Country, blank=True, null=True)
class Feed(models.Model):
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
class FeedItem(models.Model):
title = models.CharField(max_length=350, blank=True)
link = models.URLField(blank=True)
content = models.TextField(blank=True)
feed = models.ForeignKey(Feed, blank=True, null=True)
read = models.BooleanField(default=False)
guid = models.CharField(max_length=255)
pub_date = models.DateTimeField()
To make more simple I already tried add country = models.ForeignKey(Country, blank=True, null=True) to FeedItem class but does't work how i expected.
guids = FeedItem.objects.filter(feed__country__name = 'NL')