Hiii every one.
I am new to Django and start to create a basic project
and now i have a problem with ImageField and Upload_To
i have a model that have some field, like (car_name) and (photo) and i called that "Cars"
admin can create a new car and select an image
and
type a name for that car
then admin hit save button
and now image should save somewhere
I want to save that image into this path:
photos/Cars/???car_name???
my question is: how get the name of car and use that name to use in ((upload_to = path))?
im really sorry if i have writing issue 🙏🙏🙏
This is my code:
class Cars(models.Model):
car_name= models.CharField(max_length = 40)
photo = models.ImageField(upload_to=f"photos/Cars/{car_name}")
def get_upload_path(instance, filename):
return os.path.join(instance.first_name, filename)
class Cars(models.Model):
car_name= models.CharField(max_length = 40)
photo = models.ImageField(upload_to=get_upload_path)
this worked to me
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 a function that process images that are uploaded by users. I made a view that when entered apply the function on the uploaded images.
models.py
class UploadedImages(models.Model):
patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images')
pre_analysed = models.FileField(upload_to = user_directory_path ,
verbose_name = 'Image')
class Processed(models.Model):
uploaded_image = models.ForeignKey(UploadedImages,on_delete=models.CASCADE,related_name='processed')
analysedimage = models.ImageField(upload_to=analyses_directory_path,
verbose_name='analysed Image', blank=True)
views.py
def AnalysedDetails(request,pk=None):
Uimage = get_object_or_404(models.UploadedImages,pk=pk)
analysed = models.Processed(uploaded_image=Uimage,analysedimage=main(Uimage.pre_analysed.path))
analysed.save()
return HttpResponse("OK")
but when i check the admin page to see the model it only saves the uploaded image and doesn't save the processed one and when I check the directory i find that only the uploaded image field is saved.
I tried
analysed=models.Processed(uploaded_image=Uimage.pre_analysed,analysedimage=main(Uimage.pre_analysed.path))
but it returns
Cannot assign "":
"Processed.uploaded_image" must be a "UploadedImages" instance
to create new object, theres simple way, using .create(),
see this how to create object
so, it would be
analysed = models.Processed.objects.create(...)
and you don't need save() method if you use this way
to save ImageField programmatically, you can see this or this
def uploadPath(instance,filename):
return ''.join([instance.uploadPath(), filename])
class abstractClass(models.Model):
image = models.ImageField(upload_to=uploadPath, default='default.png')
class Meta:
abstract = True
class A(abstractClass):
manager = CharField(max_length=30, default='')
uploadPath = 'managerPhoto/'
def __str__:
return self.manager
class B(abstractClass):
worker = CharField(max_length=30, default='')
uploadPath = 'workerPhoto/'
def __str__:
return self.worker
Okay guys this is just an example code I wrote up so don't shoot me if it doesn't work. In this example both class A and B inherit an image field and we have a callable uploadPath that will check the value of uploadPath on the corresponding model and assign it for this model instance but, I would like to set the upload path starting point as the 'managers' name so say we have Manager = 'Tim' we have a folder called Tim with his image in there but I would like to have class B generate its new folder within 'Tim' folder for all the workers that work for him. How do I go about doing this or possibly reverse query?
one option I tried working with was during the call to uploadPath(instance,filename) ''.join([instance.str(),'/',instance.uploadPath,filename])
I inserted instance.str() to get the instance returned name but, this is model specific.....
I'm a noob django developer, I can upload images but name of the images have to be changed to image ID or whatever I want.
In addition to this, when I delete entries, images are still resting in the media file but I don't want this.
What I have to add ?
Here is my models.py
from django.db import models
class Flower(models.Model):
name = models.CharField(max_length = 30)
price = models.IntegerField()
image = models.ImageField(upload_to = 'static/media')
def __unicode__(self):
return self.name
To customize the path and filename of where the files are stored, you'll need to define a method for upload_to. Here's an example:
def my_upload_to(instance, filename):
# "instance" is an instance of Flower
# return a path here
return 'my/path/to/storage/' + filename
class Flower(models.Model):
image = models.ImageField(upload_to=my_upload_to)
See https://docs.djangoproject.com/en/dev/ref/models/fields/#filefield
To delete the underlying file, you'll need to make a call manually:
flower = Flower.objects.get(id=1)
flower.image.delete()
You can choose to override your model's delete() method, or use signals pre_delete or post_delete to delete the associated files automatically.
See https://docs.djangoproject.com/en/dev/ref/models/fields/#filefield-and-fieldfile
sorry if this is an obvious question but I have been searching for a few days and have not been able to come up with a result.
I am creating a simple photo gallery app. There are four galleries, each containing a photo (the photo consists of a 'before' image, 'after' image and caption). I am trying to use django-admin to allow users to click on a gallery and then add photos.
I am using a TabularInline to edit the photos within each gallery. In addition to the default columns on the TabularInline, I would like to add a column that shows a thumbnail preview of the 'before' photo and 'after' photo (I am using easy-thumbnails for this). After much searching, it seems like the best way to do this is to override the django-admin tabularInline.html template and add the column myself - so I created another copy and am trying to edit it now.
What I would like to do is simply reference the Photo object within the Django admin template that I am overriding - but I don't know the appropriate tag to use. I need the reference so I can use it in conjunction with the easy-thumbnails thumbnail tag ... but for the life of me I cannot figure out the template tag that references the object. I have tried iterating through the ModelForm, FormSet, and FieldSet objects but none seem to give me a direct reference to the object.
# models.py
class Gallery(models.Model):
name = models.CharField(max_length=200)
url = models.CharField(max_length=200)
desc = models.TextField()
def __unicode__(self):
return self.name
class Photo(models.Model):
gallery = models.ForeignKey(Gallery)
before = models.ImageField(upload_to='gallery')
after = models.ImageField(upload_to='gallery')
caption = models.CharField(max_length=1000)
order = models.IntegerField(blank = True, null = True)
def __unicode__(self):
return "Photo " + str(self.order)
# admin.py
class GalleryForm(forms.ModelForm):
model = Gallery
class Media:
js = (
'/assets/js/jquery-1.4.2.min.js',
'/assets/js/jquery-ui-1.8.2.custom.min-admin-sortable.js',
'/assets/js/menu-sort.js',
)
class PhotoInline(admin.TabularInline):
model = Photo
extra = 1
template = "admin/tabular-thumbnails.html"
admin.site.register(Gallery,
inlines=[PhotoInline],
form = GalleryForm)
Thanks so much in advance and please let me know if there's any additional information I can offer. I am using Django 1.1
In Django 2.1 {{adminform.form.instance.field_name}} worked for me.
{{ form.instance }} will always be the model instance associated with a modelform, assuming there is one.
(Note that ``{{ formset.instance }}` is the instance of the parent model in an inline formset).