I'm trying to remove the clear checkbox in Django's ImageField and remove the displayed current value of the file. Tha approach I tried is to replace the widget as proposed here How to not render django image field currently and clear stuff? but the result is that I get ValidationError :
"Upload a valid image. The file you uploaded was either not an image or a corrupted image.". Though the validation error the image get's uploaded, but I do not get redirected to the success page and an error is being rendered in the form.
What's the recommended way to remove the current value in the ImageField?
A solution that works for me, though I'm not sure how good is it.
profile_picture = forms.FileField(label='Upload profile picture', widget=forms.FileInput,validators=[validators.validate_image_file_extension], required=False)
I replaced ImageField with FileField and then added the ImageField default validator with FileInput widget and then added 'accept': 'image/*' to that widget, so the select shows only images. In this way I mimic the ImageField, but no error occurs.
Related
I have a simple blog app, when I update an article and remove photo I want it to use default photo.
it selects that image on create but when updating it throws an error.
here's my Models.py code.
image = models.ImageField(
upload_to="uploads/articles/",
null=True,
blank=True,
default="uploads/articles/noimage.png",
)
the error I get when I remove image during update.
Error during template rendering
The 'image' attribute has no file associated with it.
<img class='article-img' src="{{article.image.url}}" alt="">
You can use Django Signals
on delete or update or create, please read more about it.
It is like run trigger on model for example when update method happen you can check image field if it empty you can add image to it.
solution 2: override save method in django model and apply previous condation
solution 3: make static field using #proparty and check from front end if there is no image .. render this field
solution 4: I'm not sure about it but you can check on_delete=models.SET_DEFAULT
I am working on a project where we want the profile pic of user to be in a CharField i.e longtext. Now, in ModelForm for updating the user's profile I want to get profile pic and want to resize and compress it and save it in database with unique name like using timestamp.
The problem that I have is that I can get image name using cleaned_data from form but cannot process it for resize or compression and it gives me the error of no file or directory is found
So i wanted to ask how does these 2 fields works.
As my friend told me that his ios will sent byte format image to me, does it matter if i use imageField instead of BinaryField ?
I did try adding a Binaryfield into my User models but when testing it out on django admin and also django rest framework api, it doenst work
In django admin : the binaryfield did not appear in it
In django rest framework : got an error that says editable is false for binary field. Setting the binaryfield editable=True also doesnt work.
The documentation about Binaryfield in django is also not much.
Can anyone please explain to me how does these 2 field work ? does sending byte format to the imagefield work ?
The ImageField takes care of pictures. Otherwise, ImageField and FileField are the same. Both store the path to a file of the pysical volume.
And both do not meet the requirements.
The database requires a BinaryField:
models.BinaryField (blank = true, null = true, editable = true)
So far so good. With editable = True, the field should appear in the admin interface. But to see the picture, it has to be transformed again before
encoded = b64encode (model.image) .decode ('ascii')
and e.g. poured into a form.
render_to_string ('lib / forms / imageform.html', {"image": encoded}, request).
The form element in my case looks like this:
<form id = "{{form.fid}}" class = "form-horizontal data-form" enctype = "multipart / form-data" method = "post">
<img src = "data: image / png; base64, {{image}}">
</ Form>
ImageField or FileField is what you should use to save images. Both of these fields just save the file_path (Ex: /static/user_images/smith.jpg) to the physical image stored on the server.
For more detail read this FileField and ImageField
BinaryField not used to save images. For more detail
Note : that you never store a physical file to a Database. That is you don't use BinaryField for images.
I'm using Django Crispy Forms for my form with an option to upload an image (ImageField in my Model)
The forms renders as I'd expect, with the checkbox to clear an existing file. However when processing the form submission the 'image-clear' checkbox always gives me a 'None' value.
image_clear = form.cleaned_data.get("image-clear")
print image_clear
In the HTML of the page I notice that the input checkbox doesn't have a value attribute, see:
<input id="image-clear_id" type="checkbox" name="image-clear">
So I wondered if this was the issue, but when I look at the rendering in the Django admin site, the corresponding HTML input field doesn't have a value either - yet it still identifies that the image should be removed.
I should note that if I upload a new image, then this works, it's only the case where I'm removing/clearing the image (and it works in Django admin pages, so assume that means my model definition is ok to allow no image to be attached to the model)
So... in my form processing, how do I detect whether or not the image should be removed or not?
I'm sure I'm missing something simple here - and any help much appreciated.
You shouldn't check the checkbox, but check the value of the file input field. If it is False, then you can delete the file. Otherwise it is the uploaded file. See: https://github.com/django/django/blob/339c01fb7552feb8df125ef7e5420dae04fd913f/django/forms/widgets.py#L434
# False signals to clear any existing value, as opposed to just None
return False
return upload
Let me add here my code that solved the problem - I decided to put this logic to ModelForm.clean():
class Document(models.Model):
upload = models.FileField(upload_to=document_name, blank=True)
class DocumentForm(ModelForm):
def clean(self):
cleaned_data = super(DocumentForm, self).clean()
upload = cleaned_data['upload']
if (upload == False) and self.instance.upload:
if os.path.isfile(self.instance.upload.path):
self.instance.upload.delete(False)
I have a Page model that basically describes an HTML page. Pages are then served with URLs, such as http://www.mysite.com/page/1234/ for the page of id (pk) 1234.
I want to be able to add or attach images to my page. Therefore, I would like to use an Image class with a foreign key to a Page object:
class Page(models.Model):
title = ...
content = ...
class Image(models.Model):
page = models.ForeignKey(Page)
image = models.ImageField(...)
Here is my problem: I would like to deliver images to the client with urls of the form:
http://www.mysite.com/images/1234/image_name.jpg, i.e a URL that includes the page id. Also on the server, the paths should reflect the page structure: /path/to/media/images/1234/image_name.jpg
I don't know how to tackle this problem. On one hand, I would like to keep the features of an ImageField related to path formatting. For example when uploading two images with the same name, Django creates two paths ending with "image.jpg" and "image_2.jpg" or so to make the difference between both images.
On the other hand, the upload_to option has limited capability, and I don't know how to insert the page id in the path. Especially, some tricky cases such as uploading an image at the same time a page is created (using the same form), which means a page id should be generated before uploading the image.
Is it reasonably easy to make an image model that would behave as described above? If so, how do I have to modify the Image model to insert the page id in the image path?
I have seen the question Customize save path for ImageField, but it does not address the problem of primary key that might not be assigned.
Thanks.
Actually, a simple function passed as an upload_to parameter works, and there is no problem of non-existing id. So I guess that Django's default behaviour saves the image after saving the parent page model, as I wanted to.
In the Image model:
image = models.ImageField(upload_to=get_image_path)
with the following function:
def get_image_path(instance, filename):
return 'pics/' + str(instance.page.id) + '/' + filename