Coder Social home page Coder Social logo

aneesh2usman / django_cropper_image Goto Github PK

View Code? Open in Web Editor NEW
13.0 2.0 4.0 3.59 MB

django-cropper-image is an app for client side cropping and compressing uploaded images via Django's app using with help cropper.js

License: MIT License

Python 13.04% CSS 33.96% JavaScript 49.29% HTML 3.70%
cropping cropper django-cropper upload-image compress-image

django_cropper_image's Introduction

django-cropper-image

django-cropper-image is an app for client side cropping and compressing uploaded images via Django's app using with help cropper.js cropperjs. github link django-cropper-image.

Screenshot:

https://github.com/aneesh2usman/django_cropper_image/blob/main/doc/Screenshot.png

django-cropper-image is very usefull image upload with a specific size for your templates. it is more userfriendly no need add more field for cropping data storage in your db. django-cropper-image is keep both cropped image and orginal image and also setting custom configuration as you need like aspect ratio (3:4,16:9) vise versa. and you can set minimum and maximum crop width and height. it can also set compressing of image.

Installation

  1. Install django-cropper-image using pip:

    pip install django-cropper-image
    

Configuration

  1. settings.py:

    INSTALLED_APPS = [
            ...
            'django_cropper_image',
        ]
    '''
    DJANGO_CROPPER_IMAGE_SETTINGS is optional
    
    Notes : Please use
            if you use "EXCLUDE_CROPPERJS" please manually include your cropper js and css files
    
    Warning : Change only if you need to CROPPERJS_STATIC_JS,CROPPERJS_STATIC_CSS,CUSTOM_STATIC_JS,CUSTOM_STATIC_CSS,TEMPLATES
    '''
    
    DJANGO_CROPPER_IMAGE_SETTINGS ={
        'EXCLUDE_CROPPERJS':False, #can excude cropperjs js and css files
        'CROPPERJS_STATIC_JS':'django_cropper_image/js/cropper.min.js', # can change cropper js file
        'CROPPERJS_STATIC_CSS':'django_cropper_image/css/cropper.min.css',# can change cropper css file
        'CUSTOM_STATIC_JS':'django_cropper_image/js/image_cropper.js', # can change django_cropper_image module custom js
        'CUSTOM_STATIC_CSS':'django_cropper_image/css/image_cropper.css', # can change django_cropper_image module custom css
        'TEMPLATES':'django_cropper_image/image_cropper_input.html', # can change django_cropper_image module template files
    }
    

models

Add an ImageCropperField to the model that images you want to crop.you don't worried about if form error occure the image is remove

  1. Models.py:

    from django.db import models
    from django_cropper_image.fields import ImageCropperField
    
    class Images(models.Model):
        image = ImageCropperField(upload_to='image',max_length=255)
    

forms

  1. forms.py:

    from django import forms
    from django.forms import ModelForm
    from .models import Images
    
    class ImageForm(ModelForm):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # Form configuration is optional. You can change the default.
            self.fields['image'].widget.attrs.update({
                'data-aspectratio_w':16, #aspect ratio of width (Default : 1)
                'data-aspectratio_h':9, #aspect ratio of height (Default : 1)
                'data-mincropWidth' : 300, #minimum crop width
                'data-mincropHeight' : 300, #minimum crop height
                'data-maxcropWidth' : 600, #maximum crop width
                'data-maxcropHeight' :600, #maximum crop height
                'data-cropRestrict':"true", #minimum and maximum  work only when cropRestrict true
                'data-mincontainerwidth' : 300, #minimum width of image container
                'data-mincontainerheight' : 300,#minimum height of image container
                'data-filesize' : 0.5, #. 1 mb 2mb if the file size reach config file size it will be compress
                'data-fileresolution' : 0.7, #.0.7 medium resolution
                'data-fillcolor' : '#fff', #color of the cropped image background
                'data-maxmainimagewidth' : 2000, #uploaded image maximum width height take accordingily
                'data-compress':"true", # compress yes:No (Default : true)
                'data-orginal_extension':"false", # (Default : false)  if .png no chnage in png file otherwise convert jpg
    
    
            })
    
        class Meta:
            model       = Images
            fields      = "__all__"
        def clean(self, *args, **kwargs):
            self.cleaned_data = super().clean(*args, **kwargs)
    

views

  1. views.py:

    from django.shortcuts import render
    from django.http import HttpResponse,HttpResponseRedirect
    from django.views import View
    from django.urls import reverse
    from .forms import ImageForm
    from .models import Images
    from django.conf import settings
    class ImageView(View):
        template_dir = "example_project/"
        def get(self, request, *args, **kwargs):
            if 'id' in kwargs and kwargs['id']:
                context={}
                instance =  Images.objects.filter(pk =kwargs['id'] ).first()
                form = ImageForm(instance =instance)
                context['form'] =form
                context['form_media'] =form.media
            elif 'delete_id' in kwargs and kwargs['delete_id']:
                instance =  Images.objects.filter(pk =kwargs['delete_id'] ).delete()
                return HttpResponseRedirect(reverse('image_add'))
    
            else :
                context ={}
                form = ImageForm()
                context['form'] =form
                context['form_media'] =form.media
            #Send to the render view page
            return render(request, self.template_dir+'home.html',context)
        def post(self, request, *args, **kwargs):
    
            context ={}
            if 'id' in kwargs and kwargs['id']:
                instance =  Images.objects.filter(pk =kwargs['id'] ).first()
                form = ImageForm(request.POST or None,request.FILES or None,instance =instance)
                if request.POST and form.is_valid():
                    form.save()
    
                    return HttpResponseRedirect(reverse('image_edit',kwargs={'id':kwargs['id']}))
            else :
    
                form = ImageForm(request.POST or None,request.FILES or None)
                if request.POST and form.is_valid():
                    form.save()
                    return HttpResponseRedirect(reverse('image_add'))
            context['form'] =form
            context['form_media'] =form.media
    
            #Send to the render view page
            return render(request, self.template_dir+'home.html',context)
    

templates

  1. templates.html:

    {% load static %}
    {% load i18n %}
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="Django image cropper.">
    <meta name="author" content="Aneesh Usman">
    {% block stylesheet %}
    {% if form_media.css %}
        {{ form_media.css }}
    {% endif %}
    {% endblock %}
    <title>Django Image Cropper</title>
    </head>
    <body>
    
    <form method="{{form.method|default:'POST'}}" enctype="multipart/form-data" class="{{form.class}} m-form m-form--fit m-form--label-align-right" action="{{form.action|default:request.path}}" novalidate>
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit">
    </form>
    
    
    <!-- Scripts -->
    
    <script src="/static/example_project/js/jquery-3.4.1.slim.min.js" crossorigin="anonymous"></script>
    <script src="/static/example_project/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
    {% block javascript %}
            {% if form_media.js %}
            {{ form_media.js }}
            {% endif %}
        {% endblock %}
    
    </body>
    </html>
    

django_cropper_image's People

Contributors

aneesh2usman avatar carlguo866 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

django_cropper_image's Issues

Not provided image is not handled

I would like to use the app to make profile photo upload easy. I have a default User model in Django (5.01) and there is a Profile model with one to one link to the user model. When a user registers, I create a Profile instance with th foreign key and leave the other blank. Here is the field definition:

from django_cropper_image.fields import ImageCropperField
class UserProfile(models.Model):
...
avatar = ImageCropperField(verbose_name="Profil fotó",
                               upload_to="photos/%Y/%m",
                               max_length=255,
                               blank=True,
                               null=True)
...

When I try to save my profile, where the avatar field is empty as all the others but the user, I got an exception:

AttributeError: 'NoneType' object has no attribute 'get'

The issue is within your fields.py file at row 184 in pre_save method, the following line:

self.b64data = self.cropperconstobj.get()

Obviously the self.cropperconstobj is None.

Readme

@aneesh2usman could you add the compatible python and django versions in the readme?
That'd be quite helpful.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.