Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail settings only use .dev
I do not understand how to alternate between production and dev settings. Wagtail docs do not cover it and the only wagtail tutorial I can find mentions it and then completely skips over it. There is a settings file: --| settings ----| __init__.py ----| base.py ----| dev.py ----| production.py ----| .env my init file: import os from os.path import join, dirname from dotenv import load_dotenv dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) ENV = os.environ.get('AMSS_ENV') if ENV == 'dev': from .dev import * elif ENV == 'prod': from .production import * AMSS_ENV is set to 'prod'. I also have the DJANGO_SETTINGS_MODULE variable set to production in the .env from a different attempt. Does the init file not fire first? is my logic broken? I get no errors and everything works but it loads in dev every time. I've tried so many other things and it just sticks like this. Can someone tell me what am I supposed to do? or where I can look? -
pyodbc import error while using alpine image
I have below docker file FROM python:3.7-alpine # Create a group and user to run our app ARG APP_USER=appuser RUN addgroup -S ${APP_USER} && adduser -S ${APP_USER} -G ${APP_USER} RUN export CGO_ENABLED=0 RUN set -ex \ && RUN_DEPS=" \ pcre-dev \ shared-mime-info \ mariadb-dev \ nano \ busybox-extras \ curl \ " \ && seq 1 8 | xargs -I{} mkdir -p /usr/share/man/man{} \ && apk update && apk add --virtual buildups $RUN_DEPS \ && rm -rf /var/lib/apt/lists/* \ && apk del buildups # Copy odbc config file ADD odbcinst.ini /etc/odbcinst.ini # Copy in your requirements file ADD requirements.txt /requirements.txt RUN set -ex \ && BUILD_DEPS=" \ pcre-dev \ libpq \ gcc \ libc-dev \ g++ \ libffi-dev \ libxml2 \ unixodbc-dev \ build-base \ " \ && apk update && apk add --virtual buildups $BUILD_DEPS \ && apk update \ && pip install --no-cache-dir -r /requirements.txt \ \ && apk del $BUILD_DEPS \ && rm -rf /var/lib/apt/lists/* \ && apk del buildups RUN mkdir /code/ WORKDIR /code/ ADD . /code/ RUN chmod g+rx,o+rx / EXPOSE 8000 USER ${APP_USER}:${APP_USER} ENTRYPOINT ["/code/docker-entry-script.sh"] CMD ["runserver"] odbcinst.ini (checked inside container "Driver path and file is not there" [ODBC Driver 17 for SQL Server] … -
How to accept some of the form fields (not all) as CSV in Django?
I have a Django model with 2 fields as latitude and longitude. I've declared them both as a CharField. My model needs to accept more than 1 coordinates (latitude and longitude), so while entering in the rendered form (in the UI), I'm entering these coordinates separated by commas. It's this char input which I'm then splitting in the function and doing my computations.. This is my models.py class Location(models.Model): country = models.ForeignKey(Countries, on_delete=models.CASCADE) latitude = models.CharField(max_length=1000,help_text="Add the latitudes followed by comma or space") longitude = models.CharField(max_length=1000,help_text="Add the longitudes followed by comma or space") This is my view.py function def dashboard(request): form = LocationForm if request.method == 'POST': form = LocationForm(request.POST) if form.is_valid(): form.save() latitude = list(map(float, form.cleaned_data.get('latitude').split(','))) longitude = list(map(float, form.cleaned_data.get('longitude').split(','))) ......... ......... return render(request, dashboard/dashboard.html, { 'form':form }) Now, I want my model to accept the coordinates as a CSV file too. I want an option in the UI to add a csv file (having multiple latitudes and longitudes) which then populates these two char fields (as comma separated values). Note that, my csv file won't have the country name. I shall be entering the country using the form UI only. Thus, in short, I need to accept some … -
Is there any problem uploading django project to github without secret key?
I have pushed my Django project to Github and after some time I got a mail from GitGuardian saying my secret key is exposed and to protect my repo. Is there any problem exposing the secret key in your GitHub repo? And how do I hide the secret key?angoenter image description here -
Refused to display 'https://www.youtube.com/watch?v=-s7e_Fy6NRU&t=1761s' in a frame because it set 'X-Frame-Options' to 'sameorigin'
Well I am trying to play youtube videos on my site but i am having an issue. <p style ='text-align:center'> #if i enter directly link into src code it works fine. <iframe width="420" height="315" src="https://www.youtube.com/embed/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe> #if i try to insert link from the data base it shows an error. <iframe width="640" height="390" src="{{all_videos.video_url}}" frameborder="0" allowfullscreen></iframe> </p> -
do postgresql has to be downloaded locally on venv or globally?
i'm a beginner to django and postgresql. currently i have the following directory structure for a django project python3.6 --> venv --> django_project .now , i want to install postgresql and psycopg2 and use it as a database . do i have to install it in venv with venv activated or install it in python3.6 folder. also how would the two installations above behave when i try to host the project on AWS ec2. i have installed postgresql in venv with venv activated and i'm getting the error 'NO module named psycopg2'. what did i do wrong? -
Request URL in Django error message does not correspond to the acual request url
I'm building an app with Django and Django-Rest-Framework. The frontend js application makes API calls to the backend. It works well when I test it using python manage.py ruserver but when i test it in a VM similar to my production environment, all API request get a 500 response. In the error message, the Request URL does not correspond to the actual request that was made. The actual request url looks like this: http://127.0.0.1:8080/api/account/login/ But the error message says it is something like this: http://127.0.0.1:8080/path/to/my/djoserapp/on/server/api/account/login/ The server is configured with nginx and daphne and the django version is 3.1 I don't know where to begin solving this and will greatly appreciate any help i could get. Thank you -
Javascript ID not showing reference to input text box - Django
{% extends 'halls/base.html' %} {% block content %} <div class="container"> <h2>Add Video to {{hall.title}}</h2> <form method="post"> {% csrf_token %} {% load widget_tweaks %} {% for field in form %} <div class="form-group {% if field.errors %} alert alert-danger {% endif %}"> {{ field.errors }} {{ field.label_tag }} {% render_field field class='form-control' %} </div> {% endfor %} <button type="submit" class="btn btn-primary"> Add</button> </form> <br> <h2>OR</h2> <form> {% for field in search_form %} <div class="form-group "> {{ field.errors }} {{ field.label_tag }} {% render_field field class='form-control' %} </div> {% endfor %} </form> <div id="search_results"></div> <script type="text/javascript"> var delayTimer; $("#id_search_term").keyup(function (){ clearTimeout(delayTimer); $('#search_results').text('Loadingggg'); }); </script> </div> {% endblock %} this is the HTML code. SO basically the whole idea here is when I inspect the search_form, it should give the id of the input box as "id_search_term". But when I inspect the box, it gives as id="id_search". I am not able to find a way to reference the input box with the ID in the script tag -
Django and Time Zones, database storing in UTC but writing regular python to try to make a daily report failing
I have this database that is tracking logins and logouts on a site (contact tracing woo hoo) when they login via the form or a qr code, it stamps the right date. Well sort of, the form works caues they can put in the date and time exactly. The QR code that time stamps is one hour off of local time (I am not sure why). This is fine, and inside the database all the dates are in UTC, which Django works translating the data back out when I display it somehow...so I am fine with this. The problem is I am writing a reporting python script not using django but contacting the same database. I want to cron job an email out at 11:55pm every night of the logins and log outs for the day, though by 11:55pm local time is like 5:55am UTC the next day, of which there is never any logins and logouts so the report is always empty. I lost the automagic of django in the interrigation of this database...so I am not sure what I can do to get the right data from the database. My report function is simple here: import sqlite3 def … -
I'm new at cron and scrapy. // cron not working in AWS. (it's fine in my local environment)
In AWS, source /home/ubuntu/envv/bin/activate && cd /srv/MyFirstCrawler/scraper && scrapy crawl blondieshop_spider my virtualenv is envv, my project is scrapy + django, project name is MyFirstCrawler, above cron is working when i type in command line. but not working in cron.. when i typed 'service cron status' Sep 21 05:01:01 ip-172-31-5-186 CRON[6473]: pam_unix(cron:session): session opened for user ubuntu by (uid=0) Sep 21 05:01:01 ip-172-31-5-186 CRON[6474]: (ubuntu) CMD (source /home/ubuntu/envv/bin/activate && cd /srv/MyFirstCrawler/scraper && scrapy crawl blondieshop_spider) Sep 21 05:01:01 ip-172-31-5-186 CRON[6473]: pam_unix(cron:session): session closed for user ubuntu i really can't figure out what's wrong. -
Django ImportError : cannot import name 'Manager' from partially initialized module '..\django\db\models\__init__.py'
Looked for the solutions and found that it may be the case of circular import. But I'm having simple imports, leaving no space for such a case. models.py from django.db import models forms.py from django import forms from FeedbackApp.models import StudentDetails views.py from django.shortcuts import render, redirect from django.urls import reverse from FeedbackApp.forms import LoginForm only simple model class having some fields, ModelForm from that model , and view for that form (myvenv) G:\projects\pycharmproj\Feedback>python manage.py runserver Traceback (most recent call last): File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\core\ma autoreload.check_errors(django.setup)() File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\utils\a fn(*args, **kwargs) File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\__init_ from django.urls import set_script_prefix File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\urls\__ from .base import ( File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\urls\ba from .exceptions import NoReverseMatch, Resolver404 File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\urls\ex from django.http import Http404 File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\http\__ from django.http.response import ( File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\http\re from django.core.serializers.json import DjangoJSONEncoder File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\core\se from django.core.serializers.base import SerializerDoesNotExist File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\core\se from django.db import models File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\db\mode from django.db.models.base import DEFERRED, Model # isort:skip File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\db\mode from django.db.models.options import Options File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\db\mode from django.db.models import AutoField, Manager, OrderWrt, UniqueConstraint ImportError: cannot import name 'Manager' from partially initialized module 'dja ackages\django\db\models\__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) … -
I want to authenticate user name and password in sanic using djnago tables
from django.contrib.auth import authenticate user = authenticate(username='john', password='john@122') if user is not None: # A backend authenticated the credentials else: # No backend authenticated the credentials Here I wan't to authenticate user name and password in sanic instead of django. Don't want to install django in sanic. but wan't to authenticate and create password and set to database. Is there any library to get my work done? or how can I create a normal password to djnag hashed password and authenticate? -
DoesNotExist on django
Could somebody help please? I try to play videos on my site but it sems I have some problem. I am a beginner in python and django. Here is what showed to me: (Thank you in further). ['DoesNotExist', 'MultipleObjectsReturned', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getstate', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'setstate', 'sizeof', 'str', 'subclasshook', 'weakref', '_check_column_name_clashes', '_check_constraints', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_indexes', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes', '_check_ordering', '_check_property_name_related_field_accessor_clashes', '_check_single_primary_key', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', '_state', 'check', 'clean', 'clean_fields', 'comment_set', 'date_error_message', 'datetime', 'delete', 'description', 'from_db', 'full_clean', 'get_deferred_fields', 'get_next_by_datetime', 'get_previous_by_datetime', 'id', 'objects', 'path', 'pk', 'prepare_database_save', 'refresh_from_db', 'save', 'save_base', 'serializable_value', 'title', 'unique_error_message', 'user', 'user_id', 'validate_unique'] XZZ4ROG1UHRoute_Montélimar.mp4 user signed in <QuerySet []> [21/Sep/2020 06:11:43] "GET /video/24 HTTP/1.1" 200 966 -
How to display Date in popup Modal in Django?
I want to display data in the popup, I have a list on products but when a user clicks on the product id then it should be open in popup according to that product id. here is my views.py file... def myview(request): datas=TestForm.objects.all template_name='test.html' context={'datas':datas} return render(request, template_name, context) def myview(request, id): display=TestForm.objects.get(pk=id) template_name='test.html' context={'display':display} return render(request, template_name, context) here is my test.html file... <button type="button" class="btn btn-primary" data-toggle="modal" data- target="#exampleModal"> {{data.product_id}} </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria- labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <tr> <td>{{data.name}}</td> <td>{{data.price}}</td> <td>{{data.category}}</td> </tr> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> Currently, it's displaying only the first product on click all products id's, Please let me know how it can display product data according to click product id. -
django app with ajax for processing dataframe
I am trying to show busy indicator image as soon as the user uploads an excel file . While the file process is done, I would like to replace the image with processed table. Problem: The ajax success block is not executing(alert message inside success block is not working) The uploaded data is converted to json but unable to convert back to dataframe for processing. The code that gets executed on upload button click in views.py def indicator(request): excel_file = request.FILES["excel_file"] uploaded_data = pd.read_excel(excel_file) df_json = uploaded_data.to_json() return render(request,'myapp/indicator.html',{'df':df_json}) indicator.html: <script> var dataframe = JSON.parse("{{df|escapejs}}"); var replace_data = function(data){ alert('successs') $('#success').append(data.list_of_jsonstuffs); $('#loading').remove() } $(document).ready(function(){ $.ajax({ url: '/processing/', type:'GET', dataType: 'json', data: JSON.stringify(dataframe), success: function(data){ alert('ajax done') replace_data(data) } }) }) </script> The function in view that triggers and does the processing. @csrf_exempt def processing_file(request): if request.is_ajax(): excel_file1 = json.dumps(request.GET) e1 = json.loads(excel_file1) input_df = pd.DataFrame.from_dict([e1]) print(input_df.shape) processed = gen.generate_output_columns(excel_file) output_validation = processed[const.OUTPUTCOLUMNSWITHVALIDATION] excel_data = output_validation.values.tolist() return excel_data The input_df is 1 by 2 however uploaded excel is 17 by 55. Somewhere in JSON Stringify and json loads the structure is getting changed but when I try with POST I was once able to succeed with processing but success block never … -
django file upload is not working in azure blob with new version
After updated the azure blob version, it won't install everything. It will install specific version of namespace in the blob. So i installed the following packages. azure-common==1.1.25 azure-core==1.8.1 azure-nspkg==3.0.2 azure-storage-blob==12.4.0 i'm not able to upload the blob. All the references in the SO and other platforms are for old versions. For new versions there is no reference. The error i'm getting is from azure.storage.blob import BlobPermissions, ContentSettings ImportError: cannot import name 'BlobPermissions' from 'azure.storage.blob' if i manually went to the path and removed the BlobPermissions from import compilation is happening. But upload is not happening, upload time i'm getting this error connection_string=self.connection_string) endpoint_suffix=self.endpoint_suffix) TypeError: __init__() got an unexpected keyword argument 'token_credential' Can anyone help me with proper doc for django azure upload with new version. The references i got in SO is manual upload way. Some reference i got in SO: Upload and Delete Azure Storage Blob using azure-storage-blob or azure-storage ImportError: cannot import name 'BlobService' when using Azure Backend -
ImportError running multiple test modules w/ manage.py test
Presently I'm testing only one app for which I have nested a package dedicated to separating my tests (test_models.py, test_forms.py, etc.). When I created the test_forms.py module and attempted to run python manage.py test, the following error is raised: ImportError: Failed to import test module: photos.test.test_forms Traceback (most recent call last): File "C:\..\..\..\..\..\Python\Python37\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\..\..\..\..\..\Python\Python37\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "C:\..\..\..\..\..\django_photo_app\photos\test\test_forms.py", line 2,in <module> from ..forms import PhotoForm File "C:\..\..\..\..\..\django_photo_app\photos\form.py", line 8, in <module> from ..models import Photo ValueError: attempted relative import beyond top-level package The import triggering this error is: from ..forms import PhotoForm When I remove any reference to that form in the test module the overall tests run fine. Prior to creating test_forms.py , there was only the test_models.py module and there was no problem running the tests. Why is it that Django raises an ImportError and then a subsequent ValueError in this manner when running python manage.py test? -
trying to submit a java form to an API
here is my js code that am trying to run , in this js function that sends an email to this API '/emails' the form takes recipients , subject and body as inputs .. i have no idea what went wrong because the code makes sense to me , someone told me this issue is due to the usage of multiple languages but am not using any (am on the latest version of django python and VScode) : function sendEmail() { const recipients = document.querySelector('#compose-recipients').value; const subject = document.querySelector('#compose-subject').value; const body = document.querySelector('#compose-body').value; console.log(recipients); fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipients, subject: subject, body: body }) }) .then(response => response.json()) .then(result => { if ("message" in result) { // The email was sent successfully! load_mailbox('sent'); } if ("error" in result) { // There was an error in sending the email // Display the error next to the "To:" document.querySelector('#to-text-error-message').innerHTML = result['error'] } console.log(result); console.log("message" in result); console.log("error" in result); }) .catch(error => { // we hope this code is never executed, but who knows? console.log(error); }); return false; } and here is my error : Exception happened during processing of request from ('127.0.0.1', 54200) Traceback (most recent call last): … -
How can I get Django to ignore an old migration it thinks hasn't been applied?
Somehow, our test DB's migration history looks like this: ... [X] 0034_timestamp_fields [X] 0035_password_history [ ] 0036_login_lockout (2 squashed migrations) [X] 0037_force_password_change ... We're now up to migration 67; this is ancient history. Now there is a new migration, 68, that I'd like to apply. If I try to migrate right now, I get a "relation already exists" error on migration 36. I tried specifically migrating up to 67 with --fake, but got "No migrations to apply." So.. how can convince Django that 36 is already applied? Or just get it to ignore it for now and apply 68 without worrying about it? This is Django 1.11.26. -
How to resolve Undefined Table error in Django
I am new to django , was following a tutorial on youtube, on how to create custom user model. This is my model from django.db import models #from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser , BaseUserManager # Create your models here. class AccountManager(BaseUserManager): def create_user(self, email,firstName,lastName,m_phone): if not email: raise ValueError('Email Id is a required Field') if not firstName: raise ValueError('First name is a required Field') if not lastName: raise ValueError('Last name is a required Field') if not m_phone: raise ValueError('Mobile Ph. no is a required Field') user = self.model(email=self.normalize_email(email), firstName=firstName, lastName = lastName, m_phone = m_phone) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email,firstName,lastName,m_phone,password): user = self.create_user(email=self.normalize_email(email), firstName=firstName, lastName = lastName, m_phone = m_phone, password = password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(unique=True) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) m_phone = models.CharField(max_length=50) l_phone = models.CharField(max_length=50) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['firstname','lastname','m_phone'] objects = AccountManager() def __str__(self): return self.firstName def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self,app_label): return True # class Profile(models.Model): # user = models.OneToOneField(Account, on_delete = models.CASCADE) # profilePicture … -
How can I deserialize multiple files and form data in a single request using Django Rest Framework?
I would like to desearialize a form with some basic form data + one or more uploaded files. If I send the following request (generated as Python Requests code using Postman) import requests url = "http://127.0.0.1:8000/forms/test/" payload = { 'customer_id': '123456789', 'customer_name': 'Billy Bob'} files = [ ('files', open('/C:/tmp/aaaaa.csv','rb')), ('files', open('/C:/tmp/bbbbb.csv','rb')) ] headers= {} response = requests.request("POST", url, headers=headers, data = payload, files = files) print(response.text.encode('utf8')) The code returns the following response (I hoped it would save the file instead). { "files": [ "This field is required." ] } Models class Mtfar(models.Model): date = models.DateTimeField(auto_now_add=True) customer_id = models.IntegerField() customer_name = models.CharField(max_length=254) class MtfarFile(models.Model): file = models.FileField(blank=False, null=False) mtfar = models.ForeignKey(Mtfar, related_name='files', on_delete=models.CASCADE) Serializers class MtfarFileSerializer(serializers.ModelSerializer): class Meta: model = MtfarFile fields = ['file'] class MtfarSerializer(serializers.ModelSerializer): files = MtfarFileSerializer(many=True) class Meta: model = Mtfar fields = ['customer_ptid', 'customer_name', 'files'] View @api_view(['POST']) @parser_classes([MultiPartParser]) def post_generic_form(request): data = request.data filelist = [] for f in request.FILES.getlist('files'): filelist.append({ 'file': f }) data.setlist('files', filelist) serializer = MtfarSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Use pgadmin4 to open existing Django project DB
I have deployed a Django project in ptyhon venv in CentOS 8. Evertything wokrking fine. Now I'd like to install pgadmin4 to check detail data inside PostreSQL. After installation by official site instruction, pdadmin page seems working. I can also login as default user (postgres) But there's no any server showing up in left menu. Maybe I missed some steps? Pls kindly help, thx! -
Twilio outbound call hold disconnecting callee
I am implementing hold function in Twilio. Whenever I call the hold function, the callee is getting disconnected. The code below only applies to the caller, not the callee. if call_sid: client = Client(self.account_sid, self.auth_token) twiml_string = """ <Response> <Enqueue>xx</Enqueue> </Response> """ client.calls(call_sid).update(method="POST", twiml=twiml_string) -
There was an error in the distribution of the DjangoProject in PythonAnywhere - ModuleNotFoundError: No module named 'mysite'
There is an error in distribution / pythonanywhere , django_project/ I looked up all the related Stack Overflow articles! but i didn't solve this problem please let me know please let me know please let me know please let me know please let me know 2020-09-21 02:01:37,406: Error running WSGI application 2020-09-21 02:01:37,407: ModuleNotFoundError: No module named 'mysite' 2020-09-21 02:01:37,407: File "/var/www/emoclew_pythonanywhere_com_wsgi.py", line 12, in <module> 2020-09-21 02:01:37,407: application = StaticFilesHandler(get_wsgi_application()) 2020-09-21 02:01:37,407: 2020-09-21 02:01:37,407: File "/home/emoclew/covid19_survey/myvenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-09-21 02:01:37,407: django.setup(set_prefix=False) 2020-09-21 02:01:37,408: 2020-09-21 02:01:37,408: File "/home/emoclew/covid19_survey/myvenv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup 2020-09-21 02:01:37,408: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2020-09-21 02:01:37,408: 2020-09-21 02:01:37,408: File "/home/emoclew/covid19_survey/myvenv/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ 2020-09-21 02:01:37,408: self._setup(name) 2020-09-21 02:01:37,409: 2020-09-21 02:01:37,409: File "/home/emoclew/covid19_survey/myvenv/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup 2020-09-21 02:01:37,409: self._wrapped = Settings(settings_module) 2020-09-21 02:01:37,409: 2020-09-21 02:01:37,409: File "/home/emoclew/covid19_survey/myvenv/lib/python3.8/site-packages/django/conf/__init__.py", line 177, in __init__ 2020-09-21 02:01:37,409: mod = importlib.import_module(self.SETTINGS_MODULE) it is my project tree (myvenv) 02:06 ~/covid19_survey (master)$ tree . ├── db.sqlite3 ├── firstProject │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── ido │ ├── __init__.py │ ├── __pycache__ │ │ … -
Media files not serving Django production
I built an app using Django with PostgreSQL as a database. After I finished it, I decided to deploy it on Heroku. Their documentation was too complex for me to understand, so I went to this post on Medium and did what they said. A Server Error (500) came in my application, and I found out that I removed the line STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' it worked properly when I ran python manage.py runserver on my local machine, but it doesn't serve the media files. After I pushed it to Heroku, it still shows a Server Error (500) there. I am showing few parts of my code. Could you please tell me how I could serve the media files properly and why the server error is coming only in the Heroku run app? If you need any code other than whatt I have given here, please inform me in the comments. I know that you can't serve media files when DEBUG = False and that you should use Nginx, but please tell me where I can find a good guide for Nginx deployment on Heruko. Thanks in advance. settings.py """ Django settings for btre project. Generated by 'django-admin startproject' using Django …