I'm getting used to Django and I want to upload a stack of images via browser. The user must be able to upload the whole stack from one field to store the images in the database keeping the order. I think I'm looking for something like:
Class Foo(models.Model):
MultiImageField(upload_to = "/stack_name/").
And i have the models like this:
class Stack(models.Model):
user = models.ForeignKey('auth.User')
name = models.CharField(max_length=128)
class Images(models.Model):
position = models.PositiveIntegerField()
stack = models.ForeignKey(Stack)
originalImg = models.ImageField(upload_to='/stacks/')
I'm pretty lost with this, Is there any way to do it?
Thanks.
Related
I have a model that has an ImageField. I want users to be able to upload multiple images for an object of the model - not only a single image. How can this be done? Whether with and image field or another approach.
You cannot store several images in one ImageField.
One solution for this problem would be to create an additional model (I called it "Attachment" for my social network pet project, call your's whatever should suit you) and have it reference the original model in a Foreign key. That way you can upload as many images as you want and create an instance of that new model for each new image.
Example Attachment model:
class Attachment(DatetimeCreatedMixin, AuthorMixin):
class AttachmentType(models.TextChoices):
PHOTO = "Photo", _("Photo")
VIDEO = "Video", _("Video")
file = models.ImageField('Attachment', upload_to='attachments/')
file_type = models.CharField('File type', choices=AttachmentType.choices, max_length=10)
publication = models.ForeignKey(TheOriginalModelYouUsedImageFieldIn, on_delete=models.CASCADE, verbose_name='Model that uses the image field')
class Meta:
verbose_name = 'Attachment'
verbose_name_plural = 'Attachments'
I have the folllowing class model in my Django website:
class Buy(models.Model):
category = models.ForeignKey(Category, related_name='sell', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
image = models.FileField()
image2 = models.FileField(blank=True)
description = models.CharField(max_length=300)
date = models.DateField(default=timezone.now)
buy_price = models.DecimalField(max_digits=6, decimal_places=2)
sell_price = models.DecimalField(max_digits=6, decimal_places=2)
seller = models.ForeignKey(Seller, on_delete=models.PROTECT)
showcase = models.BooleanField(default=False)
As you can see, I store photos files with 2 fields: image and image2. But now my client requested me to add more photos. My doubt is:
Should I continue adding new fields to this class, for example, image3, image4, image5 and so on? The problem I see: not every records will have so many photos and the most of them will become "empty".
Should I only upload the new photos without saving their names into the database? In this way, the new photos should follow some name related to the image class field. I mean, unique_photo_1.jpg goes inside the image field, unique_photo_2.jpg is not saved into the database but is related to this field, as well as the unique_photo_3.jpg.
What is the best practice?
Thank you!
On #1, the best practice is to follow database normalization principles, and create a separate Image model that relates back to your Buy model. If you anticipate that the images may be reused in several Buy model instances, use many-to-many relationships; otherwise, use many-to-one (i.e. ForeignKey). That means removing image and image2 from your Buy model, and then creating e.g.:
class Image(models.Model):
image = models.FileField()
image_type = models.CharField()
buy = models.ForeignKey(Buy, on_delete=models.PROTECT)
By #2, if you mean you're considering skipping using FileField or ImageField to instead write code that will search for files in some storage space, then that doesn't sound like a good idea, because then you're divorcing your file (meta)data from the rest of your database contents. Using FiledField/ImageField will also make it much easier to use storage backends such as AWS S3.
I'm building a Djano application which displays a set of images, and a form for each image for recording specific image characteristics. The user initializes a "project", where they specify the set of images that will be displayed for assessment. At project initialization, I'd like to give the user the ability to add custom boolean fields (i.e. a set of checkboxes), but I can't figure out how to build the database models.
For example, a user might initialize my_project with image_A.png, image_B.png and image_C.png for assessment. The default form they'll get for each image lets them choose between PASS, FAIL and UNKNOWN. They might wish to add custom fields like "poorly cropped", "over-exposed" or "blurry" (the idea being that the image could be a global PASS, but small failures, specific to the context of this image set, could still be recorded).
Generally, I'm trying to come up with a way to model user-generated fields in Django.
If I correctly understand, you don't need dynamic model fields, instead you can add model, which contains specific attributes for image in project, something like:
class Image(models.Model):
name = models.CharField()
img = models.ImageField()
class ProjectImage(models.Model):
image = models.ForeignKey('Image')
project = models.ForeignKey('Project')
flag = models.CharField(choices=PASS_FAIL_UNKNOWN)
class ProjectImageTag(models.Model):
project_image = models.ForeignKey(ProjectImage)
value = models.CharField()
class Project(models.Model):
images = models.ManyToManyField('Image', through=ProjectImage)
Also, you can store such tags in json field or postgres hstore field instead of separate table.
EDIT
Variation with predefined keys:
class ProjectImage(models.Model):
image = models.ForeignKey('Image')
project = models.ForeignKey('Project')
flag = models.CharField(choices=PASS_FAIL_UNKNOWN)
class Image(models.Model):
name = models.CharField()
img = models.ImageField()
class Project(models.Model):
images = models.ManyToManyField('Image', through=ProjectImage)
class ProjectImageParams(models.Model):
project_image = models.ForeignKey(ProjectImage, related_name='params')
key = models.CharField()
value = models.BooleanField()
Params of image may be obtained with ProjectImage().params.all(). And yes, django-eav may be a good option.
I have Document model:
class Document(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=255)
description = models.TextField()
content = models.TextField()
and DocumentRelation model:
class DocumentRelation(models.Model):
document_a = models.ForeignKey(Document,related_name='doc_a')
document_b = models.ForeignKey(Document,related_name='doc_b')
I have single_document views:
def single_document(request,id):
doc = Document.objects.get(id=id)
return render_to_response('single_file.html',{'doc':doc},context_instance=RequestContext(request))
In single_file.html I have:
Add related document
I need create views def add_relation(request,id):. What is the best way to add the relationship? I need a preview of the document that to be added as related. How to solve it?
(I ask about the overall design. How to solve it)
First, why are you not using a ManyToManyField in the document model like this :
related_documents = models.ManyToManyField('self')
Then you can use a two steps form if you do not want to use javascript (one to select, another to confirm and display the related document).
If you want, you can also use javascript and dynamically load the related document when the user select it.
When I creating my django models I stacked up at this point.
Now, I have a model like this:
class My_Files(models.Model):
file_name = models.CharField(max_length=50)
file_size = models.IntegerField()
... etc ...
And these files must have a relation with file which it can be uploaded to my server or http link to another server. How can I handle this relation?
Thank You
You need to use django-uploadify it helps you, in the manner such that, whenever a new file is uploaded a signal is fired with the file data, you can use that signal to populate your models. It is much easier than writing a custom signal for yourself. Hope it helps!
class My_Files(models.Model):
file_name = models.CharField(max_length=50)
file_size = models.FloatField()
file_url = models.URLField(blank=True)
file_locate = model.CharField(max_length=255, blank=True)
You also should write many methods in views and forms to fill any needed fields.