Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show selected image in ImageField file in template
How do i show the selected file image in the template an error comes up with The 'image' attribute has no file associated with it. how do i wait for the user to select a file and then show the image in template. Template {{ form.instance.image.url }} -
Django enable URL link in template
I have a blog and users can comment any articles. For now, when they post an URL, we can not follow the link by a clic. Because there is no tag. I know we can display HTML by using the filter "|safe". But I don't want a user using all html tag for security reasons. I just want to make URL like "http://google.fr" as active and cliquable. Any idea ? -
Check for 404error in django templates
enter image description here I want to add condition in templates ex:) if img not found 404 error: base img else: resource.img -
After passing url in reverse_lazy its showing TemplateDoesNotExist
im getting the template exception after giving the reverse_lazy with app:url the the code as goes below IN htML <p><a href="{% url 'home:album-delete' album.id %}">Delete</a> </p> IN urls( this is the delete url) url(r'^album/(?P<pk>[0-9]+)/delete/$', views.AlbumDelete.as_view(), name='album-delete'), url(r'^$', views.IndexView.as_view(), name="index"), In Views from .models import Album, Song from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy # creating generic views class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('home:index') -
Set cache expire headers without access to nginx configuration (Django + Gunicorn)
I have my Django app up and running using Gunicorn+Nginx on a shared hosting, but I don't have access to my nginx configuration file (because of shared hosting, I create an "app" on my hosting Control panel which is automatically added as a virtual host with a specific port, and I use that port to start my Gunicorn). Is there a way to set my cache expire headers? Nginx obviously doesn't have something like .htaccess which would make this easier. Maybe there's a way that would make Django or Gunicorn "push" some configuration (location etc.) to Nginx? -
Django filter: Collect filtered data from multiple Models(Same Type) into one view
I have four different Models with same structure(Same number of columns and same column name), The four models belong to different category. I want to filter data from each of the models using some filter fields and, I want this same filters to be applicable to all the models at same instance and show all of the filtered data from all the models into one view. I am using django-filters third party library. Here is a sample filter for a Model. filters.py import django_filters from django_select2 import * from django_filters import STRICTNESS from django_filters.widgets import RangeWidget from InputForms.models import Reportable class RFilter(django_filters.FilterSet): Date = django_filters.DateFromToRangeFilter(widget=RangeWidget(attrs={'placeholder': 'YYYY/MM/DD'})) class Meta: model = Reportable fields = ['Cause','TypeOfEmployee','Date','UnitName','Shift'] strict = STRICTNESS.RETURN_NO_RESULTS views.py from django.shortcuts import render from .filters import * from InputForms.models import Reportable def RFView(request): f = RFilter(request.GET, queryset=Reportable.objects.all()) return render(request, 'template.html', {'filter': f,'Header':"Reportable"}) template.html <h3>{{ Header }}</h3> <form action="" method="get"> {{ filter.form.as_table }} {{ list_filter }} <input type="submit" /> </form> {% load render_table from django_tables2 %} {% render_table filter.qs %} -
Optimizing queries in SerializerMethodField in Django REST framework
I am accessing the related field's data in my SerializerMethodField and there is a query for every object that is being rendered. My models look like (will keep short for brevity): class Listing(models.Model): variant = models.ForeignKey(to='Variant', related_name='variant_listings') seller = models.ForeignKey(to='user.Seller', related_name='seller_listings') locality = models.ForeignKey(to='user.Locality', blank=True, null=True) price = models.IntegerField(blank=True, null=True) Variant, Seller and Locality are all related models. My Viewset: class ListingViewSet(viewsets.ModelViewSet): """Viewset class for Listing model""" queryset = Listing.objects.all() serializer_class = ListingSerializer pagination_class = TbPagination filter_backends = (filters.DjangoFilterBackend,) filter_class = ListingFilter def get_queryset(self): listing_qs = Listing.objects.filter(status='active') return listing_qs And my serializer: class ListingSerializer(serializers.ModelSerializer): """Serializer class for Listing model""" @staticmethod def get_car_link(obj): variant_name_slug = obj.variant.name.replace(' ', '-').replace('+', '') return '/buy-' + obj.seller.city.name.lower() + '/' + variant_name_slug car_link = serializers.SerializerMethodField(read_only=True) @staticmethod def get_car_info(obj): return { 'id': obj.id, 'variant_name': obj.variant.name, 'localities': obj.locality.name, } car_info = serializers.SerializerMethodField(read_only=True) @staticmethod def get_image_urls(obj): caption_ids = [1, 2, 3, 5, 7, 8, 18] attachments_qs = Attachment.objects.filter(listing_id=obj.id, caption_id__in=caption_ids) image_urls = [] for attachment in attachments_qs: url = str(obj.id) + '-' + str(attachment.file_number) + '-360.jpg' image_urls.append(url) return image_urls image_urls = serializers.SerializerMethodField(read_only=True) class Meta: model = Listing fields = ('car_link', 'car_info', 'sort_by', 'image_urls') For each listing returned by the listing viewset, there is a query for every related field accessed … -
Is it possible to convert a CSV into a Django model without specifying the model beforehand?
I'm trying to sort a large amount of data with different headers. Each CSV file has a different set of headers that need to be parsed into a Django Model. Instead of individually defining each model, is it possible to do this on the fly? -
Django model unit test
I started learning Django, and I'm having problems with the unit test, and I was trying to look for the problem, but I can not identify what the problem is in my code. If someone can identify what the problem is in my code or if you can give me some advice? Error: Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_create_user (user_api.tests.ModelUseProfileTest) Users can register ---------------------------------------------------------------------- Traceback (most recent call last): File "/vagrant/src/api/user_api/tests.py", line 26, in test_create_user user = UserProfile.objects.get(id=1) File "/home/ubuntu/.virtualenvs/venv/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ubuntu/.virtualenvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 379, in get self.model._meta.object_name user_api.models.DoesNotExist: UserProfile matching query does not exist. ---------------------------------------------------------------------- Ran 1 test in 0.040s FAILED (errors=1) Destroying test database for alias 'default'... My test: from django.test import TestCase from rest_framework import status from django.core.urlresolvers import reverse from .models import UserProfile # Create your tests here. class ModelUseProfileTest(TestCase): """ Test class define the test suite for the UserProfile model.""" def test_create_user(self): """Users can register""" # Create an instance of a GET request. response = self.client.post("/api/v1/register/", { "name": "Walter", "lasT_name": "White", "email": "heisenberg@email.com", "password": "secret", }) user = UserProfile.objects.get(id=1) self.assertEqual(user.name, "Walter") self.assertEqual(user.last_name, "White") self.assertEqual(user.email, "heisenberg@email.com") self.assertEqual(response.status_code, 201) … -
Uploading an image to a boto bucket
I am trying to an upload that I am retrieving from django forms to the amazon boto. But everytime I save it gets saved in first_part/second_part/third_part/amazon-sw/(required image) instead of getting saved in first_part/second_part/third_part. I use the tinys3 library. I tried but found boto to be a little complex to use so used tinys3. Please do help me out. access_key = aws_details.AWS_ACCESS_KEY_ID secret_key = aws_details.AWS_SECRET_ACCESS_KEY bucket_name = "s3-ap-southeast-1.amazonaws.com/first_part/second_part/third_part/" myfile = request.FILES['image'] # getting the image from html view fs = FileSystemStorage() fs.save('demo_blah_blah.png', myfile) # saving the image conn = tinys3.Connection(access_key, secret_key, tls=True, endpoint='s3-ap-southeast-1.amazonaws.com') # connecting to the bucket f = open('demo_blah_blah.png', 'rb') conn.upload('test_pic10000.png', f, bucket_name) # uploading to boto using tinys3 library -
How to get a image form django imageFile input
I want to get the image from the ImageField file input and then display the image in a template, and finally save the image to the model imageField. The file_image = request.POST.get('image') only gets the image name, how do I get the actual image. Do I need to upload the image to a NamedTemporaryFile() first? view def uploadImageView(request): form = UploadImageForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid: file_image = request.POST.get('image') request.session['file_image'] = file_image return redirect('image:create') def saveImageView(request): uploaded_image = request.session.get('file_image') form = Form(request.POST or None, request.FILES or None,) if form.is_valid(): instance = form_create.save(commit=False) instance.image = uploaded_image inastance.save() Template First views template <form method="POST" action=""> {% csrf_token %} <input type="submit"></input> {{ form }} </form> second views template <form method="POST" action=""> {% csrf_token %} {{ form }} <input type="submit"></input> </form> {{ form.instance.image.url }} -
Templates Doesnot exist at /accounts/login
I am using django-registraion for authentication of users. I did install django-registration via pip and added in the settings.py file. However it is still giving me the Templtate doesnot exist error. Here's the error: TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/ Django Version: 1.11.3 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: C:\Python34\lib\site- packages\django\template\loader.py in select_template, line 53 Here's the code: from django.conf.urls import url from django.contrib import admin from django.contrib.auth.views import login, logout from chat.views import index from django.conf.urls import include urlpatterns = [ url('^', include('django.contrib.auth.urls')), url(r'^admin/', admin.site.urls), url(r'^$',index, name='homepage'), # The start point for index view url(r'^accounts/login/$', login, name='login'), # The base django login view url(r'^accounts/logout/$', logout, name='logout'), # The base django logout view in the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', 'registration', ] This is the structure of my django project. -
Django CSRF Token Missing For iOS Post Request
Currently, I'm making an application that uses Django Rest Framework as my API and iOS (Swift) as my frontend using Alamofire for API calls. However, I've run into an issue with user authentication - whenever I try to make a POST request to login a user using Alamofire, I'm hit with this 403 error: Here is my login setup with Alamofire: func loginUser(data: Parameters) { let finalUrl = self.generateUrl(addition: "auth/login/") print(finalUrl) let header: HTTPHeaders = [ "Accept": "application/json", "Content-Type" :"application/json"] Alamofire.request(finalUrl,method: .post, parameters: data, encoding: JSONEncoding.default, headers: header).responseString { (response:DataResponse<String>) in print(data) switch(response.result) { case .success(_): if response.result.value != nil { print(response.result.value!) } break case .failure(_): print(response.result.error!) break } } } On the API side, the login I am using is the one provided by rest_framework.urls... url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')) While advice from similar posts has not resolved my issue, I believe my options are a.) Exempt my views from requiring a CSRF token (I'm not sure if it's even possible in my case - my views are bundled with include() as part of the rest_framework.urls scheme so decorating with csrf_exempt cannot work) b.)Obtain a CSRF Token for my POST requests somehow While these are my ideas, I've yet to find … -
Value is not used (unused in scope) in Django Framework
Hi I am new to Django framework and I have followed this tutorial https://www.youtube.com/watch?v=qgGIqRFvFFk&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK in order to create a website, but when I ran the Music app, it's not executing and in my views.py, there is an error which is showed by underlining the "request" in the "index(request)", that says the parameter 'request' value is not used. Below are the snippets of the codes: views.py from django.http import HttpResponse def index(request): return HttpResponse("<h1>This is Music App Page") music/urls.py from django.http import HttpResponse def index(request): return HttpResponse("<h1>This is Music App Page") website/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^music/', include('music.urls')), ] In the first image (i.e in Views.py) "request" which is highlighted in red is throwing error stating that parameter 'request' value is not used (unused in scope). I have followed the exact tutorial as mentioned in the link, can somebody please help? Thanks.! -
Django Application consuming memory in the server
I have django application in a Digital Ocean(512MB Memory) with Postgres, Nginx, and Gunicorn on Ubuntu 16.04. On running the application, it consuming more memory. If I navigate through the pages, it also consuming the memory on checking with top command. What will be the problem and what are the possible reason. Gunicorn [Unit] Description=veeyar daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/webapps/myproject/ ExecStart=/home/webapps/myproject/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/webapps/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target Nginx server { listen 9090; location = /favicon.ico { access_log off; log_not_found off; } location ^/static/ { root /home/webapps/myproject/staticfiles; } location / { include proxy_params; proxy_pass http://unix:/home/webapps/myproject/myproject.sock; } } And also in settings.py I had set DEBUG=False. I tried by googling it but i cannot understand properly.why it is happening so and did I missed anything. Can you guys please help me to sort out this problem. This will be very great full for me. Thanks in advance. -
Calculate size of folders inside S3 bucket
I have a bucket named "mybuckettest" in my AWS account. Inside this bucket I have multiple folders like "Folder1", "Folder2", "Folder3". Inside each of these folders, I have sub folders as well. It can be simulated as shown below: mybuckettest Folder1 subfolder1 content1 content2 content3 content4 subfolder2 content1 Folder2 subfolder1 Folder3 subfolder1 content1 content2 I am trying to figure out the size of each folders "Folder1", "Folder2", "Folder3" separately. Is there any specific way to do this using API? I mean I am trying to build an application through which I want to do this. Does anyone has an idea on this? My application language is Python-Django. -
Django 1.11 django.urls.exceptions.NoReverseMatch:
I've been trying to find a same question like what i want, but the question not seemed same like what i want. I still start learn about Django, Framework for python. I following a tutoial from django documentation and i get stuck when i try to learn about Generic View. i'll show my code : urls.py from django.conf.urls import url from mulai.views import IndexView, DetailView, ResultsView, votes app_name = "start" urlpatterns = [ url(r'^$', IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', DetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/results/$', ResultsView.as_view(), name='results'), url(r'^(?P<choice_question_id>[0-9]+)/votes/$', votes, name='votes') ] templates/detail.html {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'start:votes' question_list.id %}" method="post"> {% csrf_token %} {% for choice in question_list %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> <br/> {% endfor %} <input type="submit" value="vote"> </form> view.py class DetailView(generic.DetailView): model = Question template_name = 'mulai/detail.html' def votes(request, choice_pertanyaan_id): # return HttpResponse("votes of the question : %s." % choice_pertanyaan_id) question_vote = get_object_or_404(Question, pk=choice_pertanyaan_id) try: click_choice = question_vote.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'mulai/detail.html', { 'question_vote': question_vote, 'pesan_error': "You must select one of them choice.", }) else: click_choice.choice_vote += 1 click_choice.save() return HttpResponseRedirect(reverse('practice:results', args=(question_vote.id,))) And the error i got from the detail.html, and the … -
Django Templating Dynamically Generate Tables with dictionary Data
So im working on a project right now. I have an api call that i make and it returns data that looks like this : { CheckName: "AppPools", Description: "DefaultAppPool", GroupName: "Server1", Links: [ { description: "Recycles the DefaultAppPool app pool.", link: "Recyle/Server1/DefaultAppPool", title: "Recycle" }, { description: "Stops the DefaultAppPool app pool.", link: "Stop/Server1/DefaultAppPool", title: "Stop" }, { description: "Starts the DefaultAppPool app pool.", link: "Start/Server1/DefaultAppPool", title: "Start" } ] }, { CheckName: "AppPools", Description: "FinancialServices", GroupName: "ST0PWEB12", Links: [ { description: "Recycles the FinancialServices app pool.", link: "Recyle/Server2/FinancialServices", title: "Recycle" }, { description: "Stops the FinancialServices app pool.", link: "Stop/Server2/FinancialServices", title: "Stop" }, { description: "Starts the FinancialServices app pool.", link: "Start/Server2/FinancialServices", title: "Start" } ] }, There is a hierarchy here CheckName1 GroupName1 Description1 Description2 GroupName2 Description3 Description4 CheckName2 GroupName1 Description1 Description2 GroupName2 Description3 Description4 IVe stored the data in dictionaries with the following format function called groupsInChecks creates a dict with the following format: {CheckName1:(GroupName1,GroupName2, GroupName3), CheckName2:(GroupName4,Grouonam5, GroupName6)} function called serviesInGroups creates a dict with the following format: {Groupname1:(Description1, Description2, Description3), GroupName2:(Description5. Description6, Description7)} they then return the dicts , which have nested as the values. In my views py i pass each dict to a … -
How can I query with specific partitions in QuerySet Django?
I use QuerySet in Django and I want to specify a partition when I query with annotate, how can I do that? My code: queryset = Log.objects.filter(start_time__lte=dt_to, stop_time__gte=dt_from) result = queryset.values('room_id').annotate(total_active_user=Count('uin', distinct=True)) The SQL query I want: SELECT room_id, count(DISTINCT uin) AS `total_active_users` FROM log PARTITION (p88) WHERE log.stop_time >= "2017-06-01 00:00:00" and log.start_time <= "2017-06-02 00:00:00" GROUP BY room_id ORDER BY room_id; -
Check profiles on login django doesn't work
In my project I have two kind of profiles: "Student" and "Professor", in both models I declare an @property like this: class Professor(User): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) birthday = models.DateField("Data de Nascimento") sexChoices = ( (u"1", "Masculino"), (u"2", "Feminino"), ) sex = models.CharField(max_length = 1, choices = sexoChoices, default = u"1") def __str__(self): return self.user.username @property def profile(self): """ This property call the profile name """ return '%s' % 'Professor' After that I created a method call get_profile(), like this: def get_profile(user): """ defines the kind of profile Example: from roles.models import * user = User.objects.all() profile = get_profile(user[1]) profile.perfil """ try: professor = Professor.objects.get(username=user.username) return professor except: pass try: student = Student.objects.get(username=user.username) return student except: pass return user In my login view I'm trying to render differents html, for do this i'm using the get_profile() and perfil property, like this: class LoginValidator(View): def post(self, request, **kwargs): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: if user.is_active: login(request, user) messages.success(request, 'Logado com sucesso') if( get_profile(user).perfil == 'Professor'): return render(request,'professor/home.html') return render(request,'student/home.html') else: messages.error(request, 'Usuário não encontrado') So my question is: why is this methods doesn't work? Has a better way to … -
Custom Group model for Django Guardian
Django guardian requires from django.contrib.auth.models import Group to assign row-level permission to a group. I have my own group model that is NOT an instance of Group. Is there anything I can do about this? -
When I check nginx access.log, unknown HEAD requests come in periodically
First, I use the server environment: sever: nginx + uwsgi + django app, docker + AWS ECS deploy celery: rabbitmq ec2 cache: redis ec2 logging: AWS CloudWatch log + watchtower third party app When I access ECS EC2 and check nginx access.log, the following request periodically comes in. Why is this request coming to me? This is what keeps coming in the first time you open the server. In addition, my ecs server's security group 80/443 ports are opened to anywhere. nginx/access.log 183.129.160.229 - - [13/Jul/2017:17:46:14 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:47.0) Gecko/20100101 Firefox/47.0" 119.84.8.43 - - [13/Jul/2017:19:27:52 +0000] "GET http://flights.ctrip.com/international/ HTTP/1.1" 404 209 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" 119.84.8.43 - - [13/Jul/2017:19:27:53 +0000] "GET http://www.ceair.com/ HTTP/1.1" 200 396 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" 119.84.8.43 - - [13/Jul/2017:19:27:53 +0000] "GET http://www.hnair.com/ HTTP/1.1" 200 396 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" 119.84.8.43 - - [13/Jul/2017:19:48:04 +0000] "GET http://flights.ctrip.com/international/ HTTP/1.1" 404 209 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" 119.84.8.43 - - [13/Jul/2017:19:48:06 +0000] … -
No sends, no displays
HTML <div class="wrapper"> <div id="overlay"></div> <a href="#" title="{% trans "Send email - rejected file(s)" %}" class="btn btn-icon select-another-button" data-url="{% url "messaging:send" request_id=object.pk %}"> <i class="material-icons">assignment_late</i> <div class='alert alert-success' id="show-message" style="display: none;"> <p> The message was sent to the client. Please wait 5 minutes <br> before sending the message again. </p> </div> </a> </div> JavaScript $(function(){ var timeout; $('.select-another-button').each(function(){ $(this).bind('click', function(e) { $(this).attr('disabled','true'); //disables the button $('#overlay').show(); //after disabling show the overlay for hover timeout = setTimeout(function(){ $(this).attr('disabled','false'); //enables after 5mins $('#overlay').hide(); //hide the overlay }, 300000); e.preventDefault(); fileBrowser(this); return false; }); }); }); $("#overlay").hover(function(){ var timeleft = Math.ceil((timeout._idleStart + timeout._idleTimeout - Date.now()) / 1000); $('#show-message').html("Please wait" + timeleft).show(); },function(){ $('#show-message').hide(); }); Django @staff_member_required @csrf_exempt def send(request, request_id=None): req= Request.objects.get(pk=request_id) request_folders = req.folder.all_files.all() context = [] for doc in request_folders: if doc.meta.state == u'rejected': context.append(doc) if context: ctx = {'request': req} EmailFromTemplate('document-refusal', extra_context=ctx)\ .send_to(req.customer.user) return HttpResponse('') I've created a button which will send an email under certain conditions. So far I know I'm struggling with setTimeout from the JS section, but it is not the point of that question. Once I click on the button and the message is send, I'd like to deactivate the button for 5 minutes and then … -
Periodic Latency Issue with Angular/Apollo Client and Django-Graphene
I have successfully built a small GraphQL API using Django and Graphene. It consistently works properly with both GraphiQL and Postman. My colleague has built a companion client app with Angular 4 and Apollo. Our initial testing has revealed some strange results. Using Chrome, and the Developer Console open, most of the time it works fine, with results coming back very quickly. But when the Developer Console is closed it doesn't return any results for about 1 to 2 minutes. We're confused about why this is and what the root cause may be. I've searched extensively but not found any solutions. Has anyone else encountered something similar? Robert -
python can load GDAL, but django can't
I was able to successfully install gdal 1.11 and load it from python shell on my windows 32 bit machine. I can also verify its success by typing "gdalinfo --version" and getting the correct version info: GDAL 1.11.4, released 2016/01/25 However, when running "python manage.py shell" in django 1.11, I got error 127 'the specified procedure could not be found'. The error occurred when django called function lgdal = CDLL(lib_path) I printed out lib_path, it is correct. The same function worked fine in my python shell. Any idea why loading gdal111.dll would fail in the django environment when it has no problem in the python shell? Thanks.