I have following field:
photo = models.ImageField(null=True,blank=True,upload_to="product_images")
I have defined the following layout in forms.py for this field:
self.fields['photo'].label = "Asset Image"
self.helper.layout = Layout(
'photo',
HTML("""{% if form.photo.value %}
<img height="80"
width="160"
class="pull-left"
src="{{ MEDIA_URL }}{{ form.photo.value }}">
{% endif %}""", ),
Now I can upload images associated with this particular field just fine. However when I try to update the image I see the following in my template:
Is there any way I can change the layout so that only the browse button and existing image are shown when the image field is not empty? In other words, remove the text Currently: product_images/km_2.jpeg Clear Change:
I'm pretty sure ImageField uses ClearableFileInput in order to render the HTML.
So to get rid of the "Currently: ... Clear" stuff you need to subclass the ClearableFileInput and modify the template_with_clear and/or template_with_initial members.
from django.forms import ClearableFileInput
class MyClearableFileInput(ClearableFileInput):
template_with_initial = '%(input_text)s: %(input)s'
Subsequently you use MyClearableFileInput, e.g.:
class MyForm(ModelForm):
class Meta:
model = MyModel
widgets = {
"file": MyClearableFileInput(),
}
I tested this with a FileField, but I'm pretty sure it will also work with an ImageField.
Related
I have created a userUpdate view with a partial modelForm to update user data, which consists of an imageField.
Form in my template looks like:
<div class='field'>{{ form.photo.label_tag }} {{ form.photo}}</div>
Here photo is the imageField.
The rendered html view is:
But,
I don't want the clear checkbox.
How to get the url of the current image if one exists for the model instance?
What are all the properties of the photo? So, that I can individually use them as required.
clear checkbox
You need to change the widget from ClearableFileInput to Fileinput
# forms.py
from django.forms.widgets import FileInput
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = '__all__'
widgets = {
'photo': FileInput(),
}
The default FileField widget is ClearableFileInput.
https://docs.djangoproject.com/en/dev/ref/forms/widgets/#file-upload-widgets
Alternatively, You can render HTML manually for file type field.
<div class="field">
<!-- show label of field -->
{{form.photo.label_tag}}
<!-- check for input type -->
{% if form.photo.field.widget.input_type == 'file'%}
{{ form.photo.value }}<br/>
<input type="file" name="{{ form.photo.name }}" />
{% endif %}
</div>
get the URL of the current image if one exists for the model instance
You can get URL of current image using . operator
# URL of the image
photo.url
# name of the image
photo.name
properties of the ImageField
ImageField inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image.
In addition to the special attributes that are available for FileField, an ImageField also has height and width attributes.
Read the official docs for the list of all attributes
I want to add filer_image field to my Gift class instance object. It works as apphook in django-cms. The main problem is that after making migrations and open the view where the form is I don't have loaded js.
I already added all tags:
{% load staticfiles i18n cms_tags sekizai_tags menu_tags thumbnail filer_tags filer_image_tags %}
The model is:
class Gift(models.Model):
filer_image = FilerImageField(related_name="book_covers")
The form:
class GiftForm(ModelForm):
class Meta:
model = Gift
fields = '__all__'
widgets = {
'name': forms.TextInput(attrs={'class': 'basic-input full-width'}),
}
The rendered output:
The thumbnail and input view
Please tell me what am I doing wrong with these. It seems to me like some js files are not loaded. After click it opens FileImageFiler gallery, but I also cannot select any image.
Ok, i find the soliton. Basically I added {{ form.media }} after {{ csrf_token } and I have extended the form class with:
class Media:
extend = False
css = {
'all': [
'filer/css/admin_filer.css',
]
}
js = (
'admin/js/core.js',
'admin/js/vendor/jquery/jquery.js',
'admin/js/jquery.init.js',
'admin/js/admin/RelatedObjectLookups.js',
'admin/js/actions.js',
'admin/js/admin/urlify.js',
'admin/js/prepopulate.js',
'filer/js/libs/dropzone.min.js',
'filer/js/addons/dropzone.init.js',
'filer/js/addons/popup_handling.js',
'filer/js/addons/widget.js',
'admin/js/related-widget-wrapper.js',
)
That is all!
I have a model like this:
class Assignment(models.Model):
content = models.FileField(upload_to='xxx')
other_val = models.CharField(...) # not important
And a form wrapping this model (ModelForm):
class AssignmentForm(ModelForm):
class Meta:
model = Assignment
fields = ['content', 'other_val']
My view looks like this (for simplicity I skip the request.POST/request.FILES. part):
#login_required(login_url='/login/')
def create_assignment(request):
form = AssignmentForm()
# render form
#login_required(login_url='/login/')
def update_assignment(request, assignment_id):
assignment = Assignment.objects.get(id=assignment_id)
form = AssignmentForm(instance=assignment)
Creating an assignment works just fine - It forces me to upload a file, which is what I want. But when I want to update the content of the assignment (the file), it first shows a link of a previously uploaded file (excellent!) then the upload button, like this:
Currently: AssignmentTask_grading_script/grading_script_firing.py
Change: [Choose File] no file chosen
But then I assume if I don't want to replace this file, I should simply click the submit button. Unfortunately, when I click the submit button, the form complains that I should upload a file. Is there a way to silent the complaint if a file is already in database?
As following the previous comments, maybe like this;
1. forms.py
class AssignmentForm(forms.ModelForm):
# as following #Rohan, to make it optional.
content = forms.FileField(required=False)
class Meta:
model = Assignment
fields = ['content', 'other_val']
2. yourtemplate.html
<form method="post" enctype="multipart/form-data" action=".">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
<script>
{% if not form.content.value %}
$('#id_content').attr({'required': 'required'});
{% endif %}
</script>
The field of content is under required only if havn't value before...
Hi Have a choice field
class PropertyReportForm(forms.Form):
property = forms.ChoiceField(widget = forms.RadioSelect,required = False)
def __init__(self,*args,**kwargs):
properties = kwargs.pop('properties')
property_choice = []
for property1 in properties:
index = (property1.id,"Name :"+property1.name+" Area:"+str(property1.area)+" "+property1.image)
property_choice.append(index)
super( PropertyReportForm, self).__init__(*args, **kwargs)
self.fields['property'].choices = property_choice
Now while displaying I want it to display
How can I do this?
Template code similar to what I want. This does not work. But I want this
{% for field in propertyreportform %}
{{ field }} <img src="/media/{{ field.image }}" />
{% endfor %}
To solve this problem you basically have three options:
Create your own renderer, and use it as argument for ChoiceField, unfortunately you will need to create it from scratch, since django doesn't allow you to simply override RadioFieldRenderer class. https://github.com/django/django/blob/1.5.4/django/forms/widgets.py#L693
Just loop over your choices and use manually created radio input tags, there's not a lot of validation to do and retrieving selected item or model object is also simple enough.
The simplest and less recommended way could be to include the whole image tag inside label string (use settings to get media url part).
I couldn't find this in the docs, but think it must be possible. I'm talking specifically of the ClearableFileInput widget. From a project in django 1.2.6 i have this form:
# the profile picture upload form
class ProfileImageUploadForm(forms.ModelForm):
"""
simple form for uploading an image. only a filefield is provided
"""
delete = forms.BooleanField(required=False,widget=forms.CheckboxInput())
def save(self):
# some stuff here to check if "delete" is checked
# and then delete the file
# 8 lines
def is_valid(self):
# some more stuff here to make the form valid
# allthough the file input field is empty
# another 8 lines
class Meta:
model = SocialUserProfile
fields = ('image',)
which i then rendered using this template code:
<form action="/profile/edit/" method="post" enctype="multipart/form-data">
Delete your image:
<label> {{ upload_form.delete }} Ok, delete </label>
<button name="delete_image" type="submit" value="Save">Delete Image</button>
Or upload a new image:
{{ upload_form.image }}
<button name="upload_image" type="submit" value="Save">Start Upload</button>
{% csrf_token %}
</form>
As Django 1.3.1 now uses ClearableFileInput as the default widget, i'm pretty sure i can skip the 16 lines of my form.save and just shorten the form code like so:
# the profile picture upload form
class ProfileImageUploadForm(forms.ModelForm):
"""
simple form for uploading an image. only a filefield is provided
"""
class Meta:
model = SocialUserProfile
fields = ('image',)
That would give me the good feeling that i have less customized formcode, and can rely on the Django builtins.
I would, of course, like to keep the html-output the same as before. When just use the existing template code, such things like "Currently: somefilename.png" pop up at places where i do not want them.
Splitting the formfield further, like {{ upload_form.image.file }} does not seem to work. The next thing coming to my mind was to write a custom widget. Which would work exactly against my efforts to remove as many customized code as possible.
Any ideas what would be the most simple thing to do in this scenario?
Firstly, create a widgets.py file in an app. For my example, I'll be making you an AdminImageWidget class that extends AdminFileWidget. Essentially, I want a image upload field that shows the currently uploaded image in an <img src="" /> tag instead of just outputting the file's path.
Put the following class in your widgets.py file:
from django.contrib.admin.widgets import AdminFileWidget
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
import os
import Image
class AdminImageWidget(AdminFileWidget):
def render(self, name, value, attrs=None):
output = []
if value and getattr(value, "url", None):
image_url = value.url
file_name=str(value)
# defining the size
size='100x100'
x, y = [int(x) for x in size.split('x')]
try :
# defining the filename and the miniature filename
filehead, filetail = os.path.split(value.path)
basename, format = os.path.splitext(filetail)
miniature = basename + '_' + size + format
filename = value.path
miniature_filename = os.path.join(filehead, miniature)
filehead, filetail = os.path.split(value.url)
miniature_url = filehead + '/' + miniature
# make sure that the thumbnail is a version of the current original sized image
if os.path.exists(miniature_filename) and os.path.getmtime(filename) > os.path.getmtime(miniature_filename):
os.unlink(miniature_filename)
# if the image wasn't already resized, resize it
if not os.path.exists(miniature_filename):
image = Image.open(filename)
image.thumbnail([x, y], Image.ANTIALIAS)
try:
image.save(miniature_filename, image.format, quality=100, optimize=1)
except:
image.save(miniature_filename, image.format, quality=100)
output.append(u' <div><img src="%s" alt="%s" /></div> %s ' % \
(miniature_url, miniature_url, miniature_filename, _('Change:')))
except:
pass
output.append(super(AdminFileWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))
Ok, so what's happening here?
I import an existing widget (you may be starting from scratch, but should probably be able to extend ClearableFileInput if that's what you are starting with)
I only want to change the output/presentation of the widget, not the underlying logic. So, I override the widget's render function.
in the render function I build the output I want as an array output = [] you don't have to do this, but it saves some concatenation. 3 key lines:
output.append(u' <div><img src="%s" alt="%s" /></div> %s ' % (miniature_url, miniature_url, miniature_filename, _('Change:'))) Adds an img tag to the output
output.append(super(AdminFileWidget, self).render(name, value, attrs)) adds the parent's output to my widget
return mark_safe(u''.join(output)) joins my output array with empty strings AND exempts it from escaping before display
How do I use this?
class SomeModelForm(forms.ModelForm):
"""Author Form"""
photo = forms.ImageField(
widget = AdminImageWidget()
)
class Meta:
model = SomeModel
OR
class SomeModelForm(forms.ModelForm):
"""Author Form"""
class Meta:
model = SomeModel
widgets = {'photo' : AdminImageWidget(),}
Which gives us: