Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django model save to several tables
The save method saves instance into two different tables, AgencyBeforeReg and Agency, i have a problem saving Services field which is manyToMany field, how can it be done? def save(self, force_insert=False, force_update=False, using=None): if self.id and self.active: self.sign = 'f' if not self.active: self.sign = 'c' self.deactivate_date = datetime.datetime.now() super(AgencyBeforeReg, self).save(force_insert, force_update, using) agency = Agency.objects.create( id=self.id, unpf=self.unpf, unp=self.unp, egr=self.egr, title=self.title, reg_date=self.reg_date, reg_organ=self.reg_organ, post_index=self.post_index, place=self.place, office=self.office, # services=self.services, ins_date=self.ins_date, edit_date=self.edit_date ) agency.services.add() -
django StreamingHttpResponse response to download in angular4 as file
We have a site prepared in django and the front end is angular 4 when django return the response we have to get the response and download it as a file. -
Migrating social_auth to django_social using Django 1.11 and Python 3.6
I'm having problem while trying to migrate social_auth module to django_social using Django 1.11 and Python 3.6. I have some models in my models.py file that uses from social_auth.signals import pre_update, socialauth_registered from social_auth.backends.facebook import FacebookBackend from social_auth.backends.twitter import TwitterBackend but I can't find the equivalent to social_auth.signals into django_social Are they deprecated? Is there a newer version to use them? -
Django Models to Template
This might be a simple questions, but please keep in mind this is my first Django project. I have the following models: User Client Quote The user has many Client which has many Quotes How can I render the latest three quotes to the view? Regardless of the client. How can I render back all of the quotes for a particular client? How can I ensure that other Users clients/quotes are not seen unless it is their client/quote. Thanks in advance, CH -
Form to edit specific instance of model
I know this question has been asked before but I have read through the answers and none of them sufficed. I am trying to make a job board site, where an employer can sign up and post jobs. So there is an Employer object and each employer can post as many Jobs as they want. I am not sure how to create a form where a particular model instance can be edited. The model Job: 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) city = models.CharField(max_length = 50) state_choices = ( #long list omitted on purpose ) state = models.CharField(choices=state_choices, 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 I have a form to post jobs: class JobPostForm(ModelForm): class Meta: model = Job fields= ('job_title', 'establishment_name', 'details', 'address', 'city', 'state', 'zip_code', ) a view to post jobs: if request.method == 'POST': form = JobPostForm(request.POST) if form.is_valid(): job_object = form.save(commit=False) job_object.poster = request.user.employer job_object.save() return redirect('employer_home') else: form = JobPostForm() and a template … -
Attempting to create view for a list of all books on loan to the current user
I am attempting to create a view that lists all the books on loan to a specific user in my library app. However I keep getting the following error : When the user clicks on the books borrowed link the user should be redirected to the list view which contains the books the user borrowed with the name of the book rendered as a link that allows the user to access the detail view of the book. Here is the code : models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from datetime import date class Genre(models.Model): genre_name = models.CharField(max_length = 200, help_text = "Enter a book genre") def __str__(self): return self.genre_name class Mind_Book(models.Model): Title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null = True) Summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book") isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href = "https://www.isbn-international.org/content/what-isbn">ISBN Number</a>') genre_relation = models.ManyToManyField(Genre, help_text = "Selct a genre for this book") language_relation = models.ForeignKey('Language', on_delete=models.SET_NULL, null = True) def __str__(self): return self.Title # returns the url to access a particular book instance def get_absolute_url(self): return reverse('book-detail', args= [str(self.id)]) def genre_representation(self): return ', '.join([genre_relation.genre_name for genre_relation in self.genre_relation.all()[:3]]) genre_representation.short_description = 'Genre' import … -
Django admin user permissions
On my Django admin page, I am trying to get the user permissions fieldsets. But the page doesn't load after I put user_permissions. All the other fields work except this. I am trying to manage permissions through admin page and give a user a specific permissions by moving some individual permissions. class UserAdmin(BaseUserAdmin, HijackUserAdminMixin): # The forms to add and change user instances form = UserChangeForm add_form = UserCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('email', 'first_name', 'last_name', 'hijack_field') list_filter = ('first_name', 'last_name') # change form fields fieldsets = ( ('User', {'fields': ('username', 'email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name',)}), ('Permissions', {'fields': ('is_staff', 'is_superuser', 'groups')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ('User Permissions', {'fields': ('user_permissions',)}), ) All the fields work except user_permissions. I have checked the class UserAdmin from which it extends has this. @admin.register(User) class UserAdmin(admin.ModelAdmin): add_form_template = 'admin/auth/user/add_form.html' change_user_password_template = None 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')}), I am able to view all the fields except user_permissions.Is … -
Django - getting user permissions in a view only shows model views, not custom permissions
Im trying to get a list of user permissions in a script that pulls info from Django (not using a request). I have managed to do this, however when I look at a list of permissions, the custom permissions ive added via a models meta are not in this list. my script: from django.contrib.auth.models import User from django.contrib.auth.models import Permission result = '' i = Inbox(settings.ON_CALL_MAILBOX_AUTH,getNow=False) # filter sample (IsRead eq false) and (Subject eq 'who') i.setFilter("(IsRead eq false)") try: i.getMessages() except: admin_email('Email Processing Failed','Failed to get messages, either all the messages are read or credentials are incorrect') result = 'Failed to get messages, either all the messages are read or credentials are incorrect' for mail in i.messages: #get details of mail sender = Message.getSender(mail)['EmailAddress']['Address'] subject = Message.getSubject(mail) subject = subject.strip() result = 'unread mail from {0}'.format(sender) can_email_query = False user = User.objects.filter(email=sender) if user: user_permissions = Permission.objects.only('name').filter(group__user=user) if "can email query" in str(user_permissions).lower(): can_email_query = True so im looking for a perm ive set in my model of user profile class UserProfile(models.Model): mpls_m_subscriptions = models.CharField(max_length=50,verbose_name="MPLS Maintenance Subscription",choices=settings.SUBSCRIPTION_TYPE,blank=True,null=True) user = models.OneToOneField(User, on_delete=models.CASCADE) class Meta: permissions = ( ("can_email_query", "Can email query"), ) this perm is assigned to my user group … -
dynamically importing models in django throws models not ready
in my venues app model file I am dynamically adding models I need to do work. from django.apps import apps state = apps.get_model('suitsandtablesadmin', 'State') suitscity = apps.get_model('suitsandtablesadmin','City') suitsneighboorhood = apps.get_model('suitsandtablesadmin', 'Neighborhood') venuetypes = apps.get_model('suitsandtablesadmin', 'VenueTypes') venueseatingtypes = apps.get_model('venueadmin', 'SeatingTypes') costofvenue = apps.get_model('venueadmin', 'VenueCost') venuecusines = apps.get_model('venueadmin', 'Cusines') roomprivacy = apps.get_model('venueadmin', 'Roomprivacy') roomamenities = apps.get_model('suitsandtablesadmin', 'Amenities') I am doing this because a regular import statement will not work. Python says it can find the model, I am guessing because of circular importing. I see from this stackoverflow answer that it may be best to import the entire app into the file but how will that help? And is there a better solution? Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet I also have yet to create any type of migrations is that a cause? Relevant part of the trace back below `File "/home/ri`ckus/Documents/softwareProjects/211hospitality/suitsandtables/backend/suitsandtablesbackend/virtualsuits/suitsandtables/venues/models.py", line 7, in <module> state = apps.get_model('suitsandtablesadmin', 'State') File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/suitsandtablesbackend/virtualsuits/local/lib/python2.7/site-packages/django/apps/registry.py", line 193, in get_model self.check_models_ready() File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/suitsandtablesbackend/virtualsuits/local/lib/python2.7/site-packages/django/apps/registry.py", line 132, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
Django OneToOneField on foreign table
I'm trying to setup a new server with foreign tables (using postgres_fdw) that weren't foreign tables previously, and I have some OneToOneFields pointing to these tables. This doesn't work out of the box - OneToOneFields use foreign keys, and postgres_fdw does not support foreign keys for foreign tables. The foreign tables are in a read-only database on the same server. Is there an easy way to get this working? -
Deploying django application on nginx server rhel - 400 bad request Request Header or cookie too large
I'm currently trying to deploy a Django app on a REHL 7.4 server using Nginx. I've followed these tutorials : https://simpleisbetterthancomplex.com/tutorial/2017/05/23/how-to-deploy-a-django-application-on-rhel.html https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 The virtualenv and the nginx server seems to be allright. However I'm struggling with two errors: Either I got a 500 error because of worker_connections parameter value (below are logs): 13494#0: *1021 1024 worker_connections are not enough while connecting to upstream, client: 192.168.1.33, server: 192.168.1.33, request: "GET /Syc/login HTTP/1.0", upstream: "http://192.168.1.33:80/Syc/login", host: "192.168.1.33" Either I increase worker_connections value to > 4096 and I get a 400 error like in this thread 400 Bad Request - request header or cookie too large Below are my nginx.conf and app.conf, please let me know if there are configuration mistakes and thanks in advance for any help. nginx.conf: include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } # set open fd limit to 30000 worker_rlimit_nofile 30000; http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; } server { listen 80 default_server; listen … -
Passing parameters from ModalFormView to a form
I'm trying to send a list of names as choices for a modified choice field, so I can search for the choices by typing some text within the form's field, here's my view: class OfferFormModal(ModalFormView): def __init__(self, *args, **kwargs): super(OfferFormModal, self).__init__(*args, **kwargs) self.title = "ServiceOffer" services = Service.objects.filter(provider=Provider.objects.get(id=9)) choices = list() for service in services: choices.append(service.name_service) self.form_class = OfferServiceForm(data_list=choices) def form_valid(self, form, **kwargs): data = form.cleaned_data ... self.response = ModalResponse('Done', 'success') return super(OfferFormModal, self).form_valid(form) My Form looks like this: class OfferServiceForm(forms.Form): service = forms.CharField(required = True,label="") description = forms.CharField( required=True, label="", widget=forms.Textarea ) def __init__(self, *args, **kwargs): _service_list = kwargs.pop('data_list', None) super(OfferServiceForm, self).__init__(*args, **kwargs) self.fields['service'].widget = ListTextWidget( data_list=_service_list, name='service-list', attrs={'placeholder':'Service:'}) I did something similar before in a normal view without issue, but now whenever I try to load this within the ModelFormView I'm met with this error: return form_class(**self.get_form_kwargs()) TypeError: 'OfferServiceForm' object is not callable Why is it not callable as super? Am I missing something? -
django connection error using DjANGO Q package
I create I python function where I use it in my views.py to calculate some numbers but that calculate algorithm take a long time to finish it and I want to avoid long time processing reload page using DJANGO Q package and specific async. but I take this error : ConnectionError at /url/url1/ Error 10061 connecting to localhost:6379. ��� ���� ������ � ���������� ��������,. here my code : views.py import logging from django_q.humanhash import humanize from django_q.models import OrmQ from django_q.tasks import async, Task from simple_search import search_filter import os logger = logging.getLogger(__name__) @login_required(login_url="login/") def app_details(request,slug): if request.method == "POST": test = request.POST.get('car') in1 =test in2=in1*10000 task_id = async('mysite.tasks.myalg', input1=in1, input2=in2) return render(request, 'details.html') tasks.py def myalg(input1,input2): ................... ................... any idea why ? -
Is it possible to send many requests asynchronously with Python
I'm trying to send about 70 requests to slack api but can't find a way to implement it in asynchronous way, I have about 3 second for it or I'm getting timeout error here how I've tried to t implement it: import asyncio def send_msg_to_all(sc,request,msg): user_list = sc.api_call( "users.list" ) members_array = user_list["members"] ids_array = [] for member in members_array: ids_array.append(member['id']) real_users = [] for user_id in ids_array: user_channel = sc.api_call( "im.open", user=user_id, ) if user_channel['ok'] == True: real_users.append(User(user_id, user_channel['channel']['id']) ) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(send_msg(sc, real_users, request, msg)) loop.close() return HttpResponse() async def send_msg(sc, real_users, req, msg): for user in real_users: send_ephemeral_msg(sc,user.user_id,user.dm_channel, msg) def send_ephemeral_msg(sc, user, channel, text): sc.api_call( "chat.postEphemeral", channel=channel, user=user, text=text ) But it looks like I'm still doing it in a synchronous way Any ideas guys? -
CAS Server url configuration raising a 403
After my last question I managed to figure out how to setup django-mama-cas and django-cas-ng for the most part. Had to port django-cas-ng to work on Django 1.11 and my setup. Now, I think my MAMA_CAS_SERVICES setting might be wrong for the services url. Lets say I got to seconddomain.com/accounts/login. This sends me to mycasserver.com/cas/login where I can login. Upon logging in there it adds a query to the url but I get a 403 (permission denied) on urls of this form. Example: mycasserver.com/cas/login?next=ticket....... This happens when one domain is still logged in but the other isn't (the one I'm logging into) since I'm not forcing the signout to propagate between the domains. My MAMA_CAS_SERVICES setting: { 'SERVICE': '^https?://mydomain1.herokuapp.com/', 'CALLBACKS': [ 'mama_cas.callbacks.user_name_attributes', ], 'LOGOUT_ALLOW': True, 'LOGOUT_URL': 'https://mycasserver.herokuapp.com/cas/logout', }, { 'SERVICE': '^https?://mydomain2.herokuapp.com/', 'CALLBACKS': [ 'mama_cas.callbacks.user_name_attributes', ], 'LOGOUT_ALLOW': True, 'LOGOUT_URL': 'https://mycasserver.herokuapp.com/cas/logout', }, -
Django: How to handle duplicate form submission
How to handle second submission duplicate request If user was trying to refresh the page, When the first submission is not finished yet because of server lag. client side disabling submit button to avoid multiple submits. and handled Post/Redirect/Get pattern after form submit redirect to success view I believe both are handled well. class SomeView(View): def post(self, request, *args, **kwargs): if form.is_valid() if request_exists(request): # here I can raise the exception also # But How I redirect the customer to sucess page # If 1st submission got success response. else: # here I have called internal api to get/post some data. # user refreshes before this call has completed. ... # once getting respose its ALWAYS redirect to new page return HttpResponseRedirect('/thanks/') But how to handle the case If delay from getting a response from API call. I need to delay until the first submission finishes. Then I have to send the user to the thanks page. -
Can we retrieve image properties from image after uploading in server?
I want to know the image properties like image pixels and dpi etc after uploading image in server using Python language. what is the best possible approach/technique to use.Thanks for your help. -
Get the values from one app to another in Django
I am working on creating shopping cart. I am still in learning phase. I need to know how I can pass/use values from shop's models.py to cart's cart.py. shop/models.py class Product(models.Model): delivery_price = models.DecimalField(max_digits=10, decimal_places=0,default=0) support_price = models.DecimalField(max_digits=10, decimal_places=0,default=0) cart/cart.py : I think this is the file where I need to get delivery_price and support_price. I dont know how I can get these two values. I want to add these prices and multiply it by quantity (something like Product.delivery_price + Product.support_price * item.quantity -> not sure about the way this is being done) How is this flow working? If anyone help me understand, it would be great. class Cart(object): def __init__(self, request): def add(self, product, quantity=1,update_quantity=False, support_req=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] … -
Django queryset filter weekday is different in database
I'm using Django 1.10 with Postgres. I have a class defined as : class Availability(models.Model): profile = models.ForeignKey(Profile) date = models.DateField() And I'd like to get all the availabilities which date is a monday. In my database, I have a availibity which date is a monday. I used : Availability.objects.filter(profile=profile, date__week_day=2) as defined in the Django doc, 2 being monday : https://docs.djangoproject.com/en/1.10/ref/models/querysets/#week-day But it returns no objects. I then tried to change the week_day and the queryset returns the right object when I used date__week_day=4. I tried with other week days, and it appears that their is always a gap of 2 weekdays between the query_set and the database. Is there a configuration to set which day should be the start of the week ? -
Django Trunc data to 15 minutes
I am currently using the Truc function of Django to aggregate some data within the day and hour. I would like to do the same but over 15 minutes, instead of an hour or just a minute but I can't figure it out. Here is an example of my current query: data_trunc = data_qs.annotate( start_day=Trunc('date_created', 'minute', output_field=DateTimeField())) .values('start_day', 'content', 'device') The problem lies with the 'minutes' argument that can be passed to Trunc. As far as I get it, there is no choice inbetween 'hour' and 'minutes'. How can I group my data over 15 minutes and have a larger time span for the data grouping ? I know that I could do this by hand afterward but I'd really like to have the database do this for me since there is a large dataset to compute and this way is the most efficient one I have yet. If this is the only way though I am opened to suggestions to the most efficient ways to get around this. Thanks for your help -
405 on Exporting CSV file in django
I'm trying to export some data to downloadable csv file. When I click "Export" button on my website everything works up to a point when I get 405 response. The post method works as expected, in response I see all expected data. The filtering ptocess below works as expected as well. Here is the view class: class ExportInvoicesToCsvView(View, IsSuperuserMixin): http_method_names = ['post', 'get'] def post(self, request, *args, **kwargs): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = ( 'attachment; filename=raport.csv' ) writer = csv.writer(response, delimiter=';') filters = json.loads(self.request.body.decode('utf8')) data = Data.objects.filter(filters) writer.writerow([ 'data.a', 'data.b', 'data.c', 'data.d', 'data.e' ]) return response The url config is as follows: url( r'^invoices-csv/$', ExportInvoicesToCsvView.as_view(), name='invoices-csv' ), And html template: <a href="{% url 'accountant:bills:invoices-csv' %}" type="button" class="btn btn-sm btn-default" ng-click="getSelected()"> <i class="fa fa-files-o fa-2x pull-left"></i> &nbsp;{% trans 'Exportuj do csv' %} </a> -
Signal Handler Issue
First off I'm using LDAP authentication with Python 3.6 and Django 1.11, if a user is verified with AD it will create the username, password in my User table. Then I have a pre-populated table which is not to be modified or changed called AllEeActive that has a primary key of employee_ntname which I made a OneToOneField using the following class AllEeActive(models.Model): employee_ntname = models.OneToOneField(User, db_column='Employee_NTName',max_length=12) 40 other fields @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: AllEeActive.objects.create(employee_ntname=instance) AllEeActive.objects.get(employee_ntname=instance).save() @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: AllEeActive.objects.create(employee_ntname=instance) AllEeActive.objects.get(employee_ntname=instance).save() class Meta: managed = False def __str__(self): return self.employee_ntname I combined my create and save into one signal call, but for some reason it gives me the error message that accounts.models.DoesNotExist: AllEeActive matching query does not exist. Any idea as to why this is the name of the database table and my model? -
Connect Django with existing remote MySQL schema
Im trying the get data from an existing remote MySQL table with raw SQL in Django. In other words I do not have to create tables (models in Django) - just read data in a table in a 1st step. The following class is working on the localhost class Person(models.Model): first_name = models.CharField(20) last_name = models.CharField(20) for p in Person.objects.raw('SELECT * FROM myapp_person'): print(p) The result: John Smith Jane Jones How can I define a class or function to get data out of an existing database.table, based on raw SQL, without generating first a class for creating the table ? Many thanks ! -
In Django how to get this pandas dataframe to a template?
django newbie question: Documentation with django and pandas focuses on models. I need to understand better how to trace the model, view and template where pandas is involved. Here is an application problem: I am trying to display mobile telephone allowances in an app. For example, each mobile connection has a mandatory tariff and also four optional, value added services ('VAS'). Tariffs cannot be VAS, but you could have the same VAS four times to boost your allowances. There is a single table 'Tariff' for managing the details of all tariffs and VAS. For each call line identifier (mobile phone connection), we need to read the call minutes, data megabytes and text count allowances that sum from the associated tariff and four VAS columns. # models.py class Tariff(models.Model): tariff_name = models.CharField(max_length=200, unique=True, db_index=True) minutes = models.IntegerField(blank=True, null=True,) texts = models.IntegerField(blank=True, null=True,) data = models.FloatField(null=True, default=0) is_tariff_not_VAS = models.BooleanField(default=True) class CallLineIdentifiers(models.Model): mobile_tel_number = models.CharField(max_length=11, blank=False, null=False, db_index=True) tariff = models.ForeignKey(Tariff, related_name = 'tariffName' ) vas_1 = models.CharField(max_length=100, blank=False, null=False, default=0,) vas_2 = models.CharField(max_length=100, blank=False, null=False, default=0,) vas_3 = models.CharField(max_length=100, blank=False, null=False, default=0,) vas_4 = models.CharField(max_length=100, blank=False, null=False, default=0,) So far, so good. I can render an html page displaying allowances for … -
Dockerizing DJango app error: ModuleNotFoundError: No module named 'django'
I am trying to Dockerize a DJango app that is already complete (and working). To do so, I am following this link here: https://docs.docker.com/compose/django/ problem When running docker-compose up Removing intermediate container 401e0a3db63c Step 12/14 : RUN DATABASE_URL=none /venv/bin/python manage.py collectstatic --noinput ---> Running in 6dcffbe27155 Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> import django ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? here is the Dockerfile I am using FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN set -ex \ && apk add --no-cache --virtual .build-deps \ gcc \ make \ libc-dev \ libffi-dev \ zlib-dev \ freetype-dev \ libjpeg-turbo-dev \ libpng-dev \ musl-dev \ linux-headers \ bash \ pcre-dev \ postgresql-dev \ python3-dev \ && pyvenv …