Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error trying to create Generic Relation
Hi I'm trying to create a GenericForeignKey Relation to link a reviews model to a set of location classes of different types of locations.. So I class museum, restaurant, park, industry, zoo, etc. which all inherit from an abstract class 'Location' and i want to be able to submit reviews for all the different locations saved for these types.. This is what I have so far in models.py: from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericRelation class Location(models.Model): name = models.CharField(max_length=50) lat = models.FloatField() lng = models.FloatField() address = models.CharField(max_length=80, unique=True) city = models.ForeignKey(City, on_delete=models.CASCADE) email = models.EmailField(blank=True) # Below the mandatory fields for generic relation content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Meta: abstract = True class Reviews(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) review = models.CharField(max_length=200) reviews = GenericRelation(Location) def __str__(self): return self.name class College(Location): departments = models.CharField(max_length=200, blank=True) def __str__(self): return self.name class Industry(Location): type = models.CharField(max_length=50, blank=True) class Meta: verbose_name_plural = 'Industries' def __str__(self): return self.name class Hotel(Location): phone = models.CharField(max_length=15, blank=True) def __str__(self): return self.name I want to create a character text field in the reviews class (and use that for … -
How to save an array of object in DRF
I have this type of json: { "word" : "world", "days" : [1, 3, 7] } And DRF gives me this error: 'days': [{'non_field_errors': ['Invalid data. Expected a dictionary, but got int.']}, This is my days serializer: class DaysSerializer(serializers.ModelSerializer): class Meta: model = Days fields = ('day') And this my top level serializer: class WordsSerializer(serializers.ModelSerializer): days = DaysSerializer(many=True) class Meta: model = Words fields = ('word', 'days') I read that I need to use bulk serializers. Is that the route that is recommended today? Or there is a simpler way? If I need to use the bulk serializer library, I don't understand from their example how do I use that library for my purposes? Namely to (bulk) save the many to many entries (the Days) in one of the records (the Word). -
View error "str is not callable" with ModelChoiceField
I want to add Select field to form for field with type ForeignKey and use for this ModelChoiceField. But this form doesn`t rendering and throw error "'str' object is not callable" on the line " {{ form_ord.all_users}} {{ form_ord.pay_method }} {{ form_ord.pay }}" in order_add.html file. What can I use to create form for model with ForeignKey field? order.py class Order(models.Model): PAY_METHOD_CHOISES = ( ('CASH', 'cash'), ('CREDIT', 'credit card'), ('CHECK', 'check'), ) pay_method = models.CharField(max_length=15, choices=PAY_METHOD_CHOISES, default='cash') user_id = models.ForeignKey(UsersData) pay = models.BooleanField(default=False) @property def __str__(self): return self.user_id.user_name def pay_or_not(self): if self.pay: result = 'paid' else: result = 'not paid' return result class OrderForm(ModelForm): all_users = forms.ModelChoiceField(queryset=UsersData.objects.all(), empty_label=None, initial=0) class Meta: model = Order fields = ['user_id', 'pay_method', 'pay', 'all_users'] view_order.py def order_add(request): if request.method == 'POST': form_order = OrderForm(request.POST) if form_order.is_valid(): part_order_form = form_order.save(commit=False) value_user = form_order.cleaned_data.get('all_users') user = UsersData.objects.get(use_name=value_user) part_order_form.user_id = user part_order_form.save() return HttpResponseRedirect('/sushi_rinjin/orders/') else: form_order = OrderForm() return render(request, 'sushi_rinjin/forms/order_add.html', {'form_ord': form_order}) order_add.html <form action="{% url 'sushi_rinjin:add_order' %}" method="post"> {% csrf_token %} {{ form_ord.all_users}} {{ form_ord.pay_method }} {{ form_ord.pay }} <input type="submit" value="Add Order" /> </form> -
Use Oauth2 token in my classview to allow some user access only his own user data?
I use a token to retrieve user data in a mobile App. But...if a user has authenticated can access the data of another users....How I restrict that only the own user token access to the own user data in the model Users? (Sorry my bad english) -
Error configuring mod_wsgi from source code
I'm trying to ./configure mod_wsgi from source code per these instructions. Overall I'm trying to get Django working with Python3 and Apache on a Google Cloud Compute Engine. It's using Debian 9. I installed Python 3.6 from Anaconda located in /home/dhampton/anaconda3. I'm running into the following error: dhampton@blog-instance-1:~/mod_wsgi-4.5.20$ ./configure checking for apxs2... no checking for apxs... no checking for gcc... no checking for cc... no checking for cl.exe... no configure: error: in `/home/dhampton/mod_wsgi-4.5.20': configure: error: no acceptable C compiler found in $PATH See `config.log' for more details dhampton@blog-instance-1:~/mod_wsgi-4.5.20$ The following is what's in the config.log file: This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by configure, which was generated by GNU Autoconf 2.69. Invocation command line was $ ./configure ## --------- ## ## Platform. ## ## --------- ## hostname = blog-instance-1 uname -m = x86_64 uname -r = 4.9.0-4-amd64 uname -s = Linux uname -v = #1 SMP Debian 4.9.51-1 (2017-09-28) /usr/bin/uname -p = unknown /bin/uname -X = unknown /bin/arch = unknown /usr/bin/arch -k = unknown /usr/convex/getsysinfo = unknown /usr/bin/hostinfo = unknown /bin/machine = unknown /usr/bin/oslevel = unknown /bin/universe = unknown PATH: /home/dhampton/anaconda3/bin PATH: /usr/local/bin PATH: … -
Analogue of send_from_directory() from Flask in Django?
Is there Analogue of send_from_directory() from Flask in Django? -
TypeError at /accounts/register/ encode() missing 1 required positional argument: 'iterations'
hye there . i dont understand why i get this error because i did not delete anything in the encode() . it just keep me from submitting my registration form . can anybody help ? traceback : File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adila\Documents\tryFOUR\src\register\views.py" in register 13. user = form.save(commit=False) File "C:\Users\Adila\Documents\tryFOUR\src\custom_user\forms.py" in save 50. user.set_password(self.cleaned_data["password1"]) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\contrib\auth\base_user.py" in set_password 105. self.password = make_password(raw_password) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\contrib\auth\hashers.py" in make_password 84. return hasher.encode(password, salt) hashers.py : def encode(self, password, salt, iterations): Sweetwords = ['road,models,table'] Sweetwords.extend(honey_gen.gen(password, base9, [passfile.txt])) for i in range(base10): Sweetwords.extend(honeywordtweak.tweak(passwords[i], 3)) random.shuffle(Sweetwords) hashes = [ ] for swd in sweetwords: hashes.append(self.hash(swd, salt, iterations)) self.honeychecker.update_index(salt, Sweetwords.index(password)) h = Sweetwords(salt = salt, Sweetwords = pickle.dumps(hashes)) h.save() return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hashes[0]) im so confused what i did wrong -
Run multiple local terminal processes with Fabric
new to using fabric. I have a project with a django backend and angular front end. I'm trying to make running the project locally easier with a fabfile. Here is the part of the script where I'm stuck... # activate venv and start backend server with lcd(projectpath), prefix('. venv/bin/activate'): local(projectpath+backendfolder+'manage.py runserver') # start frontend server <==== FAB STOPS HERE!! with lcd(projectpath+frontendfolder): local('npm start') I have managed to get my virtual environment started and manage.py runserver to work. However fabric stops there and doesnt continue executing starting my angular server. This is obviously because this is a serial process. How can I get the angular server running as a new terminal process after my django server is running? -
Django many2many is a subset of another set
Given a model with an m2m field, let's say Article has multiple Authors. What is the most efficient way to get all the articles in which the set of their authors is a subset of another set? class Article(models.Model): authors = models.ManyToManyField('Author') Get all articles that were written by one or many of the authors in this list but doesn't have any author that is not part of this list. authors_list = ['Tom', 'John', 'Sara', 'Kati'] Articles written by 'Tom' would match. Articles written by 'Tom' and 'Sara' would match. But, Articles written by 'Tom' and 'Alter' would NOT match. -
MultipleChoiceFilter with distinct values Django
I am not able to make a multiple choice filter with checkbox in Django. I researched but couldn't find anything practical either than to use django_filters.MultipleChoiceFilter. I want to show as Checkboxes the distinct values of Category column from my Book Model (e.g.: "Fiction", "Romance", "Improvement") . Using PostgreSQL model class Book(models.Model): name = models.CharField(max_length=350) author = models.CharField(max_length=350) category = models.CharField(max_length=200) def __str__(self): return self.name filter class BookFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') author = django_filters.CharFilter(lookup_expr='icontains') category = django_filters.MultipleChoiceFilter(widget=forms.CheckboxSelectMultiple,) #does not contain any parameters to enter any queryset or anything class Meta: model = Book fields = ['name', 'author', 'category',] views class SearchBooksView(TemplateView): template_name = "booksearch.html" book_list = Book.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) book_filter = BookFilter(self.request.GET) context['book_filter'] = book_filter return context booksearch.html <h1 class="h1"> Book Search </h1> <form method="get"> {{ book_filter.form.as_p }} <button type="submit">Search</button> </form> <ul> {% for book in book_filter.qs %} <li>{{ book.name }} - {{ book.author}} - {{ book.category}}</li> {% endfor %} </ul> </h1> Can you lend a helping hand? Thank you! -
Leaflet js remove one layer, add another layer and filter by variable of first layer
i have an leaflet map serving data over two urls out of a database. i use django and django-leaflet. python 3.5, postgresql 9.6. layerA is showed when loading the page. opening the popup of layerA i want have the possibility to load layerB by clicking in the popup of an item in LayerA. Items in LayerB belong to certain items in LayerA connected by foreign key. heres my code: function map_init_basic (map, options) { urlA = "http://127.0.0.1:8000/data.A" // Geojson urlB = "http://127.0.0.1:8000/data.B" // Geojson layerA = L.geoJson(null, { pointToLayer: function(feature, latlng) { return L.marker(latlng, {icon: hvIcon}); }, onEachFeature: function( feature, layer) { popupText = "button to call layerA" + "<button id='theirFlats' type='button' class='btn btn-link' onclick='getLayerB(\""+feature.id+"\");'>show layerB:</button>"; layer.bindPopup(popupText); } }); layerB = L.geoJson(null, { filter: function(feature, layer) { {return feature.properties.id_hv == id_layerB;}; }, pointToLayer: function(feature, latlng) { return L.marker(latlng, {icon: whgIcon}); } }); $.getJSON(urlA, function(data){ layerA.addData(data); }); layerA.addTo(map); } // end map_init function getLayerB(id_layerA){ alert(id_layerA); // alerts the right id layerB.remove(); // works, removes the layerB alert(urlB) $.getJSON(whgurl, function(data){ layerB.addData(data); console.log(data); }); layerB.addTo(map); alert(layerB) map.fitBounds(layerB); } i get the following errors: TypeError: t is undefined and ReferenceError: id_layerB is not defined -
how to import stl , mesh to Django views.py or models.py
I'm trying to import stl , mesh to Django for analysis 3d model on the website. but , i couldn't do that and i saw this message view.py from stl import mesh 'ImportError: cannot import name 'mesh' even i already installed numpy , stl using pip. How to solve this problem? As i used that 'import mesh from stl ' on the jupyter notebook , i have never seen this error before. Thank you -
Django create CustomUser model
Folks, I'm trying to create my own User model by extending the AbstractBaseUser model provided by Django. However, I keep on getting the following error when migrating: ValueError: The field admin.LogEntry.user was declared with a lazy reference to '<app_name>.user', but app '<app_name>' doesn't provide model 'user'. What I have done so far is the following: In app/models.py added CustomUser class together with CustomUserManager with relevant fields and all. In app/admin.py I've added this: from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from <app_name>.models import CustomUser class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields = ('email',) class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email',) def clean_username(self): username = self.cleaned_data["username"] try: get_user_model().objects.get(username=username) except get_user_model().DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm add_form = CustomUserCreationForm fieldsets = ( (None, {'fields': [('username', 'password'),]}), (('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (('Important dates'), {'fields': ('last_login', 'date_joined')}), ) admin.site.register(CustomUser, CustomUserAdmin) Apart from that there is this added to seetings.py AUTH_USER_MODEL = '<app_name>.CustomUser' Everything that I found so far suggests that the above given code should make this work, but it doesn't. I spent like 4-5 hours already and I still can't … -
Django doesn't check passwords when reset
I'm using Django's password_reset forms with overriden html files, and when I pushed my code to my server, I could suddenly make the password 1 character long, where they should at least be 8 characters long. BUT it does show an alert if password1 and password2 aren't identical On my local machine the Django project was created using 1.11.3, and on the server the Django project was created in version 1.8.7.The form I use for posting the new password: <form method="POST"> {% csrf_token %} <input name="new_password1" class="form-control" type="password" placeholder="Adgangskode"> {% for key, value in form.errors.items %} <strong>{{ value|escape }}</strong> {% endfor %} <input name="new_password2" class="form-control" type="password" placeholder="Bekræft adgangskode"> <input type="submit" class="btn btn-default btn-block" value="Bekræft"> </form> The question is: why does Django not properly validate the password (checking if it's are entirely numeric, or if it's longer than 8 characters), on the server, but perfectly on my local machine? Thanks -
Django: Redirect is Not Working
Here's my view, class ModelLike(RedirectView): def get_redirect_url(self, *args, **kwargs): id = self.kwargs.get('id') obj = get_object_or_404(Model, id=id) user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) I used return redirect(request.META['HTTP_REFERER']) but it gives an error "name 'request' is not defined" I can't use the return obj.get_absolute_url() because i'm using this view at several places. So, how can I redirect user to the same page after Like? -
Django inline forms
I have to models, an Article and a Photo. There is a many2many relation between them. I need to design an Admin form that works better for editing them. I batch upload photos and the Photo models are created. Then when I write the articles, I want to be able to edit the Photo models as an inline form. When I set it up as described so far, I get an article edit form, with a selector to click on the name of each photo. I would like to have all unassigned photos shown, with a text box for the cutline on each photo and checkbox. When I put a checkbox and save the article the pictures are associated with that article. I also need to save the updated Photo objects with the text under each photo. Suggestions for how I should go about this? -
NameError at /accounts/register/ name 'Honeyword' is not defined
hye there . how to import my new custom password hasher ? it just give me this error : NameError at /accounts/register/ name 'Honeyword' is not defined hashers.py : class MyHoneywordHasher(PBKDF2PasswordHasher): algorithm = "honeyword_base9_tweak3_pbkdf2_sha256" iterations = 36000 digest = hashlib.sha256 def salt(self): salt = get_random_string() while Honeyword.objects.filter(salt=salt).exists(): salt = get_random_string() return salt -
Create and fill a test database
Django==1.11.6 The problem is: first test runs smoothly, but the second test faces an empty database. StaticLiveServerTestCase is a TestCase subclass. Let's have a look at the documentation about setUpClass: https://docs.python.org/3.6/library/unittest.html#unittest.TestCase.setUpClass Well, nothing is clear. But it seems that database is created in the SetUpClass. And as far as I can understand, the database created once and exists till the last method of the class finishes. Well, I seem to be wrong as the second method faces an empty database. Could you help me organize a test database, and fill it once for all the methods. class GeneralMixin(StaticLiveServerTestCase): """ Load selenium and log in. Afterwards quit webdriver. """ fixtures = ['users.yaml'] def _login(self): .... def setUp(self): self._login() @classmethod def setUpClass(cls): super(GeneralMixin, cls).setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super(GeneralMixin, cls).tearDownClass() class FrameTests(GeneralMixin): @classmethod def setUpClass(cls): super(FrameTests, cls).setUpClass() create_dateranges() create_frames() def test_id_frame_1(self): """ User visits frame 1. And sees that ID 1 is shown in the frame detail page. """ FRAME_ID = "1" self.selenium.\ get('{}{}'.format(self. live_server_url, reverse('frame_detail', kwargs={"pk": FRAME_ID}))) id_element = self.selenium.\ find_element_by_id("object_id") found_id = id_element.text self.assertEqual(found_id, FRAME_ID) def test_id_frame_2(self): """ User visits frame 2. And sees that ID 2 is shown in the frame detail page. """ FRAME_ID … -
Django Boolean Field Won't Update
I have a model which has a latest field to determine if a particular instance is the latest definition. When adding a new row to the db I want to make sure to mark latest as false for the already existing record. latest_version = Segment.objects.filter(segment_name=segment_name, third_party_type=third_party_type).first() if latest_version: latest_version.latest = False latest_version.save() This seems relatively straight forward but the latest field will not update and stays as True. -
Django - access to item in list with a changing index
I used to code in C#. I want to use python to do something like: int start_index = 4; List<int> list = { ... } for(int i = start_index;i < 10;i++){ list[i].dosomething(); } this is how I tried in Django {% with 0 as starting_index %} {% for comment in comments %} <!--set a variable to limit the amount of comment on a page--> {% with forloop.counter as index %} {% if index < 3 %} <div class="comment_body"> <div class="content_block"> <p>{{comments[index]}}</p> </div> </div> {% endif %} {% endwith %} {% endfor %} {% endwith %} This code is obviously not working. Can anybody help me with this problem? Thanks in advance! -
Django extra user registration details not saving to database
I have been trying to extend the django user profile but it won't save the extra details to the database which is a user_type of business, student, tourist and I can't figure out why. Any help would be appreciated. It doesn't save in the DB as null, it is saving as just blank. Using python 3 with the latest version of django. Forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.forms import ModelChoiceField from django.contrib.auth.models import User, Group from .models import UserProfile class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=50, required=False, help_text='Not required.') last_name = forms.CharField(max_length=50, required=False, help_text='Not required.') email = forms.EmailField(max_length=300, required=True, help_text='Please input a valid email address.') user_types = ((1, 'Business'), (2, 'Student'), (3, 'Tourist')) user_type = forms.ChoiceField(choices = user_types) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'user_type', 'password1', 'password2',) models.py from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save from django import forms # Create your models here. ADMIN = 0 BUSINESS = 1 STUDENT = 2 TOURIST = 3 class UserProfile(models.Model): user_choices = ( (0, 'Admin'), (1, 'Business'), (2, 'Student'), (3, 'Tourist'), ) # Link UserProfile to User model user = models.OneToOneField(User, on_delete=models.CASCADE) # Add attributes … -
Django - ModelChoiceField validation
I have a simple form witch ModelChoiceField. This is a part of my view.py file: def premium(request, id): context = {} try: site = Site.objects.get(id=id) except Site.DoesNotExist: raise Http404("Nie ma takiej strony") if request.method == 'POST': premium_form = PremiumForm(request.POST) if premium_form.is_valid(): # group = Group.objects.get(id=request.POST["kod"]) print('OK') else: print('NOT OK') else: premium_form = PremiumForm(site) premium_form.fields['group'].queryset = premium_form.fields['group'].queryset.exclude(group_name=site.group) context['site'] = site context['form'] = premium_form context['category'] = site.category context['subcategory'] = site.subcategory return render(request, 'mainapp/premium.html', context) This is my form: class PremiumForm(forms.Form): def __init__(self, site, *args, **kwargs): super(PremiumForm, self).__init__(*args, **kwargs) self.fields['group'].initial = 2 self.fields['group'].empty_label = None group = forms.ModelChoiceField( queryset=Group.objects.filter(is_active=True), help_text="<div id='group'></div>", label="Some text", required=False) My premium.html file: <form method="post" action="" class="form-horizontal"> {% csrf_token %} {% bootstrap_form form layout='horizontal'%} <br> {% bootstrap_button "Submit" size='large' button_type="submit" button_class="btn-primary btn-main-add" %} </form> When I press "Submit" button I get "NOT OK". I can't resolve this problem. I don't have any idea how to validate forms.ModelChoiceField. Thanks for any help. -
Cant get to data to save from form Django
I am creating a job board site. Right now I can successfully register an Employer but when I try to create a job listing while logged in as an Employer, the data from the form does not save to the database. I have the following models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.http import HttpResponse # Create your models here. class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.first_name @receiver(post_save, sender=User) def create_employer(sender, instance, created, **kwargs): if created: Employer.objects.create(user=instance) @receiver(post_save, sender=User) def save_employer(sender, instance, **kwargs): instance.employer.save() class Job(models.Model): poster = models.ForeignKey(Employer, on_delete=models.CASCADE) job_title = models.CharField(max_length=50) establishment_name = models.CharField(max_length = 50) details = models.TextField(max_length = 2000) salary = models.CharField(max_length = 20) address = models.CharField(max_length = 50) state = models.CharField(max_length = 20) zip_code = models.CharField(max_length = 10) def __str__(self): return self.job_title + " - " + self.establishment_name \ + ", " + self.poster.user.first_name + " " +self.poster.user.last_name A user can register as an employer just fine, but I am having problems getting Jobs to save to the database. Once a user registers/logs in as an employer they are redirected to employer_home.html, where an employer can post a job: {% extends … -
How to make a button click update the database and redirect to a view in Django?
I have been struggling with this for a while, any help would be appreciated! Basically, what I want to do is click an HTML button in Django, change a field in the database (of the object with the primary key in question), and redirect back to home. An example for clarity: Currently, I am working in the url: http://127.0.0.1:8000/result/edit/1/. The /1/ is the primary key of the model I want to change. The model is a custom group-model, with a field called "status". Status can be "approved", or "not approved": status = models.CharField(max_length=30, default=Status.not_sent, choices=Status.choices(), null=False) In the url result/edit/1/ I have an "Approve" button. When I click the button I want to change status in the model, and save that in the database. Also, after changing status I would like to redirect back to home. I have written the following method in views to do it: def approve_group(request, pk): group = Group.objects.filter(pk=pk) group.status = Status.approved group.save() return redirect(request, 'home') In the html, I have created the following button: <a href="{% url 'resultregistration:approve_group' %}" /> <button id="approve-btn" />Approve</button> </a> My reasoning is that the button should call this URL, which should again call the function in the view: url(r'^result/approve/(?P<pk>\d+)/$', views.approve_group, … -
Ghostscript/Imagemagick is not working in Django
I am working on a Django/Django REST framework based web application. I am building an API that slice pdf to every page, and convert them to image. Here are some of my code. with Image(filename=os.path.join(tmp_dir, pdffilename)) as img: for i, page in enumerate(img.sequence): file = '%s-%d.jpg' % (imagefilename, i + 1) Image(page).save(filename=file) filelist.append(file) but I am getting this error: DelegateError: FailedToExecuteCommand `'gs' -sstdout=%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 '-sDEVICE=pngalpha' -dTextAlphaBits=4 -dGraphicsAlphaBits=4 '-r72x72' '-sOutputFile=/var/folders/kl/5qf5q4x50xj2rbdp8t2prsbh0000gn/T/magick-26897HyfIoUTUbASw%d' '-f/var/folders/kl/5qf5q4x50xj2rbdp8t2prsbh0000gn/T/magick-26897y4uJPEzsfHCE' '-f/var/folders/kl/5qf5q4x50xj2rbdp8t2prsbh0000gn/T/magick-268970ovMV9WfGDbE'' (1) @ error/pdf.c/InvokePDFDelegate/292 I am using python 2.7.10 / Django 1.9. And, of course, installed Ghostscript(9.2.2) and imagemagick(6.9.9). I am not sure why this is not working. Would you like to help me? Any idea why this isn't working for me?