Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error encountered while using py decouple
A string is returned in the settings.py file but SPOTIPY_REDIRECT_URI goes unnoticed. .env SPOTIPY_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxx SPOTIPY_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxx SPOTIPY_REDIRECT_URI=http://localhost/ settings.py SPOTIPY_CLIENT_ID= config('SPOTIPY_CLIENT_ID') SPOTIPY_CLIENT_SECRET= config('SPOTIPY_CLIENT_SECRET') SPOTIPY_REDIRECT_URI= config('SPOTIPY_REDIRECT_URI') ERROR: decouple.UndefinedValueError: SPOTIPY_REDIRECT_URI not found. Declare it as envvar or define a default value. -
Run Django commands on Elastic Beanstalk SSH -> Missing environment variables
So this has been a long-running problem for me and I'd love to fix it - I also think it will help a lot of others. I'd love to run Django commands after ssh'ing on my Elastic Beanstalk EC2 instance. E. g. python manage.py dumpdata The reason why this is not possible are the missing environment variables. They are present when the server boots up but are unset as soon as the server is running (EB will create a virtual env within the EC2 and delete the variables from there). I've recently figured out that there is a prebuilt script to retrieve the env variables on the EC2 instances: /opt/elasticbeanstalk/bin/get-config environment This will return a stringified object like this: {"AWS_STATIC_ASSETS_SECRET_ACCESS_KEY":"xxx-xxx-xxx","DJANGO_KEY":"xxx-xxx-xxx","DJANGO_SETTINGS_MODULE":"xx.xx.xx","PYTHONPATH":"/var/app/venv/staging-LQM1lest/bin","RDS_DB_NAME":"xxxxxxx":"xxxxxx","RDS_PASSWORD":"xxxxxx"} This is where I'm stuck currently. I think need would need a script, that takes this object parses it and sets the key / values as environment variables. I would need to be able to run this script from the ec2 instance. Or a command to execute from the .ebextensions that would get the variables and sets them. Am I absolutely unsure how to proceed at this point? Am I overlooking something obvious here? Is there someone who has written … -
Django Saving files in database with username
I am getting multiple file entries from the user. And I save all of these in the database in one go. But I don't want these files to get mixed up when multiple users use the system. Therefore, when I save each file, I want the username that uploaded that file to be saved in the database. Models.py class users(models.Model): person_name = models.CharField(max_length=50, null=False, blank=True, verbose_name="name") person_surname = models.CharField(max_length=50, null=False, blank=True, verbose_name="surname") email = models.CharField(max_length=100, null=False, blank=True, verbose_name='email') user_name = models.CharField(max_length=30, null=False, blank=True, verbose_name="username") user_password = models.CharField(max_length=35, null=False, blank=True, verbose_name="password") class files(models.Model): owner= models.OneToOneField(User, unique=True, related_name="owner", on_delete=models.CASCADE) description = models.CharField(max_length=255, blank=True) excelFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) wordFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) txtEmailFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) txtContentFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) attachmentFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) forms.py class DocumentForm(forms.ModelForm): class Meta: model = files fields = ('description', 'excelFile', 'wordFile', 'txtEmailFile', 'txtContentFile', 'attachmentFile') views.py ( only one func ): @login_required(login_url="login") def sendmail(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('sendmail') else: form = DocumentForm() return render(request, 'sendmail.html') I am not adding the html file here because I received multiple file entries from the user and the html file is mixed. Database ( MySql Workbench ): How can I do it ? -
Django Rest Framework Error: JSON parse error - Expecting ':' delimiter: line 4 column 21 (char 103)
I want to save a new user via POST request using the @api_view decorator in DRF but got the following error : { "detail": "JSON parse error - Expecting ':' delimiter: line 4 column 21 (char 103)" } models.py code: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.conf import settings class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'users/default.jpg', upload_to = 'users/profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, **kwargs): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) views.py code: from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.http import HttpResponse, JsonResponse from rest_framework.parsers import JSONParser from .serializers import UserSerializer from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status @api_view(['GET', 'POST']) def user_list(request): if request.method == 'GET': users = User.objects.all().order_by('id') serializer = UserSerializer(users, many = True) return Response(serializer.data) elif request.method == 'POST': serializer = UserSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_created) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) serializers.py code: from rest_framework import serializer from django.contrib.auth.models import User from .models import Profile from django.contrib.auth.hashers import make_password class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only = True) … -
NameError: name 'MyModel' is not defined. Why?
I dont really understand what is happening in my code but it says the my Book model is undefined. Below is my code: This is my forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class BooksForm(forms.ModelForm): class Meta: model = Books fields=('book_id',) my models.py class Books(models.Model): book_id = models.CharField(primary_key=True, max_length=50) book_title = models.CharField(max_length = 100) book_author_id = models.ForeignKey(Author, on_delete=models.CASCADE) book_cover = models.ImageField(upload_to='media/') book_file = models.FileField(upload_to='media/') book_year = models.DateField(default = timezone.now) book_tags = models.CharField(max_length = 100) book_summary = models.CharField(max_length = 100) book_category_no = models.ForeignKey(Category, on_delete=models.CASCADE) book_info = models.CharField(max_length = 100, default="") is_bookmarked = models.BooleanField() is_downloaded = models.BooleanField() is_read = models.BooleanField() class Meta: db_table = "Books" -
How to make an API using DRF to accept and verify a JWT?
I need to make an API which can take in a JWT token and an ID parameter and create multiple endpoints which will serve data( like '../api/contact/', '../api/qualifications/', etc). I do not understand how to take in the JWT and the ID parameter. Should I make another API endpoint where the user can POST the data but how do I save it in Django and design a way to serve the other endpoints? This is the first time I'm making any sort of APIs. -
Djongo: objects.all() on model having ArrayReferenceField
I'm using Djongo(a mongo database connector for django). Model.objects.all() causes issues on a model containing ArrayReferenceField (documentation: https://www.djongomapper.com/using-django-with-mongodb-array-reference-field/). The code works as expected when I remove all the ArrayReferenceFields from the model In the code below, Projects.objects.all() gives the error: from_db_value() missing 1 required positional argument: 'context'. However, printing Projects.objects gives database_models.Projects.objects irrespective of whether the model contains an entry. So the error lies in the all() method. Any one of the following will help: Syntax to fetch all records Modification of model such that it supports all functionalities of ArrayReferenceField Any other workaround so I can store and fetch the values Traceback: Traceback (most recent call last): . . . File "Path_to_file_having_method\project.py", line 85, in fetch_projects_of_user print(Projects.objects.all()) File "path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 252, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 276, in __iter__ self._fetch_all() File "path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 74, in __iter__ for row in compiler.results_iter(results): File "\env\lib\site-packages\django\db\models\sql\compiler.py", line 1095, in apply_converters value = converter(value, expression, connection) TypeError: from_db_value() missing 1 required positional argument: 'context' My model: from .users import Users from djongo import models class Projects(models.Model): project_id = models.IntegerField(primary_key=True) title = models.CharField(max_length=200) description =models.CharField(max_length=200,default='') mentor = models.CharField(max_length=200,default='') max_members = models.IntegerField() … -
Django Rest Framework - Calling .update() from an overriden .create() method inside ModelViewSet
I'm using Django 2.2.x and djangorestframework 3.11.1. Inside a ModelViewSet I had to override the .create() method to customize the default behavior. Sometimes I need to really create a new model instance upon receiving a POST http request, sometimes I need to .update() an existing instance but all I can receive are POST requests (the source is an external server I don't have control over). I know it's a bad idea to conflate create and update... The problem is that whenever my update-instead-of-create logic kicks in, I get the following error: AssertionError: Expected view EventViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly I tried two other ways to work around this issue: directly call Event.objects.update() but I realized this is a no go for me, since I overrode the get_serializer() method to alter the raw json payload coming from the external server and I don't want to duplicate the customization logic here. calling the django built-in .update_or_create() method but the filtering was a bit too complex and I still have the same problem of the first bullet My view: class EventViewSet(LoggingMixin, viewsets.ModelViewSet): """this is … -
How to deserialize array of objects with no name?
So I have array of object being POSTed to my view with shape like this: [{"id": 5, "is_read": true}, {"id": 6, "is_read": false}] I want to find a way of deserializing that in my DRF serializer. It is possible to have nested serializers when your array has name, that is, is like this: "arrayName": [] instead of just like this: []. With nested serializers I could write something like this: class MarkReadItemDeserializer(serializers.Serializer): id = serializers.PrimaryKeyRelatedField(queryset=Message.objects.all()) is_read = serializers.BooleanField() class MarkReadDeserializer(serializers.Serializer): arrayName = MarkReadItemDeserializer(many=True) Now this obviously doesn't work in my case because my array is not named arrayName. Any idea how I could go about this? -
filedescriptor out of range in select() when using Celery with Django
I am using Django, Celery and Channels(with redis backend) to handle tasks in Dajngo based backend. Recently, as the things have scaled, I am facing the issue of : ValueError('filedescriptor out of range in select()',) Traceback (most recent call last): File "/home/cbt/backend/venv/lib/python3.6/site-packages/asgiref/sync.py", line 46, in __call__ loop.run_until_complete(self.main_wrap(args, kwargs, call_result)) File "/usr/lib/python3.6/asyncio/base_events.py", line 471, in run_until_complete self.run_forever() File "/usr/lib/python3.6/asyncio/base_events.py", line 438, in run_forever self._run_once() File "/usr/lib/python3.6/asyncio/base_events.py", line 1415, in _run_once event_list = self._selector.select(timeout) File "/usr/lib/python3.6/selectors.py", line 323, in select r, w, _ = self._select(self._readers, self._writers, [], timeout) File "/home/cbt/backend/venv/lib/python3.6/site-packages/gevent/monkey.py", line 831, in _select return select.select(*args, **kwargs) File "/home/cbt/backend/venv/lib/python3.6/site-packages/gevent/select.py", line 145, in select sel_results = _original_select(rlist, wlist, xlist, 0) ValueError: filedescriptor out of range in select() During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/cbt/backend/venv/lib/python3.6/site-packages/celery/app/trace.py", line 385, in trace_task R = retval = fun(*args, **kwargs) File "/home/cbt/backend/venv/lib/python3.6/site-packages/celery/app/trace.py", line 648, in __protected_call__ return self.run(*args, **kwargs) File "/home/cbt/backend/cbproj/tasks/tasks.py", line 1095, in start_new_subgame_timer add_users_to_subgame(game, game_type) File "/home/cbt/backend/cbproj/tasks/tasks.py", line 1405, in add_users_to_subgame async_to_sync(group_send_empty_subgame_audio_game_response)(game, game_type) File "/home/cbt/backend/venv/lib/python3.6/site-packages/asgiref/sync.py", line 50, in __call__ loop.run_until_complete(loop.shutdown_asyncgens()) File "/usr/lib/python3.6/asyncio/base_events.py", line 471, in run_until_complete self.run_forever() File "/usr/lib/python3.6/asyncio/base_events.py", line 438, in run_forever self._run_once() File "/usr/lib/python3.6/asyncio/base_events.py", line 1415, in _run_once event_list = self._selector.select(timeout) File "/usr/lib/python3.6/selectors.py", line 323, in … -
Whe I am starting my server i am getting values of my form printed on my html page, which i have not taken as input yet
[![enter image description here][1]][1] Here i have to take input for city ,but instead it showing these default values.. [![enter image description here][2]][2].stack.imgur.com/CnWLz.png This is my views.py [![enter image description here][3]][3] this is index.html [1]: https://i [2]: https://i.stack.imgur.com/0ocRa.png [3]: https://i.stack.imgur.com/HVcS5.png -
django NoReverseMatch when trying to delete an object from database
I'm new to django and I've been stuck on a problem when trying to delete objects in my project's database. I've made a function in my views.py that should delete objects that are passed to it. Problem is, my template doesn't seem to be passing information correctly to the url so the whole chain is breaking. Here's the delete function in views.py def delete_player(request, id): quarterback = Quarterback.get(id=id) quarterback.delete() return redirect('show') The model "Quarterback" is here in models.py class Quarterback(models.Model): name = models.CharField(max_length=20) in my template called "show.html" I have this <tr> <td>{{ QB }} <a href="{% url 'delete_player' quarterback.id %}">Delete</a> </td> </tr> Here's the path in urls.py path('delete_player/<int:id>', views.delete_player, name="delete_player") This all keeps returning a "NoReverseMatch: Reverse for 'delete_player' with arguments '('',)' not found. 1 pattern(s) tried: ['game/delete_player/(?P[0-9]+)$']" The error message also keeps referring to my show() in views.py like this... C:\Users\Leigh\Desktop\fantasyfootball\game\views.py, line 321, in show return render(request,"game/show.html", context) … ▼ Local vars Variable Value K 'Greg Zuerlein K 10.0' QB 'Russell Wilson QB 41.34' RB 'Mark Ingram RB 31.5' TE 'Austin Hooper TE 18.6' WR 'Mike Evans WR 37.0' context {'K': 'Greg Zuerlein K 10.0', 'QB': 'Russell Wilson QB 41.34', 'RB': 'Mark Ingram RB 31.5', 'TE': 'Austin Hooper … -
Caching list of id's of django queryset, and reusing that list for another Viewset
Let's use these 4 simple models for example. A city can have multiple shops, and a shop can have multiple products, and a product can have multiple images. models.py class City(models.Model): name=models.CharField(max_length=300) class Shop(models.Model): name = models.CharField(max_length=300) city = models.ForeignKey(City, related_name='related_city', on_delete=models.CASCADE) class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=5000) shop=models.ForeignKey(Shop, related_name='related_shop', on_delete=models.CASCADE) class Image(models.Model): image=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) For an eCommerce website, users will be writing keywords and I filter on the products names, to get the matching results. I also want to fetch together the related data of shops, cities and images, relevant to the products I will be showing. To achieve that I am using .select_related() to retrieve the other objects from the foreignKeys as well. Now, my question is, what is the best way to send that to the client? One way is to make a single serializer, that groups all data from all 4 tables in a single JSON. That JSON will look like 1NF, since it will have many repetitions, for example, there will be new row for every image, and every shop that the product can be found, and the 10.000 character long description will be repeated for each row, so this is not such a good … -
How to avoid displaying form errors twice when using messages?
When showing a form in a template, I have a block that displays form errors: {% if field.errors %} {% for error in field.errors %} <div class="d-block">{{ error }}</div> {% endfor %} {% endif %} However on the same page I also have a block to display messages from the Django message system: {% for message in messages %} <div class="alert alert-{% if message.level_tag %}{{ message.level_tag }}{% endif %} alert-dismissible fade show" role="alert"> {% if message.extra_tags and 'safe' in message.extra_tags %} {{ message|safe }} {% else %} {{ message }} {% endif %} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endfor %} This means the form errors are displayed twice on the page, both in the messages block and the field.errors block. How do I avoid this? -
What are the differences between Django and Express.js?
Since, Django and Express.js are both web frameworks for Python and Node.js respectively. So, This is a very basic difference between them. But, there might be other important differences. So, if somebody can explain that here, it will be very beneficial to me. -
How can i fetch a specific to a variable
Hello i want to fetch a specific field to a variable For that I have Order model: class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey( Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) Here I want to fetch total field in a variable.But I am new for that reason I am really confused about this topic -
get variable from method that have a parameters without sending the parameter (dynamic Django Chart Js)
So i have views method in my Django Project like this def analyticindex(request): token = request.GET.get('token') return render(request, 'analytic.html') And another method for viewing the chart into that template ('analytic.html') def respon(request): nama_token = #GET_VARIABLE_token_FROM_analyticindexMethod from .getChart import barFunc, pieFunc model = [Detik,Kompas,Antara] dtk_bar = dict(zip(barFunc(Detik,10)[0],barFunc(Detik,10)[1])) ant_bar = dict(zip(barFunc(Antara,10)[0],barFunc(Antara,10)[1])) kmp_bar = dict(zip(barFunc(Kompas,10)[0],barFunc(Kompas,10)[1])) pie = {} data_bulan = [] for x in pieFunc().items(): pie[x[0]] = x[1] for i in model: for x in i.objects.filter(token=nama_token).values_list('january','february','march','april','may','june','july','august','september','october','november','december'): data_bulan.append(list(x)) data ={ 'pie' : {'nama':list(pie.keys()),'angka':list(pie.values())}, 'dtk_bar':{'nama':list(dtk_bar.keys()),'angka':list(dtk_bar.values())}, 'kmp_bar':{'nama':list(ant_bar.keys()),'angka':list(ant_bar.values())}, 'ant_bar':{'nama':list(kmp_bar.keys()),'angka':list(kmp_bar.values())}, 'jamet':[sum(x) for x in zip(*data_bulan)] } return JsonResponse(data) as we can see, that i need the 'token' variable from analyticindex method into the respon method, so i can dynamicaly get the data into my templates (from user input) Thank you! -
How do I send form data to my email for approval as a post on my django webapp?
I think I know how to send the form data to email with existing django documentation but I am wondering how I'd go about the post pending approval part. also how could I implement the ability to edit the post's contents before the form data gets finally submitted as a post? -
displaying data from Django in React Native app
I am trying to send pull from Postgres database in Django to my React Native app. const [gardens,setGardens] = useState([]); useEffect(() => { fetch("http://127.0.0.1:8000/Home/Gardens/",{ method:'GET', headers:{ 'Content-Type': 'application/json', 'Authorization': 'Token ***' } }) .then( res => res.json()) .then(jsonRes => setGardens(jsonRes)) .catch( error => console.log(error)); }, []); <FlatList data={gardens} renderItem={({item}) => ( <View style={styles.item}> <Text style={styles.itemText}>{item.name}</Text> </View> /> The app is displaying no data and I am getting the following message: [native code]:null in callFunctionReturnFlushedQueue. Please help me solve this issue. -
Boolean expression not returning the right logic
I have a simple code which is supposed to return True or False, if a user is following another user or not. this is the code below, everything is fine that is return "False" all the time even when the user is actually following. I think im missing something. What do you think? def get_is_following(self, obj): is_following = False context = self.context request = context.get("request") if request: user = request.user is_following = user in obj.followers.all() return is_following -
How are databases/table laid out in real life for blog/article websites?
I am building a blog/articles website and wanted to know what is the professional way of laying out the table for it. I am novice web developoer still in the process of learning. Hope someone helps :). -
How to get Authorization Code after successful login -- Linkedin OAuth - Django, Python
I have a Django website where users can fill in an profile form using Linkedin login. My logic was to have the user first sign-in using LinkedIn credentials & then retrieve/parse their profile & populate the fields. I was able to successfully make a user login using 'social-auth-app-django'. Now I believe my next step should be to generate an Access token. However, to generate this access token, I need the authorization code. This is where I need help. I referred to many resources, which all said, copy the authorization code manually & use it for generating access token. But I don't understand, how that's gonna work in my case, as it could be any random user accessing the form.. or am i completely in the wrong path?? Any leads or help will be greatly appreciated. -
Solving IOError while generating a pdf using reportlab and generated qr code image
I am trying to generate a qr code from text, and then insert into a reportlab pdf. My code: def qr_code_as_image(text): from io import BytesIO print("In show_qr") img = generate_qr_code(text) print(img, type(img)) i = Image(img) print(i, type(i)) return i def add_patient_header_with_qr(self): line1 = ("Name", self.linkedcustomer.name, "Age", self.linkedcustomer.age()) line2 = ("MRD No.", self.linkedcustomer.cstid, "Date", self.prescription_time) line3 = ("No.", "#", "Doctor", self.doc.name) datatb = [line1, line2, line3] patientdetailstable = Table(datatb) patientdetailstable.setStyle(self.patientdetails_style) col1 = patientdetailstable checkin_url = reverse('clinicemr', args=[self.checkin.checkinno]) qr_image = qr_code_as_image(checkin_url) qr_image.hAlign = 'LEFT' col2 = Table([[qr_image]]) tblrow1 = Table([[col1, col2]], colWidths=None) tblrow1.setStyle(self.table_left_top_align) self.elements.append(tblrow1) def final_generate(self, footer_content, action=None): with NamedTemporaryFile(mode='w+b') as temp: from django.http import FileResponse, Http404 from functools import partial # use the temp file cmd = "cat " + str(temp.name) print(os.system(cmd)) print(footer_content, type(footer_content)) doc = SimpleDocTemplate( temp.name, pagesize=A4, rightMargin=20, leftMargin=20, topMargin=20, bottomMargin=80, allowSplitting=1, title="Prescription", author="MyOPIP.com") frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal') template = PageTemplate( id='test', frames=frame, onPage=partial(footer, content=footer_content) ) doc.addPageTemplates([template]) doc.build(self.elements, onFirstPage=partial(footer, content=footer_content), onLaterPages=partial(footer, content=footer_content) ) print(f'Generated {temp.name}') I get the following output: 2020-11-29 13:06:33,915 django.request ERROR Internal Server Error: /clinic/presc/k-0NGpApcg Traceback (most recent call last): File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 655, in open_for_read return open_for_read_by_name(name,mode) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 599, in open_for_read_by_name return open(name,mode) ValueError: embedded null byte During handling of … -
How to Merge Slashes in uWSGI When Using HTTP-Socket [Django]
I have a problem where the frontend engine sometimes adds an extra slash / in the URLs as such: /api/v1/sample//path If my UWSGI is set in socket mode, this would not cause an issue. I guess it merges the slashes internally. But, if I put the uWSGI in http-socket mode, I get the 404 because of the double slashes. How can I resolve it through uWSGI settings? Note: I have activated merge_slashes on; in Nginx configs [which is proxy passing the requests to my UWSGI]. But, it does not resolve the issue. -
Cashing all the static assets at once in a service worker in PWA
My question is about caching all the static assets present in a seperate directory (for me it is 'static') at once in the service worker in a PWA. As we know we need to provide a path to the asset to be cashed. E.g, if we want to cache an image 'img.png' then we need to do something like this; cache.add(/static/img.png) where cache is the element returned by caches.open(). And if we want to add multiple files we can do something like this; assets = [ 'static/img1.png', 'static/img2.png' ] // and so on. cache.addAll(assets); What i want to know is that if there is any way to pass directly all the files present in static folder like; cache.add(/static); But the above line is not working as we can only pass a valid path(URL) not a folder or just a file.