My class is
from django.db import models
from .dir import my_func
class Upload(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images')
img_content = my_func(image)
def __str__(self):
return self.title
and I'm not able to pass the image because of an E006 error
is there a way to avoid it?
because I can call the function but I need to know the name of the newly uploaded image.
thanks in advnace
You define a property that will obtain the value for image:
class Upload(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images')
#property
def img_content(self):
return my_func(self.image.name)
Related
I have 2 similars forms so I decide to inherite one form from another and it looks like:
class EditModuleForm(forms.Form):
category_name = forms.CharField(label='Name', max_length=100)
image = forms.ImageField(label='Icon', required=False)
def clean_image(self):
image = self.cleaned_data.get('image', None)
if image:
check_image_size(image)
class NewCategoryForm(EditModuleForm):
category_slug = forms.CharField(label="Slug", max_length=10)
field_order = ['category_name', 'category_slug', 'image']
def clean_image(self):
super(NewCategoryForm, self).clean_image()
and during using NewCategoryForm image is not validated and value is None. Looks like this form can't get value from image field. Could somebody give me a hint what I'm doing wrong?
You aren't returning the cleaned data from your clean_image method, the clean_<field> methods allow us to change the data for the field and hence we must return the data from the method. Also you don't need to override the method inside your subclass:
class EditModuleForm(forms.Form):
category_name = forms.CharField(label='Name', max_length=100)
image = forms.ImageField(label='Icon', required=False)
def clean_image(self):
image = self.cleaned_data.get('image', None)
if image:
check_image_size(image)
return image
class NewCategoryForm(EditModuleForm):
category_slug = forms.CharField(label="Slug", max_length=10)
field_order = ['category_name', 'category_slug', 'image']
For example, I have three Models in django:
class Car(models.Models):
range = models.DecimalField()
speed = models.DecimalField()
def __str__(self):
return self.speed
class Group_of_Cars(models.Models):
name = models.CharField()
starting_city = models. CharField()
car = models.ManyToManyField(Car)
def __str__(self):
return self.name
class Arrival_time(models.Models):
Location_of_ArrivalPoint = models.CharField()
Last_known_location_of_CarGroup = models.CharField()
Group_of_Cars = models.ForeignKey(Group_of_Cars)
def function(self):
"Get speed of the "Car" in "Group_of_Cars"
def __str__(self):
return self. Location_of_ArrivalPoint
This is an example of what I want to do, not my actual models. The idea is for the user to input a series of values for the type of "Cars" such as speed and range. I'd like "Cars" to be selected when defining parameters for "a Group_of_Cars". What I'm not sure how to do is how to get the speed of the car, for the Group_of_Cars for which I need to calculate an arrival time (Group_of_Cars consists of one type of car and I'd like 'Arrival_time' to be its own table).
Thank you for any input.
models.py
from django.db import models
# Create your models here.
class Car(models.Model):
range = models.DecimalField(decimal_places=2,max_digits=5)
speed = models.DecimalField(decimal_places=2,max_digits=5)
def __str__(self):
return str(self.speed)
class Group_of_Cars(models.Model):
name = models.CharField(max_length=50)
starting_city = models. CharField(max_length=50)
car = models.ManyToManyField(Car)
def __str__(self):
return self.name
class Arrival_time(models.Model):
Location_of_ArrivalPoint = models.CharField(max_length=50)
Last_known_location_of_CarGroup = models.CharField(max_length=50)
Group_of_Cars = models.ForeignKey(Group_of_Cars, on_delete=models.CASCADE)
def function(self):
# "Get speed of the "Car" in "Group_of_Cars"
return self.Group_of_Cars.car.all()
def __str__(self):
return self. Location_of_ArrivalPoint
In views.py
from django.shortcuts import render
from core.models import Arrival_time
from django.http import HttpResponse
# Create your views here.
def home(request):
arp = Arrival_time.objects.get(Location_of_ArrivalPoint='Newyork')
for i in arp.function():
print(i)
return HttpResponse()
How can I can use managers to query my foreign key and then retrieve objects that are connected to foreign key?
Here is my models.py:
from django.db import models
# Create your models here.
class BookManager(models.Manager):
def title_count(self,keyword):
return self.filter(title__icontains=keyword).count()
class CategoryManager(models.Manager):
def category_count(self):
return self.filter(category__icontains=python).count()
class Category(models.Model):
title=models.CharField(max_length=20)
def __str__(self):
return self.title
class Enquiry(models.Model):
title=models.CharField(max_length=200)
category=models.ForeignKey(Category ,default=False,blank=False)
detail=models.TextField()
objects = BookManager()
objects=CategoryManager()
# tags=models.ChoiceField()
def __str__(self):
return self.title
I tried to use category manager but it gave me a strange error.
I just want to know how exactly we can get the objects that are connected with category foriegn-key and show them as list to the users.
You can combine both the title_count and category_count methods under one Manager. When filtering through a ForeignKey, your field lookup needs to specify the name of the field you're trying to filter on, else it will assume you're querying the ID field. So instead of category__icontains, you would do category__title__icontains.
Another note, in newer versions of Django, you are required to specify the on_delete parameter when defining a ForeignKey.
This is a working example of what I think you're trying to accomplish.
class BookManager(models.Manager):
def title_count(self, keyword):
return self.filter(title__icontains=keyword).count()
def category_count(self, keyword):
return self.filter(category__title__icontains=keyword).count()
class Category(models.Model):
title = models.CharField(max_length=20)
def __str__(self):
return self.title
class Enquiry(models.Model):
title = models.CharField(max_length=200)
category = models.ForeignKey(Category,
default=False,
blank=False,
on_delete=models.CASCADE)
detail = models.TextField()
books = BookManager()
# tags=models.ChoiceField()
def __str__(self):
return self.title
Here's how you would use it:
Enquiry.books.category_count('python')
Enquiry.books.title_count('test')
I have these models:
class BlogCategory(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
def get_number_of_categorys_items(self):
return self.post_set.count()
class Post(models.Model):
title = models.CharField(max_length=130)
content = models.TextField()
category = models.ForeignKey(BlogCategory, related_name='blog_category')
def __str__(self):
return self.title
And when I try to call method get_number_of_categorys_items it cause error:
AttributeError: 'BlogCategory' object has no attribute 'post_set'
This method should return number of posts with this category.
What can I do?
Since you've specified the related_name, Django would not automatically create the related name as post_set for you. Either use:
def get_number_of_categorys_items(self):
return self.blog_category.count()
Or, don't specify the related_name:
category = models.ForeignKey(BlogCategory)
There are two models:
class BaseImage(models.Model):
description = models.CharField(max_length=200)
image = models.ImageField(upload_to='images')
class Meta:
abstract = True
class PostImage(BaseImage):
in_text = models.BooleanField()
def __init__(self, *args, **kwargs):
super(BaseImage, self).__init__(*args, **kwargs)
self.image.upload_to = 'images/news/%Y/%m/%d'
How can I set upload_to property in the base model? This my attempt doesn't work:
self.image.upload_to = 'images/news/%Y/%m/%d'
What I can suggest is to write function to get upload to method from instance e.g.
in models.py
#default method to get file upload path
def get_upload_to(instance, filename):
return instance.get_upload_to_path(filename)
class BaseImage(models.Model):
description = models.CharField(max_length=200)
image = models.ImageField(upload_to=get_upload_to)
class Meta:
abstract = True
#method on the class to provide upload path for files specific to these objects
def get_upload_to_path(instance, filename):
return 'images/'+filename
class PostImage(BaseImage):
in_text = models.BooleanField()
#method to provide upload path for PostImage objects
def get_upload_to_path(instance, filename):
#change date.year etc to appropriate variables
return 'images/news/%Y/%m/%d' % (date.year, date.month, date.day)