Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO, returning from AJAX call does not update html
I am updating a db entry through a click on a select dropdown. After confirming the selection I send an AJAX POST to another view that applies required changes on the db and reverse to the previous page. The problem is that the destination page does not reflect the new values unless I refresh. select html (project.html) <select id="update_status_outreach" name="{{outreach.id}}_____{{project.id}}"> {% for outreach_status in outreach_statuses %} {% if outreach_status.0 == outreach.outreach_status %} <option value="{{ outreach.outreach_status }}" selected>{{ outreach.outreach_status }}</option> {%else%} <option value="{{ outreach_status.0}}">{{outreach_status.0}}</option> {% endif %} {%endfor%} </select> Javascript (project.html) document.getElementById("update_status_outreach").onchange = changeListener; function changeListener() { var name = this.name.split("_____"); var project_id = name[1]; var outreach_id = name[0]; var new_status = this.value; if(confirm("Placejpòdore")) { $.ajax({ type: "POST", url: "{% url 'action:update_status_outreach' %}", data: { csrfmiddlewaretoken: "{{ csrf_token }}", 'project_id': project_id, 'outreach_id': outreach_id, 'new_status': new_status }, }); } } update_status_outreach view in outreach.py @login_required(login_url='action:login') def update_status_outreach(request): project_id = request.POST['project_id'] outreach_id = request.POST['outreach_id'] new_status = request.POST['new_status'] jobproject = get_object_or_404(JobProject, id=project_id) if jobproject.owner != request.user: raise HttpResponse(status=500) else: outreach_to_be_updated = Outreach.objects.get(id=outreach_id) outreach_to_be_updated.outreach_status=new_status outreach_to_be_updated.save() return HttpResponseRedirect(reverse('action:project', args=(project_id,))) project view in project.py @login_required(login_url='action:login') def project(request, project_id): if request.method == 'POST': outreach_id = request.POST.get('outreach_id') new_rank = request.POST.get('new_ranking') update_rank(outreach_id=outreach_id, new_rank=new_rank) project_referred = get_object_or_404(JobProject, id=project_id) jobpositions_referred = JobPosition.objects.filter(jobproject=project_referred) … -
how to format large numbers using spaces instead fo comma?
I am using django.contrib.humanize intcomma tag to format large numbers like this $18,162,711,641 but what I want spaces instead of comma, like this $18 162 711 641 How can I achieve this? Thank you. -
python / django log in issue
Currently I have usertypes in this python/django project and I was able to log in as admin but I am not being able to login as student or staff I am using postgres as data base can anyone please help me ? my models.py file models.py class CustomUser(AbstractUser): user_type_data = ((1,"HOD"), (2,"Staff"), (3,"student")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class Admin(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Staff(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) address = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Students(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=255) profile_picture = models.FileField() address = models.TextField() course_id = models.ForeignKey(Courses, on_delete=models.DO_NOTHING) session_start_year = models.DateField(blank=True, null=True) session_end_year = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type==1: Admin.objects.create(admin=instance) if instance.user_type==2: Staff.objects.create(admin=instance) if instance.user_type==3: Students.objects.create(admin=instance, course_id = Courses.objects.get(id=1), session_start_year="2020-04-02", session_end_year="2022-01-01", profile_picture="", gender="") @receiver(post_save, sender=CustomUser) def save_user_profile(sender, instance, **kwargs): if instance.user_type==1: instance.admin.save() if instance.user_type==2: instance.staff.save() if instance.user_type==3: instance.students.save() here are my views.py file views.py def DoLogin(request): if request.method != "POST": return HttpResponse("<h2> Do log in first </h2>") else: user = EmailBackEnd.authenticate(request, username=request.POST.get("email"),password=request.POST.get("password")) … -
How to pass context dictionary in django rest framework? Help me and make my life simple and easy
First of all, I want to pass multiple queryset in the same view or you can say same url path or route. In django we pass this context dictionary like this qs = Qs.objects.all() ps = Ps.objects.all() context = { 'qs' : qs, 'ps' : ps } return render(request, 'some.html', context) and in the frontend we just call them via qs or ps and we get the object. I want to do the same in django rest framework and react frontend. @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(_id=pk) related = Product.objects.filter(category=product.category).exclude(_id=pk).order_by('?')[:4] print(related) serializer = ProductSerializer(product, many=False) return Response(serializer.data) I have two queryset here product and related. I want to pass both of them in the same serializer or response. I don't know actually how to pass multiple queryset. In the react frontend const productDetails = useSelector(state => state.productDetails) const {loading, error, product} = productDetails useEffect(() => { dispatch(listProductDetails(match.params.id)) }, [dispatch, match]) const addToCartHandler = () => { history.push(`/cart/${match.params.id}?qty=${qty}`) } when I call this <h3>{product.name}</h3> I get the name from product queryset. I want the same process for my related queryset. Suppose if I call {related.name} then it should show me the name of the related product. In the backend if … -
Why does print show SRID 3847 in Geodjango?
I'm developing an app using Geodjango and PostGIS. In the admin area of my site, all polygons are displayed correctly with the (default) SRID of 4326 e.g. SRID=4326;POLYGON ((0.6564331054687499 52.13854550670472, 0.6289672851562499 52.08456959594681, 0.7553100585937497 52.08456959594681, 0.6564331054687499 52.13854550670472)) Why, when I print to the web server/console does the SRID show in 3857? The above admin area polygon is printed as: SRID=3857;POLYGON ((73073.79904062848 6825215.129639958, 70016.31790922143 6815431.190019455, 84080.73111369385 6815431.190019455, 73073.79904062848 6825215.129639958)) I don't know whether I can continue manipulating polygons as I can't, at present, be sure of their projection. -
Raising an issue after upgrading Django version
I upgraded my Django version from 3.1.2 to 3.2. But it gives me this error. django.core.exceptions.ImproperlyConfigured: Cannot import 'api'. Check that 'apps.api.apps.ApiConfig.name' is correct. Please give a suggestion. Thank you. -
Django, Javascript: passing data disables functions inside app
I'm aware that a lot of people asked a similiar question, but none of these helped me with my problem!? Inside my view I'm passing the name of the active user... views.py def index(request): user = User.objects.get(username=request.user) user_name = f"{user.first_name} {user.last_name}" json_data = json.dumps(user_name) return render(request, 'index.html', {"user_name": json_data}) script.js let user_name = {{user_name|safe}}; But when trying to attach the data to my variable inside javascript, I'm getting the following error and all of my other functions inside js stop working! SyntaxError: Unexpected token '{' Does someone know what I'm doing wrong here? Thanks for your help and have a great day! -
How to iterate on dict which contains another dict in Django?
i have some issue with my application. Here's my code : view.py dict_test = {} for result in myMongoDbRequest: dict_in_dict = {} for otherResult in result["myList"]: dict_in_dict[otherResult["1"]] = [otherResult["2"], otherResult["3"]] dict_test[result["name"]] = [result["value1"], dict_in_dict] template_filter.py @register.filter def get_in_list(list, index): return list[index] template.html {% for key, values in dico_test.items %} <div id="div{{key}}"> {% for key, value in values|get_in_list:1.items %} <div class="{{ key }}"> {{ value }} </div> {% endfor %} </div> {% endfor %} Obviously, the .items in the template is incorrect, but i wonder how to resolve this problem ? Maybe with another filter ? I try several things but nothing works, like this filter : @register.filter def convert_in_dict(a): return vars(a) {% for key, value in values|get_in_list:5|convert_in_dict.items %} But django raise Could not parse the remainder: '.items' from 'values|get_in_list:1|convert_in_dict.items' -
Having one single generic Viewset that can be resolved through its router basename on Django Rest Framework
My question is more about refactoring, best practices and potential vulnerability while organizing my routes and views in DRF. My app is really a simple one and all the views are to be described in the same fashion. Take my views.py file for example: # views.py class TrackView(viewsets.ModelViewSet): queryset = Track.objects.all() serializer_class = TrackSerializer class AlbumView(viewsets.ModelViewSet): queryset = Album.objects.all() serializer_class = TrackSerializer class ArtistView(viewsets.ModelViewSet): queryset = Artist.objects.all() serializer_class = ArtistSerializer class ChartView(viewsets.ModelViewSet): queryset = Chart.objects.all() serializer_class = ChartSerializer And in urls.py I can do: #urls.py router = DefaultRouter() router.register(r'tracks', TrackView) router.register(r'albums', AlbumView) router.register(r'artists', ArtistsView) router.register(r'charts', ChartsView) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] In this scenario every new View is a copied logic of each other only changing the name of the model they use, and for every new model added that needs a view I would basically have to create the same repeated code in urls.py and views.py. Instead of doing like that I refactored it like this: # views.py from rest_framework import viewsets class APIView(viewsets.ModelViewSet): queryset = None def get_queryset(self): return eval(self.basename).objects.all() def get_serializer_class(self): return eval(self.basename+'Serializer') # urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from top_charts.views import * from .routes import ROUTE_NAMES router … -
Why does this work?? Class Meta, model = User
Can someone please explain this?? I'm in the process of trying my first post-tutorial project. I've made a model called Profile with 4 attributes (given_name, surname, bio, image). I've made a form called ProfileForm which inherits from UserCreationForm and i've added the 4 attributes of my model into the form as form attributes. MY Question is: Why does it only work like this class Meta: model = User This is my models.py file class Profile(models.Model): given_name = models.CharField(max_length=255) surname = models.CharField(max_length=255) bio = models.TextField(blank=True, null=True) image = models.ImageField(upload_to='uploads/', blank=True, null=True) def __str__(self): return self.given_name class Meta: ordering = ['given_name'] This is my forms.py file class ProfileForm(UserCreationForm): firstName = forms.CharField(max_length=255) lastName = forms.CharField(max_length=255) bio = forms.CharField(widget=forms.Textarea) image = forms.ImageField() class Meta: model = User fields = ['firstName', 'lastName', 'username', 'password1', 'password2', 'bio', 'image'] This is my views.py file def sign_up_view(request): if request.method == "POST": form = ProfileForm(request.POST, request.FILES) if form.is_valid(): user = form.save() login(request, user) profile = Profile.objects.create( given_name=form.cleaned_data['firstName'], surname = form.cleaned_data['lastName'], bio = form.cleaned_data['bio'], image = form.cleaned_data['image']) return redirect('home') else: form = ProfileForm() return render(request, 'core/sign_up.html', {"form": form}) Note : I'm able to achieve my desired outcome, but I'm having trouble in understanding how its working. **Also if i wanted … -
XLWT TypeError at /XLS 'tuple' object is not callable
I am getting the above-mentioned error when clicking the "export to excel" button on my form. I am using the XLWT module to print the excel sheet, so I think it might have something to do with that. Please see the below code and full error message: Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse import pyodbc from django.http import FileResponse from django.contrib import messages from django.views import View from django.template.loader import render_to_string from weasyprint import HTML import tempfile from django.db.models import Sum import datetime from datetime import datetime from dateutil.relativedelta import relativedelta import xlwt def printToXLS(request): response = HttpResponse(content_type= 'application/ms-excel') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.xls' wb=xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('TrialBalance') row_num = 0 font_style = xlwt.XFStyle() columns = ('Account' , 'Description' , 'Debit' , 'Credit') all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Credit"] = row[2] rdict["Debit"] = … -
celery logging not showing in django application inside docker shell
from logging import error @app.task def partial_bid_created_event(event): event_time = get_event_time() print('wrong function') a = getWrongfunc() # here it should throw error because that function is not exist. error showing in my docker django shell . antiquely | Starting development server at http://0.0.0.0:8000/ antiquely | Quit the server with CONTROL-C. watcher | wrong function watcher exited with code 1 watcher | Monitoring 1 contracts using %s rinkeby.infura.io watcher | subscription id: %s 0x1feed3405f0f0680df9c9684957ad03d It is just showing exited with code 1 but i am expecting exact error for logging Is it because of celery async task ? How to get exception on this error . Please take a look -
Add and remove items in ManyToMany relation in Django
I have model as follows: class BusinessUnitGroup(models.Model): name = models.CharField(max_length=255) business_units = models.ManyToManyField(to=BusinessUnit, blank=True, null=True) capacity = models.IntegerField(null=True, blank=True) def __unicode__(self): return self.name Now in an view I have fields with group id's where the business unit needs to be added. From the other one it needs to be remove if it exists. I do it as follows: business_unit = get_or_none(BusinessUnit, id=business_unit_id) # Groups old_groups = BusinessUnitGroup.objects.exclude(id__in=form_data['groups']) for group in old_groups: group.business_units.remove(business_unit) new_groups = BusinessUnitGroup.objects.filter(id__in=form_data['groups']) for group in new_groups: group.business_units.add(business_unit) Where form_data['groups'] is an param and it's just a list of ids [1, 2, 3] That works fine, but is there any better way to do it? -
Instantiating URLS , Views and Models in Django
Is there a way to instantiate SQLite models, views and URLs in Django? I have tried to research it but couldn't find anything on the automatic creation of views, URLs and templates etc. I have thought of maybe creating models that have key values which tell the program what to instantiate, however, this doesn't seem to be the most efficient and user-friendly way of doing this -
Django tries to return the file (which was previously generated by Celery) and cannot find it
i deployed two docker files to Heroku (Celery, Django), but due to the fact that the volume is not scrapped as in docker-compose, Django tries to return the file (which was previously generated by Celery) and cannot find it. How can I solve the problem? -
In Dajango How import a function from another view?
I have this folder hierarchy: |---- ksy |---- shop |---- views.py |---- over_time |---- views.py On my shop/views.py, I have this functions: def check_consumed_hour(request, job_no, booked_hour): estimate_hour, consumed_hour = 0.0, 0.0 obj_job = JobNumbers.objects.get(Q(job_no=job_no)) total_consumed_hour = float(obj_job.consumed_hour) for job in obj_job.estimatedhours_set.all(): if request.user.userinform.section in job.shop_name: estimate_hour = float(job.man_hour) else: pass for job in obj_job.consumedhours_set.all(): if request.user.userinform.section in job.shop_name: consumed_hour = float(job.man_hour) else: pass balance_hour = estimate_hour - consumed_hour book_hour = float(booked_hour) # if balance_hour >= book_hour: # ESTIMATED HOUR EXCEED MSG SHOW. for job in obj_job.consumedhours_set.all(): if request.user.userinform.section in job.shop_name: man_hour = float(job.man_hour) man_hour += book_hour job.man_hour = str(man_hour) job.save() total_consumed_hour += book_hour obj_job.consumed_hour = str(total_consumed_hour) obj_job.save() return True else: pass On my core/views.py, I need the day_studies() function, so I'm importing like this: from plater_shop.views import check_consumed_hour But I'm getting the error: from shop.views import check_consumed_hour ImportError: cannot import name 'check_consumed_hour' How can I make this importation? I don't want to reply all code. -
How i access my django project on browser after deploye on aws ec2 used by container?
containers are working good but I'm trying to access it on browser ,but fail to access -
is there any way to send webrtc frame to python script?
I created first web app(python and django) which shows client's webcam frames This is my video.js 'use strict'; // On this codelab, you will be streaming only video (video: true). const mediaStreamConstraints = { video: true, }; // Video element where stream will be placed. const localVideo = document.querySelector('video'); // Local stream that will be reproduced on the video. let localStream; // Handles success by adding the MediaStream to the video element. function gotLocalMediaStream(mediaStream) { localStream = mediaStream; localVideo.srcObject = mediaStream; } // Handles error by logging a message to the console with the error message. function handleLocalMediaStreamError(error) { console.log('navigator.getUserMedia error: ', error); } // Initializes media stream. navigator.mediaDevices.getUserMedia(mediaStreamConstraints) .then(gotLocalMediaStream).catch(handleLocalMediaStreamError); However, I want to use client's webcam frame as an input to my machine learning script(python .py) file. In local, it was easily done via opencv and numpy. But in web, I cannot feed frames to ML model. Any suggestions? -
Django database routing parameter transmission problem
class AuthRouter: def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ params = hints.get('params') return 'default' def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ params = hints.get('params') return 'default' I want to pass some parameters to **hints, but I don’t know how to do it, can you tell me, thank you very much! I tried the following methods, but none of them work # read TestModel.objects({'params': 'Hello World'}).filter() # {TypeError}'UserManager' object is not callable TestModel.objects.filter(hints={'params': 'Hello World'}) # {FieldError} Cannot resolve keyword 'hints' into field ... # write TestModel.objects.filter().first().save(hints={'params': 'Hello World'}) # {TypeError}save() got an unexpected keyword argument 'hints' -
How to get the instance when upload file using model FileField in Django
I have a Customer model and I have a upload model, linked to Customer: model.py class BasicUploadTo(): prefix = '' suffix = dt.now().strftime("%Y%m%d%H%M%S") def upload_rules(self, instance, filename): (filename, extension) = os.path.splitext(filename) id = instance.customer_id.customer_id.user_id return os.path.join(str(id), "Docs", f"{self.prefix}_{self.suffix}{extension}") def upload_br(self, instance, filename): instance1 = Customer.customer_id self.prefix = "BR" dir = self.upload_rules(instance, filename) return dir class AttachmentsBasic(models.Model): customer_id = models.OneToOneField("Customer", verbose_name="client ID", on_delete=models.DO_NOTHING, blank=False, null=True) br = models.FileField(upload_to=BasicUploadTo().upload_br, verbose_name="BR", null=True, blank=True) class Customer(models.Model): customer_id = models.OneToOneField("UserID", blank=False, null=True, verbose_name="Client ID", on_delete=DO_NOTHING) ... class UserID(models.Model): user_id = models.CharField(max_length=5, blank=False, verbose_name="Client ID") class Meta(): verbose_name = "Client" verbose_name_plural = "Client" def __str__(self): return f"{self.user_id}" form.py: class ClientUploadForm(ModelForm): class Meta: model = AttachmentsBasic fields = ( "br",) def __init__(self, path, *args, **kwargs): super(ClientUploadForm, self).__init__(*args, **kwargs) print(path) for x in self.fields: self.fields[x].required = False def save(self, client_id, commit=True): clientDoc = super(ClientUploadForm, self).save(commit=True) print(self) instance = Customer.objects.get(customer_id__user_id=client_id) clientDoc.customer_id = instance if commit: clientDoc.save() return clientDoc views.py def clienInfo(request, client): clientsIDs = [c.customer_id.user_id for c in Customer.objects.all()] if client in clientsIDs: matching_client = Customer.objects.filter(customer_id__user_id=client) if request.method == "POST": instance = Customer.objects.get(customer_id__user_id=client) uploadForm = ClientUploadForm(request.POST, request.FILES, instance.customer_id.user_id) if uploadForm.is_valid(): uploadForm.save(request.POST["customer_id"]) else: print("Client's document form got error.") else: print("Client form got error.") uploadForm = ClientUploadForm sale = sales.objects.all() return … -
enable to verify whether data exists in database for login
i am a beginner i am trying to do a post request to get the coer_id and password from the client and then i am trying to check whether they exists in database or not .i am enable to perform it.it will be really helpful if you can tell me how i can correct it or do it . models.py from django.db import models from django.core.validators import RegexValidator class student_register(models.Model): name=models.CharField(max_length=100) father_name=models.CharField(max_length=100,null=True) bhawan=models.CharField(max_length=100,null=True) branch=models.CharField(max_length=40,null=True) coer_id=models.CharField(max_length=12,unique=True,null=True) phone_regex=RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+9999999999'. Up to 12 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17) password=models.CharField(max_length=100) serializer.py from django.db.models import fields from rest_framework import serializers from .models import student_register class register_serializers(serializers.ModelSerializer): class Meta: model = student_register fields = '__all__' class login(serializers.ModelSerializer): class Meta: model = student_register fields = ['coer_id','password'] views.py from rest_framework.response import Response from rest_framework import viewsets from .models import student_register from .serializer import register_serializers from .serializer import login from rest_framework.decorators import api_view from rest_framework import status class register_view(viewsets.ModelViewSet): queryset= student_register.objects.all() serializer_class= register_serializers @api_view(['POST']) def check_login(request): serializer=login(data=request.data) if serializer.is_valid(): if student_register.objects.filter(coer_id=serializer['coer_id']).exists(): if student_register.objects.filter(password=serializer['password']).exists(): return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) this is the error which i get when i send the json file and post it Internal Server Error: /login/ Traceback (most … -
Where is class "django.template.Node " defined in Django source code
I am reading Django official guide and came across a statement as below: When Django compiles a template, it splits the raw template text into ‘’nodes’’. Each node is an instance of django.template.Node and has a render() method. A compiled template is a list of Node objects. But I did not find django.template.Node definition in Django source code, where is it please ? -
how can i route from one nginx serve to another?
i have a containerized nginx server currently setup with https (nginx.main) and it's serving my django app that's in another container. unfortunately, django is not responding with the static files - and i've read that's a normal thing. so, what i'd like to do is setup another instance of nginx to do that for me (nginx.static) nginx.main default.conf config that i've tried: ...some stuff going to --> server { listen 4430 ssl; listen [::]:4430 ssl default ipv6only=on; server_name avnav.com; ssl_certificate /etc/nginx/_cert/etc/letsencrypt/live/avnav.com/fullchain.pem; ssl_certificate_key /etc/nginx/_cert/etc/letsencrypt/live/avnav.com/privkey.pem; ssl_dhparam /etc/nginx/_cert/etc/letsencrypt/live/dhparam.pem; ...some security stuff... location / { proxy_pass http://django_app; proxy_set_header Host avnav.com; } location /media { proxy_pass http://nginx_static; } } nginx.main nginx.conf config: upstream django_app { server droplet.ip:8000; } upstream nginx_static { server droplet.ip:8082; } nginx.static default.conf config: server { listen 8080 default; server_name localhost; location / { root /usr/share/nginx/static/; } at first i thought it was an issue with alias vs root, but not so. the volumes are setup so that the host static files are mounted to /usr/share/nginx/static in nginx.static. inside that folder, there are subfolders for css, js, etc. nginx.main runs on port 8081:8080 django runs on 8000 nginx.static runs on 8082:8080 -
Access blocked by CORS policy: No 'Access-Control-Allow-Origin'
I am using the following versions Python 3.9.6 Django 3.2.3 django-cors-headers==3.7.0 I have the following in my settings.py CORS_ALLOW_ALL_ORIGINS=True CORS_ORIGIN_WHITELIST = ('http://localhost:3000',) For some reason, one of the API call fails out with this error. Access to fetch at from origin has been blocked by CORS policy: No 'Access->Control-Allow-Origin' header is present on the requested resource. If an opaque response serves >your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I am not able to understand why I get this error. Here are the relevant request and response details as extracted from Google Chrome Developer tools General Request URL: http://10.0.123.123:8998/api/box?unit=101&box=TOT000000000051345&login_user_id=USERID&reserve_locn=101 Request Method: OPTIONS Status Code: 200 OK Remote Address: 10.0.123.123:8998 Referrer Policy: strict-origin-when-cross-origin Response Headers Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Allow-Origin: * Access-Control-Max-Age: 86400 Connection: keep-alive Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Tue, 07 Sep 2021 01:15:10 GMT Server: nginx/1.20.1 Vary: Origin Request Headers OPTIONS /api/box?unit=101&box=TOT000000000051345&login_user_id=USERID&reserve_locn=101 HTTP/1.1 Host: 10.0.123.123:8998 Connection: keep-alive Accept: / Access-Control-Request-Method: GET Access-Control-Request-Headers: content-type Origin: http://10.0.123.123:8999 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Sec-Fetch-Mode: cors Referer: http://10.0.123.123:8999/ Accept-Encoding: gzip, deflate Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 -
How to connect AWS Elasticache Redis from a local machine for a Django project?
I've Redis chace installed on both my local and aws elasticache. My Django project runs well on my local machine with Redis. However, when I connect to my redis remotely on aws, I get the following error. Error 10060 connecting to xyz.0001.use2.cache.amazonaws.com:6379. A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. I have the following Django settings for the local redis: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } And this the Django settings for the remote redis instance: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://xyz.0001.use2.cache.amazonaws.com:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } Again, when I switch from local to remote caches settings, I get that error above. I know that I it is not possible to connect ElastiCache outside AWS unless you have a vpn connection. So, I've set up the vpn client end point on aws and connected to it using the aws vpn client. I can successfully connect via vpn as shown below. Any idea why I still can't connect from my local machine to the remote redis …