Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Retrieve nested fields multiple levels deep using foreign keys
I'm struggling to write a Django GET that returns the following looking response: { "lists": [ { "id": "123", "list_order": [ { "id": "123_1", "order": 1, "list_id": "123", "item_id": 9876, "item": { "id": 9876, "name": "item1", "location": "California" } }, { "id": "123_2", "order": 2, "list_id": "123", "item_id": 2484, "item": { "id": 2484, "name": "item2", "location": "California" } } ], "updated_date": "2018-03-15T00:00:00Z" } ] } Given a list_id, the response returns the basic information on the list ("id", "updated_date"), as well as the order of items in the list. Inside each item in the list order, it also grabs the related item details (nested in "item"). Below are my models, serializers, and views. I'm able to get this response without the "item" details ("id", "name", "location" fields). models.py class Lists(models.Model): id = models.CharField(null=False, primary_key=True, max_length=900) updated_date = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'tbl_lists' class Items(models.Model): id = models.BigIntegerField(primary_key=True) name = models.TextField(blank=True, null=True) location = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'tbl_items' class ListOrder(models.Model): id = models.CharField(null=False, primary_key=True, max_length=900) list_id = models.ForeignKey(Lists, db_column='list_id', related_name='list_order') item_id = models.ForeignKey(Items, db_column='item_id', related_name='items') order = models.BigIntegerField(blank=True, null=True) class Meta: managed = False db_table = 'tbl_list_order' serializers.py class ItemsSerializer(serializers.ModelSerializer): … -
trying to use cookiecutter-django, getting errors and does not create anything
trying to get a Django project started using cookiecutter-django and can't seem to get it to generate anything. using Python 3.6, Django 2.0.5, cookiecutter 1.6.0 (then created a virtualenv and entered a new, blank directory) so I enter this command: cookiecutter https://github.com/pydanny/cookiecutter-django and get this error traceback: Traceback (most recent call last): File "c:\python\python36\lib\runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "c:\python\python36\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Python\python36\Scripts\cookiecutter.exe__main__.py", line 9, in File "c:\python\python36\lib\site-packages\click\core.py", line 722, in call return self.main(*args, **kwargs) File "c:\python\python36\lib\site-packages\click\core.py", line 697, in main rv = self.invoke(ctx) File "c:\python\python36\lib\site-packages\click\core.py", line 895, in invoke return ctx.invoke(self.callback, **ctx.params) File "c:\python\python36\lib\site-packages\click\core.py", line 535, in invoke return callback(*args, **kwargs) File "c:\python\python36\lib\site-packages\cookiecutter\cli.py", line 120, in main password=os.environ.get('COOKIECUTTER_REPO_PASSWORD') File "c:\python\python36\lib\site-packages\cookiecutter\main.py", line 63, in cookiecutter password=password File "c:\python\python36\lib\site-packages\cookiecutter\repository.py", line 103, in determine_repo_dir no_input=no_input, File "c:\python\python36\lib\site-packages\cookiecutter\vcs.py", line 99, in clone stderr=subprocess.STDOUT, File "c:\python\python36\lib\subprocess.py", line 336, in check_output **kwargs).stdout File "c:\python\python36\lib\subprocess.py", line 418, in run output=stdout, stderr=stderr) subprocess.CalledProcessError: Command '['git', 'clone', 'https://github.com/pydanny/cookiecutter-django']' returned non-zero exit status 128. -
how to add a prefix to a domain name in django
I've seen another site with this functionality and would like to have it on my site as well, but I have no clue how to go about it. Just say I had a membership site called www.mysite.com. I would like to have it so that each member can go to his personal console by adding prefix to the domain, for example www.myconsole.mysite.com. As I say I've seen this at another membership site I know. Any ideas how to go about this? -
django how to get request object (url param) in class based view
I have a class based view which has a query set like below: def get_queryset(self): queryset = Article.objects.all() return queryset If I pass an article id as a URL parameter like this: <url>/stories/?articleid=1000 Then how can I get this value in the get_queryset function so that I can use it to filter? something like below: def get_queryset(self): articleId = #get the article_id from URL. How to do this? queryset = Article.objects.filter(article_id=articleId) return queryset Any help is appreciated. -
Django annotate queryset with intersection count
Djangonauts, I need to tap your brains. In a nutshell, I have the following three models: class Location(models.Model): name = models.CharField(max_length=100) class Profile(models.Model): locations_of_interest = models.ManyToManyField(Location) class Question(models.Model): locations = models.ManyToManyField(Location) I want to find all Profiles which locations of interest intersect with the locations specified for a certain question. That’s easy: question = Question.objects.first() matching_profiles = Profile.objects.filter( locations_of_interest__in=question.locations.all() ) But in addition, I would also like to know to what extend the locations overlap. In plain python, I could do something like this: question_location_names = [l['name'] for l in question.locations.all()] for profile in matching_profiles: profile_location_names = [l['name'] for l in profile.locations_of_interest.all()] intersection = set(question_location_names).intersection(profile_location_names) intersection_count = len(list(intersection)) # then proceed with this number However, it seems to me favourable to do the operation directly in the database if possible. TL;DR So my question is: Is there a way to annotate the profile queryset with this intersection count and that way do the operation in the database? I have tried several things, but I don’t think they are helpful for those who read this and might know an answer. -
including login form in base.html
I'm using context_processors.py to pass the login form to all of my views, then I can include it in all of my pages here are my files context_processors.py from django.contrib.auth.forms import AuthenticationForm def include_login_form(request): login = AuthenticationForm() return {'login': login} base.html <div class="well well-small" style="width: 220px"> {% if user.is_authenticated %} <img src="{% static 'img/user.png' %}"> <div id="btns"> <a href="{% url 'logout' %}"><button class="btn-danger">تسجيل الخروج</button></a> </div> {% else %} <form method="post"> {% csrf_token %} {{ login.as_p }} <div id="buttons" align="right"> <button class ="btn btn-primary" type="submit">تسجيل الدخول</button><br><br> </div> </form> <a href="{% url 'signup' %}"><button type="button" class="btn btn-warning"> إنشاء حساب جديد</button></a> {% endif %} </div> But my login form is not working at all, It just reloads the page after pressing on submit any suggestions to solve this? -
How to add extra attrs each checkbox CheckBoxSelectMultiple?
How to add extra attrs each checkbox CheckBoxSelectMultiple? Does someone solved this problem? -
Django multiple model update/create
I am a beginning programmer in Django/Python and I am now looking for a way to robustly create and update my models. I would expect this is a very common problem. Some example code of how to do this the right way would be very much appreciated. Problems which I struggling with is that I am not sure where to put the save() command. Now there are multiple places where I put the save() method. And sometimes I have to multiple times hit the save button on the various views before a change on a low level trickless up to a higher level model. In this example I use two simplified models named Medium and Circuit. The create methods for the two models are specified as well as a set_medium and set_circuit method, this shows how I am currently doing it. class Circuit(models.Model): medium = models.ForeignKey('medium.Medium', related_name='medium_related', on_delete=models.CASCADE) temperature = models.FloatField(default=60, help_text='[degC]') glycol_percentage = models.FloatField(default=0, choices = choices.GLYCOL_PERCENTAGE) @classmethod def create( cls, temperature, glycol_percentage): circuit = cls( temperature = temperature, glycol_percentage = glycol_percentage) circuit.medium = Medium.create(circuit.temperature, circuit.glycol_percentage) circuit = circuit.set_circuit(circuit) circuit.save() return circuit def set_circuit(self, circuit): circuit.medium.glycol_percentage = circuit.glycol_percentage circuit.medium.temperature = circuit.temperature circuit.medium = circuit.medium.set_medium(circuit.medium) return circuit class Medium(models.Model): glycol_percentage … -
Is it a good idea to run a python shell script(having django models updates) through crontabs. Asking for production environment
I have made a parallel script to update some of my django model objects and i want to run this script periodically through crontabs. script looks like import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dataserver.settings") import django django.setup() from profiles.models import Profile #updating some Profile objects and saving Is this a good thing to do in a production server? why/why not? I know about celery handling asynchronous periodic tasks but want to know about this approach. -
Cannot query "Cast object (1)": Must be "Person" instance
I am trying to create a detail-list of my actor where it will show all the shows he has been a cast member of. This is part of mozilla's challenge yourself section at the end of the tutorial. I am having trouble filtering my class Cast so that I can get a specific Actor. I do not understand why the filter is not working. If self.object has a value of '3' for example, it should be filtering out all of the actors and only display the actor with the id of 3. But that does not seem to be the case. I also am not understanding the error code it is tossing out. My Cast class does have a foreignkey to person. Similar to my show details page, instead of casts, I want it to be the actor's starred in movies. Image of my Show Details Page View class ActorDetailView(generic.DetailView): model = Cast template_name = 'show/actor-detail.html' def get_context_data(self, **kwargs): context = super(ActorDetailView, self).get_context_data(**kwargs) context['casts'] = Cast.objects.filter(person_id=self.object) return context Models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Character(models.Model): name = models.CharField(max_length=128) on_which_show = models.ForeignKey('Show', on_delete=models.SET_NULL, null=True) def __str__(self): return self.name class Cast(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) cast_show = … -
create a simple textbox filter for listview in django
I am very new to django (few days old). I have a django installation and am trying to create a UI in django for a few of the database tables. In my database there are two tables - Articles and Author. The Articles table has a foreign key to Author table with field name as author_id. I have managed to create a ListView class that lists articles using code below: class ArticleListView(ListView): template_name = "article.html" context_object_name = 'articles' paginate_by = 25 def get_queryset(self): queryset = (Article.objects .all() .prefetch_related('author') .order_by('-created_at')) return queryset Then in the view I loop the Article queryset and prints its fields, and this works fine. (I had SO help to get it done). <h1>Articles</h1> <ul> {% for article in object_list %} <li>{{ article.pub_date|date }} - {{ article.headline }} - {{article.author.name}}</li> {% empty %} <li>No articles yet.</li> {% endfor %} </ul> I want to now create a very simple search for this list. As next step What I am trying to do is have a simple textbox in the template file just above the article listing. In this textbox the user can type either a string or a number. If it is a number, then I want to … -
Why does this python code crash my website? And this other python code does not?
Why does the python code below crash my website? And the other python code at the bottom does not crash the website? Here is the code that crashes the website: from django.urls import path, include from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls')) ] Here is the code that does not crash: from django.urls import path from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), ] I'm using python 3 and django 2 Thank you -
Django 2.0 Add to date N months when compared in the clean method
Yes, yes you can give me a bunch of examples with different implementations and mark it as a duplicate, but! All the answers I found were used by third-party libraries, not saying that they were written 2 to 7 years ago, we will return to them later. So, I have two dates in the database and a N number that characterizes the number of months. I need to compare one date with another by adding to it the number of months N. Perhaps in the new versions of Django or Pothon there are built-in implementations of this action? Let's return to third-party libraries. I met solutions with the use of manual calculation of type 365/12, etc. but they did not solve the problems with February, etc. Also I met the solutions with the use of dateutil, when I tried to use it at first glance everything started to work, but there was an intrusive error: 'module' object is not callable and swore it at this place: ...+relativedelta(months=+self.verifying_period_mounts) As I understood on the model field. Let me remind you that the number of Int. So maybe someone knows how to bypass the error or tell another way to implement new releases? -
Django rest framework errors in trying to persist an image
This is my UserProfile object, class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE, ) badge = models.ImageField(upload_to='media/badges/', null=True) reputation = models.IntegerField(default=0) status = models.CharField(max_length=255, null=True, blank=True) thumbnail = models.ImageField(upload_to='media/user/', blank=True, null=True) This is the Serializer, class UserProfileSerializer(serializers.ModelSerializer): thumbnail = serializers.ImageField(max_length=None, use_url=True, read_only=True) class Meta: model = models.UserProfile fields = ('badge', 'reputation', 'status', 'thumbnail',) This the api that tries to save the image, class CreateUpdateUserThumbnail(views.APIView): def post(self, request, **kwargs): user = User.objects.get(id=kwargs.get('user_id')) user.profile.thumbnail = UserProfileSerializer(instance=user.profile, data=request.data) if user.profile.thumbnail.is_valid(): user.profile.thumbnail.save() return Response(user.profile.thumbnail.data, status=status.HTTP_201_CREATED) else: return Response(user.profile.thumbnail.errors, status=status.HTTP_400_BAD_REQUEST) When I try to upload an image to this endpoint this is the error that I get, AttributeError: 'UserProfileSerializer' object has no attribute '_committed' What am I doing wrong here? -
How to use regex in python for a string
I have a string as stringvalue="UPI-917020028084740-GOOG-PAYMENT@OKAXIS-805214272567-UPI" I want to remove all special characters and number from the string except words by using regex in python I want the output to be as UPI GOOG PAYMENT OKAXIS UPI -
Django staff users permission to add staff user
let's suppose we have 2 or 3 type of users ! 1- superuser 2- admin 3- blogger i would like to admin users could add only admin and blogger but they don't have permission to create superuser class UserManager(aparnik.models.UserManager): def create_superuser(self, request, username, first_name, last_name, is_staff=None, password=None): if not request.user.is_superuser: ValueError('buggggg!') user = self.model( username=username, first_name=first_name, last_name=last_name, sex=User.SEX_MALE, is_staff=True, is_active=True, is_superuser=True ) user.save() return user class User(aparnik.models.User): # REQUIRED_FIELDS must contain all required fields on your User model, # but should not contain the USERNAME_FIELD or password as these fields will always be prompted for. # REQUIRED_FIELDS = ['first_name', 'last_name', 'is_staff'] # latitude = FloatField( # verbose_name=_('Latitude'), # null=True, # blank=True # ) # # longitude = FloatField( # verbose_name=_('Longitude'), # null=True, # blank=True # ) website = URLField( verbose_name=_('Website'), max_length=61, help_text='personal website', blank=True, null=True ) biography = TextField( verbose_name=_('Biography'), help_text='i have been programming since 8 years ago and at the end i am pretty much newbie', null=True, blank=True ) landline_phone = PhoneField( mobile=False, unique=True, verbose_name=_('Landline Phone'), null=True, blank=True ) major = CharField( max_length=127, verbose_name=_('Major'), default='Software Engineering', help_text='Software Engineering', null=True, blank=True ) university = CharField( max_length=63, verbose_name=_('University'), null=True, blank=True ) degree = ForeignKey( Degree, null=True, blank=True ) objects = models.UserManager() … -
Template for Image grid and select
I am working on a website withDjango, and I would like to make a page where: There is a table listing all the images of a model There are two available space two show the images selected by the user Example: image grid display Currently, in my template I produce the table like that: <table class="table table-striped table-advance table-hover"> <tr> <th>Field 1</th> <th>Field 2</th> <th>Field 3</th> </tr> {% for imagemodel in imagemodel %} <tr> <td>{{ imagemodel.image }}</td> <td>{{ imagemodel.date_taken }}</td> <td>{{ imagemodel.image.url }}</td> </tr> {% endfor %} </table> I don't know what would be the best way to make my wish feasable: Is it possible to do that only with javascript ? or only html ? Should I work through my django view ? Many thanks for your help, I am lost :/ Cheers. -
Adding forms to Django DetailView ERROR message:Method Not Allowed (POST)
Hi Djangonauts I am trying to Build a Question and Answer type app like "StackOverflow" or "Quora" I am new to Django. so please forgive any silly mistakes in logic or code. Below is my error Before: I made the question and answer app and it worked fine. The Question Detail page had the Question and an answer button to let the user answer the Question. When the user clicks on the button he goes to a new "answer_form.html" writes his answer and clicks Save His answer then shows in the Question Detail page. Till here everything worked fine The Problem: Now I don't want the user to leave the Question Detail page post his answer, I used JavaScript to make the answer_form to appear on the question detail page, However now when the user clicks Save I get a error This page isn’t working If the problem continues, contact the site owner. HTTP ERROR 405 How can I fix this error. I am sure a lot of people don't want people to leave the detail page to comment a post or answer a question. Below are my views and template details views.py class AnswerCreate(LoginRequiredMixin, CreateView): model = Answer form_class … -
Laravel's dd() equivalent in django
I am new in Django and having a hard time figuring out how to print what an object have inside. I mean type and value of the variable with its members inside. Just like Laravel's dd(object) function. Laravel's dd() is a handy tool for debugging the application. I have searched for it. But found nothing useful. I have tried pprint(), simplejson, print(type(object) and {% debug %}. But none of them could provide the required information about an object. Here is a sample output from Laravel's dd() function. In this Image, I am printing the request object of Laravel. as you can see its showing complete information about an object. I mean name of class it belongs to, its member variables. also with its class name and value. and it keeps digging deep inside the object and prints all the information. But I am not able to find a similar tool in Django. That's hard to believe that Django doesn't have such a useful tool. Therefore I would like to know about any third party package that can do the trick. I am using Django version 2.0.5. and trying to print django.contrib.messages -
The model field, which is only modifiable in the function
In my project there is information about the devices and their verification. There are data with dates, these dates indicate the periods of verification. I need to create a BooleanField, which can only be changed by the custom function that the user invokes in the admin panel. So here's how to create a BooleanField, which will be read-only in the forms of modification and addition. -
url pattern to accept dots, -, letters and digits
How my url pattern should looks like if I need to accept urls like this? My try: url(r'^users/items/(?P<item_id>[-.\w\d]+)$', MyView.as_view()) example: /users/items/abcde.xyz.item.AHR24LEFUQCEIFFJW/ -
Django override init in proxy models
Given a concrete model MyModel having an item_type field I want to create different proxy models to establish a (python only) inheritance identified by the item_type field. This is a simplification: ITEM_TYPE_CHOICES = ( (TYPE_A, _('type_a')), (TYPE_B, _('type_b')), ) class OtherModel(models.Model): title = models.CharField(_('Title'), max_length=200) def __str__(self): return "{} - {}".format(self.pk, self.title) class MyModel(models.Model): item_type = models.CharField(max_length=12, choices=ITEM_TYPE_CHOICES) another_model = models.ForeignKey(OtherModel, related_name='my_models') def __str__(self): return "{}-{}-{}".format(self.item_type, self.pk, self.another_model) class SubModelA(MyModel): class Meta: proxy = True def __init__(self, *args, **kwargs): super().__init__(self, *args, **kwargs) self.item_type = TYPE_A class SubModelB(MyModel): class Meta: proxy = True def __init__(self, *args, **kwargs): super().__init__(self, *args, **kwargs) self.item_type = TYPE_B This code work without problems. The problem comes from the overriding of the __init__ done in the proxy subclasses. Whenever creating a MyModel directly I have to explicitly pass the item_type but if I want to create instances from for example SubModelA I already know the type argument should be TYPE_A. For this reason I've overridden the init methods: def __init__(self, *args, **kwargs): super().__init__(self, *args, **kwargs) self.item_type = TYPE_A Also this work correctly but it has side effects. In particular If I create two objects: other = OtherModel(title = 'hello') ob1 = MyModel(another_field = other, item_type=TYPE_A) ob2 = … -
Django abstract model + DB migrations: tests throw "cannot ALTER TABLE because it has pending trigger events"
I want to write an abstract model mixin, that I can use to make OneToOne - relations to the user model. Here is my code: from django.conf import settings from django.db import models class Userable(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) class Meta: abstract = True I've written the following test for this model: class TestUserable(TestCase): model = Userable def setUp(self): user = User.objects.create_user( email="testuser@test.com", name="Test User", password="test1234test" ) self.user = user self.model = ModelBase( '__TestModel__' + self.model.__name__, (self.model,), {'__module__': self.model.__module__} ) with connection.schema_editor() as schema_editor: schema_editor.create_model(self.model) def test_uuid(self): self.model.objects.create(user=self.user) self.assertEqual(self.model.objects.count(), 1) def tearDown(self): with connection.schema_editor() as schema_editor: schema_editor.delete_model(self.model) My problem is, that this test in it's tearDown() method throws the follwing error: django.db.utils.OperationalError: cannot DROP TABLE "core___testmodel__userable" because it has pending trigger events What could be the cause of this? I did run python manage.py makemigrations and python manage.py migrate, but there are no pending migrations (as is expected, since this is an abstract model. -
Django Celery task expired repeatedly without any calling as soon as celery started
I did use celery in django. Celery scheduled task has expired incessantly as soon as celery started. [2018-05-27 18:37:22,466: INFO/Beat] beat: Starting... [2018-05-27 18:37:22,479: INFO/Beat] Writing entries... [2018-05-27 18:37:22,543: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// [2018-05-27 18:37:22,595: INFO/MainProcess] mingle: searching for neighbors [2018-05-27 18:37:22,679: INFO/Beat] DatabaseScheduler: Schedule changed. [2018-05-27 18:37:22,679: INFO/Beat] Writing entries... [2018-05-27 18:37:22,727: INFO/Beat] Scheduler: Sending due task ex_rate_update_task (celery_task.tasks.updateInfo) [2018-05-27 18:37:22,731: WARNING/Beat] scehduled > [2018-05-27 18:37:22,732: WARNING/Beat] => update_task : [2018-05-27 18:37:22,732: WARNING/Beat] 2018-05-27 18:37:22.730208 [2018-05-27 18:37:22,733: INFO/Beat] Task celery_task.updateInfo[54b6ab8d-d8ce-4806-a5d6-70860d75eb02] succeeded in 0.0034391450171824545s: None [2018-05-27 18:37:22,734: INFO/Beat] Writing entries... [2018-05-27 18:37:22,754: INFO/Beat] Scheduler: Sending due task ex_rate_update_task (celery_task.tasks.updateInfo) [2018-05-27 18:37:22,757: WARNING/Beat] scehduled > [2018-05-27 18:37:22,757: WARNING/Beat] => update_task : [2018-05-27 18:37:22,757: WARNING/Beat] 2018-05-27 18:37:22.756909 [2018-05-27 18:37:22,757: INFO/Beat] Task celery_task.updateInfo[4acdf40b-c4a4-4551-ab57-f1f9671abc82] succeeded in 0.0010353299730923027s: None [2018-05-27 18:37:22,759: INFO/Beat] Scheduler: Sending due task ex_rate_update_task (celery_task.tasks.updateInfo) [2018-05-27 18:37:22,760: WARNING/Beat] scehduled > [2018-05-27 18:37:22,760: WARNING/Beat] => update_task : [2018-05-27 18:37:22,764: WARNING/Beat] 2018-05-27 18:37:22.760353 [2018-05-27 18:37:22,764: INFO/Beat] Task celery_task.updateInfo[ba6ddfa9-b1f7-4d4f-972e-6bef96ddb0d3] succeeded in 0.004193355998722836s: None [2018-05-27 18:37:22,766: INFO/Beat] Scheduler: Sending due task celery_task.updateInfo (celery_task.tasks.updateInfo) [2018-05-27 18:37:22,767: WARNING/Beat] scehduled > [2018-05-27 18:37:22,768: WARNING/Beat] => update_task : [2018-05-27 18:37:22,768: WARNING/Beat] 2018-05-27 18:37:22.767552 [2018-05-27 18:37:22,769: INFO/Beat] Task celery_task.updateInfo[7f36b3f8-250e-4ed1-8490-9aeb8bdc8b58] succeeded in 0.001550107990624383s: None [2018-05-27 18:37:22,771: INFO/Beat] Scheduler: Sending due task celery_task.updateInfo … -
Error import whitenoise
I'm trying to deploy my website in pythonanywhere.com following djangoGirls tutorial. When I run my website, It give me this error: Error running WSGI application ImportError: No module named 'whitenoise' File "/var/www/cryptoassistant_pythonanywhere_com_wsgi.py", line 7, in module> from whitenoise.django import DjangoWhiteNoise My WGSI file: import os import sys from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(get_wsgi_application()) path = '/home/cryptoassistant/tfg/' if path not in sys.path: sys.path.append(path) and my setting.py file: MIDDLEWARE_CLASSES = ( 'django.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) I installed whitenoise $ pip install whitenoise > Requeriment already satisfied: whitenoise in path (3.3.1) What I should change?