Skip to content

Instantly share code, notes, and snippets.

@solanoize
Last active July 1, 2017 07:44
Show Gist options
  • Select an option

  • Save solanoize/c3226010d33c4fcceddf48363e5d2be0 to your computer and use it in GitHub Desktop.

Select an option

Save solanoize/c3226010d33c4fcceddf48363e5d2be0 to your computer and use it in GitHub Desktop.

Saya kepingin image yang saya upload hanya berjenis jpg dan gif saja saja dengan batasan sizenya hanya kurang atau sama dengan 2 mb ? Bisakah ? bisa ! memang Django hanya menyediakan Field ImageField hanya untuk semua file berjenis image dengan kapasitas yang kita belum batasi. Caranya gimana ?

Buat file bernama fields.py di dalam folder app, tambahkan kode berikut ini untuk membuat field baru yang kita extends dari class FielField pada package django.db.models:

from django.db.models import FileField
from django.forms import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _


class ImageFieldRestrict(FileField):

	def __init__(self, *args, **kwargs):
		self.content_types = ['image/jpeg', 'image/gif']
		self.max_upload_size = 2242880
		super(ImageFieldRestrict, self).__init__(*args, **kwargs)

	def clean(self, *args, **kwargs):
		data = super(ImageFieldRestrict, self).clean(*args, **kwargs)
		file = data.file
		try:
			content_type = file.content_type
			if content_type in self.content_types:
				if file._size > self.max_upload_size:
					message = 'Please keep filesize under {}. Current file size %s'
					message = message.format(filesizeformat(self.max_upload_size), filesizeformat(file._size))
					raise forms.ValidationError(_(message))
			else:
				raise forms.ValidationError(_('Filetype not supported.'))
		except AttributeError:
			pass

		return data

Cara penggunaannya mudah. Buka file models, lalu gunakan class pada salah satu field di model yang kita anggap sebagai field untuk image (perhatikan pada field pic!):

from .fields import ImageFieldRestrict

class Photo(models.Model):
	user = models.ForeignKey('auth.User', related_name="user_photos")
	booklet = models.ForeignKey(Booklet, related_name="photos")
	about = models.CharField(max_length=100)
	pic = ImageFieldRestrict(upload_to='photo/%Y/%m/%d')
	created = models.DateTimeField(auto_now_add=True)

	def __str__(self):
		return self.booklet.title

	class Meta:
		ordering = ('-created',)

Silahkan lakukan migrasi. Coba upload gambar berejenis png atau upload gambar berjenis jpg tapi sizenya melebihi 2mb. Akan muncul pesan validasi.

from django.db.models import FileField
from django.forms import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
class ImageFieldRestrict(FileField):
def __init__(self, *args, **kwargs):
self.content_types = ['image/jpeg', 'image/gif']
self.max_upload_size = 2242880
super(ImageFieldRestrict, self).__init__(*args, **kwargs)
def clean(self, *args, **kwargs):
data = super(ImageFieldRestrict, self).clean(*args, **kwargs)
file = data.file
try:
content_type = file.content_type
if content_type in self.content_types:
if file._size > self.max_upload_size:
message = 'Please keep filesize under {}. Current file size %s'
message = message.format(filesizeformat(self.max_upload_size), filesizeformat(file._size))
raise forms.ValidationError(_(message))
else:
raise forms.ValidationError(_('Filetype not supported.'))
except AttributeError:
pass
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment