Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send dynamic ID info from django class-based view to formset
I have a class-based view that renders a formset based on the project selected. Each project has a unique project_id. I get a 404 error caused by Line 14(below) in views.py if don't hard-code the project_id (ie '4') to replace 'None'.Also,the formset doesn't load if i don't hard-code the project_id in Line 4 under forms.py. Since the project_id needs to be passed automatically,how can i get it updated and passed into the formset? Thanks. I tried this: views.py class ReqView(CreateView): template_name = "req_view.html" model = ProjectBudgetReq form_class = ReqForm def get_form_kwargs(self,*args, **kwargs): form_kwargs = super(ReqView, self).get_form_kwargs(*args, **kwargs) form_kwargs['project_id'] = self.kwargs.get('project_id') print("get_form_kwargs:",form_kwargs) return form_kwargs def get_context_data(self,**kwargs): project_id = kwargs.pop('project_id',None)#Line 14 404 Error project = get_object_or_404(ProjectDetails,id=project_id) formset = ReqFormSet(instance=project) context = super(ReqView, self).get_context_data(**kwargs) context['project'] = project context['formset'] = formset return context def get_context_kwargs(self,**kwargs): context_kwargs = super(ReqView,self).get_context_kwargs(*args,**kwargs) context_kwargs['project_id'] = self.kwargs.get('project_id') return context_kwargs forms.py class CreateReqForm(forms.ModelForm): def __init__(self,*args,**kwargs): project_id = kwargs.pop('project_id',None) #Line 4 Formset not rendered super(CreateReqForm,self).__init__(*args,**kwargs) self.fields['proj_name'].queryset = ProjDesc.objects.filter(id=project_id) self.fields['budget_desc'].queryset = ProjBudget.objects.filter(proj_name_id=project_id) class Meta: model = ProjBudgetReq fields = '__all__' BudgetReqFormSet = inlineformset_factory(ProjDesc, ProjBudgetReq, form=CreateReqForm, fields='__all__',extra=2) Issues: views.py #Line 14: 404 Error since it returns 'None' forms.py #Line 4: Formset does not render, since it's 'None' -
Using Python, I want to check the data that is Type_Of_Wallet is already exists in my MySQL database table or not?
I am new to Django where I designed an application where I created a form in templates and used a database that is in localhost/PHPMyAdmin. Now when the user enters the data in given fields and presses the submit button, it should check in the database whether the given data is present in the database or not. But my code is not working. `views.py import mysql.connector from django.http import HttpResponse from django.template import loader from django.views.decorators.csrf import csrf_exempt @csrf_exempt def index(request): if request.method == 'POST': Type_Of_Wallet = request.POST.get('Type_Of_Wallet') BLE_MAC_ID = request.POST.get('BLE_MAC_ID') BAR_CODE = request.POST.get('BAR_CODE') Version = request.POST.get('Version') context = { 'Type_Of_Wallet': Type_Of_Wallet, 'BLE_MAC_ID': BLE_MAC_ID, 'BAR_CODE': BAR_CODE, 'Version': Version, } template = loader.get_template('valid_form/showdata.html') return HttpResponse(template.render(context, request)) else: template = loader.get_template('valid_form/index.html') return HttpResponse(template.render()) mydb=mysql.connector.connect( host = 'localhost', user = 'rajat', passwd = 'rajat', database = 'MyForum' ) mycursor=mydb.cursor() print('Enter Type_Of_Wallet:') Type_Of_Wallet=Input(context) CheckType_Of_Wallet=mycursor.execute( 'SELECT Type_Of_Wallet FROM form_simpleform WHERE Type_Of_Wallet=%(Type_Of_Wallet)s', {'Type_Of_Wallet':Type_Of_Wallet}) if CheckType_Of_Wallet !=0: print('Type_Of_Wallet does not exit') else: print('Its Available') ` index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Validation</title> </head> <body> <h2>Validation</h2> <form method="post" action="/getdata/"> <table> <tr> <td>Enter Wallet Type:</td> <td><input type="text" name="Type_Of_Wallet"/></td> </tr> <tr> <td>Enter your BLE_MAC_ID:</td> <td><input type="varchar" name="BLE_MAC_ID"/></td> </tr> <tr> <td>Enter your Bar Code:</td> <td><input type="varchar" name="BAR_CODE"/></td> </tr> <tr> … -
Unsupported mimetype: application/vnd.openxmlformats-officedocument.wordprocessingml.document
I am using preview-generator to make a pdf from docx file in Django. The code is working properly in my local machine but the same deployment is not working on the server which is ubuntu 18.04. I am having Unsupported mimetype: application/vnd.openxmlformats-officedocument.wordprocessingml.document error. I have researched about it and found libre office needs to be installed in the server and its already present on my server. can you please suggest what I need to do or how I can define path of libre office. I am using Django and once I use the shell the file generated properly but in the the web its not working. This is the error on terminal. gunicorn[29453]: Builder is missing a dependency: this builder requires inkscape to be available gunicorn[29453]: Builder is missing a dependency: this builder requires convert to be available Builder is missing a dependency: this builder requires qpdf to be available Builder is missing a dependency: this builder Builder is missing a dependency: this builder requires libreoffice to be available -
How to convert this raw query to Django ORM query set
task_data_calldetail.objects.raw('SELECT id from `task_router_calldetail` where direction = "inbound" AND YEARWEEK(`time_stamp`, 1) = YEARWEEK( "' + today_date + '" - INTERVAL 1 WEEK, 1)') -
Slug generator don't generate slug for tablecontent
I don't know why the slug generator does not generate a slug for the items in my table. It works perfectly if i save the data with the .save() command. But it does not work with a pipeline wich does not use django related commands. I use a Postgresql database Model: class WhiskyContent(models.Model): products = models.CharField(max_length=250) price = models.FloatField(default=20) date = models.CharField(max_length=250) picture = models.CharField(max_length=250) site = models.CharField(max_length=250) product_link = models.CharField(max_length=250) shipping = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True, blank=True, null=True) def get_absolute_url(self): return "/products/{slug}/".format(slug=self.slug) def __str__(self): return self.products objects = models.Manager def product_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(product_pre_save_receiver, sender=WhiskyContent) Pipeline into database: import psycopg2 import sys import logging class Frankbrauer360Pipeline(object): def __init__(self): self.create_connection() def create_connection(self,): hostname = 'localhost' username = 'postgres' password = 'Whisky#123!' database = 'Items' x = 1 try: if (x == 1): self.connection = psycopg2.connect(host=hostname, user=username, password=password, dbname=database) except psycopg2.DatabaseError as e: logging.error(e) sys.exit() finally: logging.info('Connection opened successfully.') def process_item(self, item, spider): cursor = self.connection.cursor() cursor.execute(''' insert into homepage_whiskycontent(products, price, picture, site, product_link, shipping, date) values (%s, %s, %s, %s, %s, %s, %s); ''', [ item['products'], item['price'], item['picture'], item['site'], item['product_link'], item['shipping'], item['date'], # item["slug"], ]) self.connection.commit() return item def close_spider(self, spider): self.connection.close() … -
Average duplicates from specific columns in QuerySet in Django
I have a Django Model I am using that looks like this: class FinancialAid(models.Model): RECEIVED_EVERY = (("J", "Jours"), ("S", "Semaines"), ("M", "Mois")) ID = models.AutoField(primary_key=True) Name = models.CharField(max_length=100, null=True, blank=True) Value = models.IntegerField(null=True, blank=True, default=-1) ReceivedEvery = models.CharField(max_length=15, null=True, blank=True, choices=RECEIVED_EVERY) Exchange = models.ForeignKey('Exchange', on_delete=models.CASCADE) I am able to access the information I want but I have an issue in that I often have duplicates within my QuerySet over the Name and ReceivedEvery columns but not always on the Value and never on the Exchange. Say I have the following QuerySet expanded out: financial_aid_qs = [ (ID=1, Name="Aid1", Value=100, ReceivedEvery="M", Exchange=Exchange.objects.get(pk=1)), (ID=2, Name="Aid2", Value=200, ReceivedEvery="S", Exchange=Exchange.objects.get(pk=2)), (ID=3, Name="Aid1", Value=150, ReceivedEvery="M", Exchange=Exchange.objects.get(pk=3)), (ID=4, Name="Aid3", Value=100, ReceivedEvery="M", Exchange=Exchange.objects.get(pk=4)) ] As you can see, I have the same Name and ReceivedEvery for indexes 1 and 3. What I would like to do is get a QuerySet (or ValuesQuerySet although I seem to recall this was removed) that will contain all the different FinancialAid objects in terms of Name and average out the Value of FinancialAid objects that have the same Name. Ideally it would take into account the fact that ReceivedEvery can differ even though the Name is the same (This is all … -
Making generated emails 'outlook friendly'
I'm using Summernote as a WYSIWYG editor for users to create emails and send them within a django application. As it stands it works perfectly well in most clients which handle HTML in any normal way, however when the mail is sent to outlook it goes awry. Essentially Summernote is using style="float: x width: x" which outlook is simply ignoring, then rendering the image that should be floated right or left wherever it has been placed and at full size. Does anyone know of a package that can parse the generated summernote HTML and make it Outlook friendly before I go ahead and start writing up a whole lot of string replacements in the generated HTML? -
How to import the data from a data dump (SqLite3) into django?
I have a data dump file(.sql) containing certain data, I would like to import it to my database(currently Sqlite3 but thinking about changing to MySQL) in order to use it in my test website. Also, I need to know if it's possible to add the models too automatically, I presume it needs to be added manually, but any how, if there is any way to solve it, please suggest it. -
Search Marker Leaflet Map
I am working on an application with Django. There in this application, I am first using Django to create a database with points and extract a JSON file (It is called "markers.json"). Then, using this JSON file, I am creating markers on a map with Leaflet. When I finished entering all the points to the database they will be around 5000 thousand. So, I decided that it is a good idea to be able to search this markers with an input tag and a search button. I enter the "site_name" as input and when I click the "search" button the related marker should popup. However, always the same marker pops up and I don't know where I am doing wrong. Could you please help me on that? HTML PART <input type="text" id="mast_find" name="mastName" placeholder="Search or masts..."> <button type="submit" id="mast_button">Search</button> JAVASCRIPT PART var streets = L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>', subdomains: ['a', 'b', 'c'] }), esri = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community' }), topo = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', { maxZoom: 17, attribution: 'Map data: &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, <a href="http://viewfinderpanoramas.org">SRTM</a> | Map style: … -
Annotating average and count of latest instances created by one author
So, I've got that piece of code: def generate_annotated_applications(queryset): return queryset.annotate( avg_rating=Avg( 'application_ratings__rate', distinct=True, filter=Q(application_ratings__job_process_step__job_process__job=F('job')), ), ).annotate( num_ratings=Count( 'application_ratings', distinct=True, filter=Q(application_ratings__job_process_step__job_process__job=F('job')), ) In general it works well, but the problem is that avg_rating is counted from every existing application_ratings. What I need to achieve is to count average taking only latest ratings with unique author. There are many instances of application_rating with different rate and author. Same thing is with num_ratings - I need to count number of latest ratings with unique author field. -
how to add multiple dict inside a list in python 3 with same key?
how to add multiple dict in python which is inside a list something like in this i need to add the amount from same person so where email id is same i want to add the amount. how can we do this i tried merging dic but i am getting duplicate responce. { "payment_type_details": [ { "email": "revati.sukumar@gmail.com", "first_name": "Revati ", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 200000.0 }, { "email": "revati.sukumar@gmail.com", "first_name": "Revati ", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 10049.99 }, { "email": "pradhan.sangita123@gmail.com", "first_name": "Sangita ", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 128388.99 }, { "email": "pradhan.sangita123@gmail.com", "first_name": "Sangita", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 100250.85 }, ] } -
Django - Heavy database usage
Let's say you are building a SAAS application system in which every user will use the database heavily, for example, a hospital management system. Should you have separate databases for each user? And how do you implement this in Django? -
Object of type 'bytes' is not JSON serializable while calling an api
I'm trying to save a form which involves an API call but its throwing me an error that Object of type 'bytes' is not JSON serializable. when I call data=json.dump(dump) it throws the following error def getAttributes(self, jsonObj=False): attributes = vars(self) data = {var: value for var, value in attributes.items() if not var.startswith('_')} print(data, "data") if jsonObj: import json data = json.dumps(data) return data p.s.: In print data statement it is returning me a dict. -
Python: Passing an object instance from one function to another?
I'm having trouble with passing a value from one script to another, trying to take it a step at a time but the big picture would be to print the value obj1.get_predval to my Django view and wait for the users' input. active_learner.obj1.get_predval in my beta.py script doesn't work, it just prints out the initial value which makes sense because it's not running the main.py but I'm not sure how I'd pass the value of obj1.set_predval(machine_prediction) from main.py. It properly outputs the obj1.get_predval in the main.py script. I'm assuming I have a fundamental misunderstanding, for now, all I'm trying to return is the value of obj1.get_predval in function beta.py, when it gets to the line return value and wait for user input then continue. main.py script below obj1 = MachinePred() def main(): model = load_model('model_new.h5') DATAFILE = "c_user_model_data100000.csv" dataset = loadtxt(DATAFILE, delimiter=",") X_pool, Y = dataset[:, 0:5], dataset[:, 5:] sc_x, sc_y = StandardScaler(), StandardScaler() X_pool, Y = sc_x.fit_transform(X_pool), sc_y.fit_transform(Y) learner = ActiveLearner( estimator = model, query_strategy = uncertainty_sampling ) for i in range(3): query_idx, query_inst = learner.query(X_pool) print("The machine queried:\n{}\nat index {}".format( sc_x.inverse_transform(query_inst), query_idx ) ) machine_prediction = learner.predict(X_pool[query_idx]) obj1.set_predval(machine_prediction) print("predvalue:", (obj1.get_predval())) ratings = [] cc_factor = ["delay", "speed", "missing_words", … -
using django permissions.IsAuthenticatedOrReadOnly with token authentication
I have this Django API view that I want to allow authorized and unauthorized users access it, I have set Django token-authentication as the default authentication class, however, whenever I try to access the view as unauthenticated user,I get error Unauthorized: which is weird coz am doinf a get request in the view my code is here @api_view(['GET']) @permission_classes([permissions.IsAuthenticatedOrReadOnly]) def all_Search(request): print(request.headers) src = request.GET.get('q') my settings for rest framework is REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ] } is there a way to work around this? will appreciate any help, thanks -
How to suppress warning message in django unit test
I'm trying to write some unit test cases for django (Restful API backend), While executing, I'm seeing below (403 Forbidden), which is expected, since the test is to hit a 403 endpoint. Is there a way to suppress that. I have already tried python -W error but no luck. (venv) python manage.py test System check identified no issues (0 silenced). [16/Nov/2019 11:15:26] WARNING [http://log.py:228 ] Forbidden: /api/test_enter ------------------------------------------------------------------------------ Ran 1 test in 0.021s OK How to suppress warning message in #python #django #unittest. Any thoughts would be very very helpful. Thanks. a fellow developer. :) -
Create session but has error 'Confirm form submission'
so i try to make a login function with session so if people logout , they cannot back to the page before but everytime i try to back (that has session or not) it always give me an error Confirm Form Resubmission This webpage requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed. i dont know wheres the problem , but here's the code def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') guest = User.objects.get(username=username) role = guest.role user = authenticate(username=username, password=password) if user is not None: if role == 'Business Analyst': login(request, user) request.session['username'] = username return render(request,'index.html',{"username":username}) #return redirect('/home') elif role == 'Admin': login(request, user) request.session['username'] = username return redirect('/manageuser/') elif role == 'Manager': login(request, user) request.session['username'] = username return redirect('/approvallist/') elif role == 'Segment Manager': login(request, user) request.session['username'] = username return redirect('/approvallist/') else: messages.error(request, "Invalid username or password!") else: messages.error(request, "Invalid username or password!") form = AuthenticationForm() return render(request,"login.html",{"form":form}) #page when you success login def index_view(request): if request.session.has_key('username'): username = request.session['username'] return render(request,'index.html',{"username":username}) else: return redirect('/') … -
Getting validation error field can not be null, even if null=True in model
I've a foreign key in my model and this field can be null. status = models.ForeignKey(Status, on_delete=models.SET_NULL, null=True, blank=True, related_name="status") When i send a request with this field as null i get validation error saying [ { "status": [ "This field may not be null." ] } ] Even though I have set null=True I'm not sure why it's throwing me that validation error? Can anyone please help me with this. -
How to create a validation check that ensures the right-formatted directory path is stored and if it contains a file extension in Django?
I have a template that allows a user to store a pathname of a directory in my model (the directory should be available/exist in the server for a website or seen in a local machine). Before saving the path to the model, I need to ensure whether if the right format for the directory is being saved. Example: var/www/html/media/product or C:\Users\Danny\Desktop\folder. There shouldn't be any irregular strings, expressions or invalid format seen in the path like var/www/html/media/product\pic/... Moreover, I want to stop users if they want to save a specific directory path that contains a file extension. Example: var/www/html/media/product/file.<'file extension'> ('file.png', top.txt', 'random.jpg', etc...) How can this be done in my views.py code? Currently, this is what I did so far: views.py: def dashboard(request): if request.method == 'POST': form = PathForm(request.POST) if form.is_valid(): path = form.cleaned_data['path'] #CharField that stores the path name in model from form. #Two checks required. Need to see if it is a valid directory path format or if the path contains a general path directory. Not specific files (like images, text, csv file) should be seen in the path. #if file path contains a file extension at end. This is tedious since I need include all … -
Django: Get last record by ID [many-to-one relationship]
I'm trying to get the last record in one table connected to another one using many-to-one relationship in django models. Here's my django models: class DataCollecttion(models.Model): default_name = models.CharField(max_length=100) class NameHistory(models.Model): old_name = models.CharField(max_length=100) collection_data = models.ForeignKey(DataCollection, on_delete=models.CASCADE, null=True) Here I created a sample data for DataCollection table: And here's the sample data for NameHistory table: What I want here is to filter or get the last record in NameHistory in each collection_data_id (the records inside the red rectangle) and display it in my views. So in short I want to get these lines and how can I do it in ORM Query: sample3 test2 data1 -
A mistake on django "'django.forms.models' has no attribute 'Model'
[whats appears on the terminal ][1] i cant solve this error when i write the comand python manage.py makemigrations polls [1]: https://i.stack.imgur.com/brkOJ.png python manage.py makemigrations polls -
How do i host a django website via filezilla?
I am trying to host a django website via filezilla using a2hosting server.Steps i followed are given below 1. Uploaded my website from local host to remote site via filezilla. 2. Install all django requirements via putty. 3. Add allowed host as "mydomain". 4.Run server using the command "python3 manage.py runserver myip:8000 now i can access my website.But the problem is after stop running the server.It shows "404 Not Found Nginx/1.10.3 (Ubuntu)" error message. How do i resolve this issue? -
Static Files not saving on S3 bucket using cookiecutter-django
I'm trying to deploy my project on Heroku. I ran heroku run python3 manage.py collectstatic after deploying it. I have this on config/base.py STATIC_ROOT = str(ROOT_DIR("staticfiles")) STATIC_URL = "/static/" STATICFILES_DIRS = [str(APPS_DIR.path("static"))] STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] This is on the config/production.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS += ["storages"] # noqa F405 AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME") AWS_QUERYSTRING_AUTH = False _AWS_EXPIRY = 60 * 60 * 24 * 7 AWS_S3_OBJECT_PARAMETERS = { "CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate" } AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = env("DJANGO_AWS_S3_REGION_NAME", default=None) STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" from storages.backends.s3boto3 import S3Boto3Storage # noqa E402 class StaticRootS3Boto3Storage(S3Boto3Storage): location = "static" default_acl = "public-read" class MediaRootS3Boto3Storage(S3Boto3Storage): location = "media" file_overwrite = False DEFAULT_FILE_STORAGE = "config.settings.production.MediaRootS3Boto3Storage" MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/media/" These are my heroku env variables I generated this using cookiecutter-django. Everything works fine on my localhost but when I deploy it to heroku, it doesn't save the static files. -
I keep getting below error when starting django server. Below is a full trace of the error. Please let me know what could fix this issue
(env) C:\Users\LENOVO\Desktop\SD\backend>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\channels\apps.py", line 6, in <module> import daphne.server File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\daphne\server.py", line 18, in asyncioreactor.install() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\asyncioreactor.py", line 320, in install reactor = AsyncioSelectorReactor(eventloop) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\asyncioreactor.py", line 69, in init super().init() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\base.py", line 571, in init self.installWaker() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\posixbase.py", line 286, in installWaker self.addReader(self.waker) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\asyncioreactor.py", line 151, in addReader self._asyncioEventloop.add_reader(fd, … -
Define a path for a file in python script on heroku
I have a text file in a folder inside of my app in a django project. I am using Heroku bash to run a script that reads the text file and populate the data into the database. on my machine I have defined this: file=open(os.path.join(settings.BASE_DIR,'myappfolder/folder_name/data.txt'),'r',encoding="utf8") It works on my local but when I run it in the heroku using bash it replies: FileNotFoundError: [Errno 2] No such file or directory: '/app/myappfolder\\folder_name\\data.txt' Could tell me how can I modify in a way that it works on my heroku app and also my local machine?