I have a model called Photo and looks like this...
class Photo(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4)
created_at = models.DateTimeField(auto_now_add=True)
photo = models.FileField()
title = models.CharField(max_length=30)
kind = models.CharField(max_length=30)
size = models.CharField(max_length=30)
strength = models.CharField(max_length=30)
combinations = models.CharField(max_length=30)
favors = models.CharField(max_length=30)
availability = models.BooleanField(default=True)
iscarousel = models.BooleanField(default=False)
def __str__(self):
return "%s %s %s %s %s %s %s %s %s %s" % (self.created_at, self.photo, self.title,
self.kind, self.size, self.strength, self.combinations, self.favors, self.availability,
self.iscarousel)
I am can save to my aws s3 bucket but I do not have a url path to it, or so I believe this is the case. How can I save my model where once I upload my photo the url gets saved in my model as well. So I am thinking that I will need a url field and I know there is a models.UrlField or something like that. I am just curious though how I tell django to extract that url and add it to some field so I can later access it. If I don't have it I don't know how I am suppose to retrieve it to later show it on my web application
IF you use ImageField instead of FileField you will get more related to images. However both have a url attribute you can access from a django template or when querying for a specific image.
In your model it would look something like this:
image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True)
In a Django Template you would access it like this:
<img src="{{ img_obj.image.url}}" alt="connect" style="max-height:300px">
Here is a reference to more info on how to set that up
Related
I'm a newbie in Django, and I don't know how to this.
I have a model 'Seller':
class Seller(models.Model):
seller_name = models.CharField(max_length=50)
def __str__(self):
return self.seller_name
and a model 'Item':
class Item(models.Model):
seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
item_name = models.CharField(max_length=100)
item_category = models.CharField(max_length=100, choices=ALL_CATEGORIES)
item_price = models.FloatField()
item_preview = models.ImageField(upload_to='previews/<the seller's name>')
def __str__(self):
return self.item_name
connected via ForeignKey to Seller.
In this model, I have an ImageField, and I want it to upload the files to previews/Seller's name directory, but I don't know how to access the Seller's name from Item. Is it possible? Or am I doing something I am not supposed to? Because I couldn't find any similar cases in the internet.
You can access Seller name like this.
item = Item.objects.get(<condition>)
item.seller.seller_name
If you are using filter
items = Item.objects.filter(<condition>)
items[0].seller.seller_name #You need to provide index in queryset
or
for item in items:
item.seller.seller_name
you can't provide a path like that. You can either use a callable in upload_to or can use the lambda function.
item_preview = models.ImageField(upload_to=lambda instance: 'previews/{0}'.format(instance.seller.seller_name))
If you use upload_to callable
item_preview = models.ImageField(upload_to=upload_file_handler)
def upload_file_handler(instance, filename):
return 'previews/{0}'.format(instance.seller.seller_name)
I have model an Django model as follows:
class BusinessUnit(models.Model):
name = models.CharField(max_length=255)
address = models.ForeignKey(to=Address)
vat_number = models.CharField(max_length=50)
telephone = models.CharField(max_length=50)
email = models.CharField(max_length=50)
manager = models.ForeignKey(to=User, null=True)
def __unicode__(self):
return self.name
How can I change address directly from BusinessUnit in Django admin?
Now I can only select the address, but I cant change it. I need to go to Address model and change it there, but I want to be able to change it directly in BusinessUnit model.
Any idea how can I do that?
On the webpage I am currently working on I have to display profiles of different persons. Each person has a profile image that is displayed on the right side. Furthermore, I have the content saved as markdown on the server.
Now I want to add the possibility to add an optional list of images that are displayed under the text and shows something about the person. My model for the person looks like that:
class stipendiat(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
content = models.TextField()
year = models.IntegerField(blank=False, null=False)
form = models.IntegerField(blank=False, null=False)
image = models.ImageField(upload_to='stipendiaten/', blank=True, null=True, default='default.jpg')
gallery = # This is the question
def __unicode__(self):
return self.first_name + " " + self.last_name
Because I want to save some data about the image the model should look like that:
class Image(models.Model):
caption = models.CharField(max_length=512)
year = models.IntegerField()
image = models.ImageField(upload_to=upload_path_handler, blank=False, null=False)
For convenience it should be possible to add an image while editing the form for the person. To be precise, I want to add a person and fill in the necessary information (first_name, last_name, content etc.). At the end should be a list of connected images and a button to add an image rapidly.
Is it necessary to use an external app or is there an elegant solution with relation fields?
Maybe you should use a different model for the gallery images and a foreign key field to link the two models together
class Image(models.Model):
#...
stipendiat = models.ForeignKey(Reporter)
Now you can retrieve the Gallery Images for a stipendiat with id 1 like this
Image.objects.filter(stipentiat__pk=1)
I have the following models:
class Quiver(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
is_default = models.BooleanField(default=False)
type = models.CharField(max_length=1, choices=QUIVER_TYPES)
category = models.CharField(max_length=255, choices=QUIVER_CATEGORIES)
def __unicode__(self):
return u'[%s] %s %s quiver' % (
self.user.username,
self.get_type_display(),
self.get_category_display())
class Image(models.Model):
photo = models.ImageField(upload_to=get_upload_file_path)
is_cover = models.BooleanField(default=False)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
def save(self, *args, **kwargs):
try:
this = Image.objects.get(pk=self.pk)
if this.photo != self.photo:
this.photo.delete(save=False)
except Image.DoesNotExist:
pass
super(Image, self).save(*args, **kwargs)
class Surfboard(models.Model):
quiver = models.ForeignKey(Quiver)
brand = models.CharField(max_length=255)
model = models.CharField(max_length=255)
length = models.CharField(max_length=255)
width = models.CharField(max_length=255, blank=True)
thickness = models.CharField(max_length=255, blank=True)
volume = models.CharField(max_length=255, blank=True)
images = generic.GenericRelation(Image)
def __unicode__(self):
return u'%s %s %s' % (self.length, self.brand, self.model)
def get_cover_image(self):
"Returns the cover image from the images uploaded or a default one"
for image in self.images.all():
if image.is_cover:
return image
return None
I'd like to be able to have the same form I have in the admin in my frontend view /surfboard/add:
As a new Django fan and user, I started to create the form from scratch. Not being able to do what I want with including the foreign key "quiver" as a dropdown list, I found in the doc the ModelForm, and decided to use it, so here what I got:
class SurfboardForm(ModelForm):
class Meta:
model = Surfboard
In my view, it looks like this and it's already a good start:
So now, I wanted to have a way to add pictures at the same time, and they are linked to a surfboard via a Generic Relation. Here I don't find the way to do a implementation like in the admin, and get frustrated. Any tips to do so?
Thanks!
What you seek is called an inline formset - see the docs for more.
It's also handy that you can render a formset quickly with {{ formset.as_p }}, but you'll need to write some JavaScript (or use the JavaScript that's used in the Django admin) to handle adding and removing forms.
class Product(models.Model):
...
image = models.ImageField(upload_to=generate_filename, blank=True)
When I use ImageField(blank=True) and do not select image into admin form, an exception occurs.
In django code you can see this:
class FieldFile(File):
....
def _require_file(self):
if not self:
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
def _get_file(self):
self._require_file()
...
Django trac has ticket #13327 about this problem, but seems it can't be fixed soon. How to make these field optional?
blank=True should work. If this attribute, which is False by default, is set to True then it will allow entry of an empty value.
I have the following class in my article app:
class Photo(models.Model):
imagename = models.TextField()
articleimage = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
I make use of the above class in another class by using the ManyToManyField relationship:
class Article(models.Model):
pub_date = models.DateTimeField(default=timezone.now)
slug = models.SlugField(max_length=130)
title = models.TextField()
photo = models.ManyToManyField(
Photo, related_name='photos', blank=True)
author = models.ForeignKey(User)
body = models.TextField()
categories = models.ManyToManyField(
Category, related_name='articles', null=True)
I want to make images in my articles optional, so blank=True in
photo = models.ManyToManyField(Photo, related_name='photos', blank=True)
is necessary. This allows me to create an article without any images if I want to.
Are you using class Product in any relationship? If so, make sure to set blank=True in the relationship you are using.
Set null=True (see documentation)
class Product(models.Model):
...
image = models.ImageField(upload_to=generate_filename, blank=True, null=True)
If 'optional' means that you want to be able to disregard the image field altogether. Then blank=True, so do the trick. However, if you are still getting the same error, then this means that you are using it's url either in the template somewhere or you are trying to open the path of the image in models.py or views.py ( may be to resize the image or some other backend preprocessing).
That is why it is always suggested to use try - catch block while handling files.