Django Admin add support for HEIC for ImageField - python

please has someone experience with adding support of new image formats to the Django Admin module? I want to use this one called pyheif-pillow-opener pyheif-pillow-opener for HEIC support. It should be registered, but I am not sure where exactly. I tried to install that module and then in Django Admin upload an image to ImageField, but still, I am getting a message:
Upload a valid image. The file you uploaded was either not an image or a corrupted image.
EDIT - Solution:
There is only need to add to a used Django applications admin.py file these lines of code:
from pyheif_pillow_opener import register_heif_opener
register_heif_opener()

Another solution(add it to admin.py as TS suggest):
try:
from pillow_heif import HeifImagePlugin
except ImportError:
HeifImagePlugin = None # here you can log a warning

Related

How to delete existing image while uploading new image in django

Let say I have a model which has a profile pic image field.As a user I uploaded a profile pic.When I upload a new profile pic, old profile has to get deleted.
How to handle this scenario in development and production stage
Use django-cleanup, it automatically deletes unnecessary files from server.
pip install django-cleanup
And add it to your settings.py:
INSTALLED_APPS = [
...
'django_cleanup'
]
Possible duplicate of:
https://stackoverflow.com/a/28986357/7320045

save() doesn't work in Mongoengine

I'm trying to perform a simple insert operation using Mongoengine and Django.
Regarding my project structure simply I have a project, AProject and an app, AnApp. I have a running mongo in a remote machine with an IP of X.X.X.X. I am able to insert document using Robomongo in it.
I have removed the default Database configuration part of the settings.py located inside the AProject directory. The newly added lines are shown below:
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
import mongoengine
# ----------- MongoDB stuff
from mongoengine import register_connection
register_connection(alias='default', name='AProject', host='X.X.X.X')
# ----------
Now let me show the models.py and the views.py located inside AnApp.
models.py
from mongoengine import Document, StringField
class Confession(Document):
confession = StringField(required=True)
views.py
from django.http import HttpResponse
from models import Confession
from mongoengine import connect
def index(request):
connect('HacettepeItiraf', alias='default')
confession = Confession()
confession.confession = 'First confession from the API'
print(confession.confession + ' Printable') # The output is --First confession from the API Printable--
print(confession.save()) # The output is --Confession object--
return HttpResponse(request)
The urls.py located inside AProject is simply as below:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^confessions/', include('confession.urls')),
url(r'^admin/', admin.site.urls),
]
When I enter http://127.0.0.1:10000/confessions/ I see a blank screen which I expect. However there is nothing saved from the API. I get the expected output except Confession object.
How can I solve this problem?
EDIT:
I found the concrete proof that currently MongoEngine's support for Django is unstable and it is corresponding to Django version 1.9:
MongoEngine documentation on Django support states:
Django support has been split from the main MongoEngine repository. The legacy Django extension may be found bundled with the 0.9 release of MongoEngine.
and
6.1. Help Wanted!
The MongoEngine team is looking for help contributing and maintaining a new Django extension for MongoEngine! If you have Django experience and would like to help contribute to the project, please get in touch on the mailing list or by simply contributing on GitHub.
Which leads to this repo, where the following is stated:
THIS IS UNSTABLE PROJECT, IF YOU WANT TO USE IT - FIX WHAT YOU NEED
Right now we're targeting to get things working on Django 1.9
So it may be possible that it cannot play well with Django at this state or with your version and thus the problem occurs.
Initial attempt, leaving it here for legacy reasons.
I believe that the problem occurs on how you are initializing your object, although I do not have a set up to test this theory.
It is generally considered that is better to make a new object with the .create() method:
def index(request):
connect('HacettepeItiraf', alias='default')
confession = Confession.objects.create(
confession='First confession from the API'
)
print(confession.confession + ' Printable')
confession.save()
return HttpResponse(request)
Have a look at the Django & MongoDB tutorial for more details.
In this tutorial, the supported Django version is not mentioned, but I haven't found concrete proof that MongoDB Engine can or can't play well with Django version > 1.8.
Good luck :)

Django: Django-Rest-Framework gives Attribution error (pagination)

I'm trying to create migrations of a project which uses Rest Framework pagination.
But I'm getting error as Attribution error: 'module' object has no attribute BasePaginationSerializer. I have tried uninstalling-resinstalling the said versions of Python, Django and RestFramework. But I still get that error.
Here's the screenshot of terminal showing error.
Here's a chunk of the code present in paginator.py
import urlparse
from django.core.paginator import EmptyPage, Page, PageNotAnInteger, Paginator
from django.utils.http import urlencode
from rest_framework import serializers, pagination
class CustomPaginationSerializer(pagination.BasePaginationSerializer):#Here it shows the error.
meta = MetaSerializer(source='*')
results_field = 'objects'
Can someone help me out in getting this issue resolved?
Info:
- Here's the project which I'm trying to build. https://github.com/mozilla/zamboni
I'm using Ubuntu 15.10
Python - 2.7.10
Django - 1.8.7
Django Rest Framework doesn't provide anything like BasePaginationSerializer, that's why you're getting an error - because it doesn't exist. You probably want to use BasePagination

cloudinary django database error

I am developing app that uses Cloudinary, using Django 1.8.
I downloaded the sample project from https://github.com/cloudinary/cloudinary-django-sample.
This line:
image = CloudinaryField('image')
causes an error when runnig "manage.py migrate" saying
django.db.utils.OperationalError: near "None": syntax error
Tried adding "null=True" and "blank=True" to the field definition
image = CloudinaryField('image', null=True, blank=True)
but I am getting the same result.
I import cloudinafield like this
from cloudinary.models import CloudinaryField
When I comment out the line with CloudinadyField there are no errors.
What can be the reason of this error?
Well, there is no such field type like the one you used.
For handling image you can either use CharField to store the url or use FileField to store the file key which will link the url.
You can find detailed configuration on this page.
I feel like an idiot, just updated cloudinary library to 1.1.3 and everything works fine now. Thanks Tal Lev-Ami

reading file in a django view function

EDITED in response to comments and answers:
I am new to django and web development and I feel like I'm missing something basic about how to use django views.
I have a django app that I set up following the instructions in the django tutorial: here. Specifically, I end up with the autogenerated directory and file structure described there:
mysite/
manage.py
settings.py
urls.py
myapp/
models.py
views.py
templates/
*.html
static/
*.css
In my app I receive some user input from a template form and save it in my model in a function in views.py.
Before doing this I want to run some functions to check the input - depending on what it is I decide whether or not and where to put it in the database and also what content to display to the user next.
For example, one thing I want to do is check whether the words that were input are in the dictionary. I have a word list in a text file and I want to check whether the words from the input are in that list.
I want to be able to do something like:
wordlist = set(w.strip() for w in open(filename).readlines())
Where should I put this text file and how can I refer to it (in order to open it) in views.py? Where should I put that line of code - is there a way to only make this set once and then access it whenever any user submits input?
Note that I tried just putting the text file in myapp/ and then doing open(filename) but I get an error:
IOError No such file or directory.
I also tried to put the file in static/ and then do open(STATIC_URL + filename) but I get an error:
NameError Name 'STATIC_URL' is not defined.
However I do have from django.contrib import staticfiles so it should be defined.
This is a very old post, but I was doing something similar and here is my solution of how to read text content in Django view.py
import os
def your_view_function(request):
module_dir = os.path.dirname(__file__) #get current directory
file_path = os.path.join(module_dir, 'data.txt') #full path to text.
data_file = open(file_path , 'rb') #I used'rb' here since I got an 'gbk' decode error
data = data_file.read()
# print("data=", data)
return whatever_you_need
Django is just Python. There are no special rules about accessing files in Django, you do it just as you would with any other Python script.
You don't give any examples or reason why open(filename) doesn't work. Assuming filename is an absolute path, and that the user that Django is running as has permission to open the file, it should definitely work. (Although note that relying on opening a file may not be the best design when it comes to a multi-user web site.)

Categories