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.
Related
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.
I was wondering if there is a field (A model field) that represents a remote image.
What I need is to add an image field to my model that isn't stored locally, but is given a remote URL and can only be viewed, not edited or uploaded.
Edit: To make myself more clear, I meant I need a field such as URLField that can store a URL (to the image) but that in the admin page, (or other forms) it will show the image like ImageField does.
A URLField is an extension of the CharField and can store a valid URL that points to an image. Note that you will not be able to upload an image, only reference an image that already exists on the web.
class MyModel(models.Model):
remote_image = models.URLField()
In your view you can set the remote image with a string:
my_instance = MyModel()
my_instance.remote_image = 'http://example.com/images/example.jpg'
my_instance.save()
You can display the remote image in your template by setting the src attribute:
<img src="{{ my_instance.remote_image }}">
Django has a file storage API. The default storage class is the FileSystemStorage, that stores your images using the file system.
One of the best things about Django is its huge ecosystem: you can find storage classes for S3 and other popular hosting services.
It is somewhat easy to write your own, also.
You can use URLField to store the source URL and handle viewing the image a django View that you build, I can imagine that your django View can read data using your model (including the image source URL), set it in context dictionary object, which can be read from the HTML template of your view to display the image.
Please read about django Views and Templates for more info.
I have a django ModelForm with an image field. I want to resize the image when the user submits the form, but only if they uploaded a new image. My code looks like this:
class EditProfileForm(forms.ModelForm):
class Meta:
model = Person
fields = ['picture', '...']
def clean_picture(self):
picture = self.cleaned_data['picture']
if picture.file: #This isn't right though
#resize it
return picture
However it seems like picture.file always exists if the model being edited contains a file. I know I can check request.FILES back in the view, but that's very inelegant. Is there a better way?
In general, you can do this with self.changed_data, which returns a list of the names of the fields where the value changed. Whether there's anything special about a FileField that would interfere I don't know offhand.
In js,
In JS, set a global variable file_changed = 0.
HTML input tag < input ng-model="avatar" type="file" onchange="ChangeFile()">
Lets say ChangeFile() will provide a small preview of the file to be uploaded
In function ChangeFile set file_changed=1 once the file is selected.
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