Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the many to one relatiodata on DRF
How can I get the information which has a relationship with another modal class For eg. class UserSensorDevice(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) sensor_type = models.ForeignKey( 'core.Component', on_delete=models.CASCADE ) sensor_code = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.pseudonym And I have another modal class: class ReplacedSensorDevice(models.Model): sensor_type = models.ForeignKey( 'core.Component', on_delete=models.CASCADE ) replaced_for = models.ForeignKey( 'UserSensorDevice', on_delete=models.CASCADE, null=True ) sensor_code = models.CharField(max_length=255, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) When I will call UserSensorSerializer then if replacement is available then I need to get that information as well. I am not able to figure it out how can I get that views.py class UsersSensorDeviceView(generics.ListAPIView): permission_classes = (permissions.IsAuthenticated, jwtPermissions.IsOwner,) queryset = sensorModels.UserSensorDevice.objects.all() pagination_class = pagination.PostLimitOffsetPagination filter_backends = (DjangoFilterBackend,OrderingFilter,SearchFilter) filter_fields = ('user','id','sensor_type',) serializer_class = serializers.UserSensorDeviceSerializer serializers.py class UserSensorDeviceSerializer(serializers.ModelSerializer): sensor_name = serializers.CharField(source='sensor_type.comp_code', read_only=True) class Meta: model = sensorModels.UserSensorDevice fields = '__all__' read_only_fields = ['id','created_at'] Any suggestion will be of great help. -
Is it possible to pass the foreign key id in Django rest-framework URL?
I am using routers in Django Rest Framework and trying to create a dynamic URL based on a foreign key. My urls.py file looks like this, router = routers.DefaultRouter() router.register('user/<int:user_id>/profile', IntensityClassViewSet, 'intensity_classes') urlpatterns = router.urls My models.py file looks like below, class Profile(models.Model): user = models.ForeignKey( User, related_name='profile_user', on_delete=models.CASCADE) character = models.CharField(max_length=10, null=True, blank=True) My views.py file looks like below, class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer I am getting the 404 error in all (post, put, get) request. Is there any possible easy solution for such kind of implementation? -
How to create own storage for COS in Django
ValueError: Cannot serialize: <desert.storage.TencentStorage object at 0x104fcc580> There are some values Django cannot serialize into migration files. For more, see https://docs.djangoproject.com/en/4.0/topics/migrations/#migration-serializing I want to link the FileField in Django to my COS so that I can upload file from admin site to COS. Here is my code: secret_id = settings.COS_SECRET_ID secret_key = settings.COS_SECRET_KEY region = settings.REGION bucket = settings.BUCKET config = CosConfig(Region=region, Secret_id=secret_id, Secret_key=secret_key) client = CosS3Client(config) host = 'https://' + bucket + '.cos.' + region + '.myqcloud.com/' class TencentStorage(Storage): def save(self, name, content, max_length=None): filename = self.generate_filename(name) client.put_object( Bucket=bucket, Key='song/' + filename, Body=content.read() ) return filename def generate_filename(self, filename): return filename + '_' + sha1(str(time.time()).encode('utf-8')).hexdigest() def url(self, name): file_url = client.get_object_url(bucket, 'song/' + name) return str(file_url) But after I fill this storage into model like this and use the make migration command: song_file = models.FileField(storage=TencentStorage(), null=True) It raised an error: ValueError: Cannot serialize: <desert.storage.TencentStorage object at 0x104fcc580> There are some values Django cannot serialize into migration files. For more, see https://docs.djangoproject.com/en/4.0/topics/migrations/#migration-serializing How to solve this. -
Implementing Django Bootstrap crispy forms into default signup / login pages?
I've set up user account signup and login pages following this tutorial and it all works great, except the pages have no formatting. I'm now looking for a simple drop in solution to improve the appearance of "templates/registration/login.html" and "templates/registration/signup.html". Someone recommended crispy forms which look great, and as the rest of my site uses Bootstrap 5, crispy-bootstrap5 looks ideal. I'm struggling to implement crispy-bootstrap5 as I don't understand Django's inbuilt django.contrib.auth.forms nor forms in general, and can't find simple reproducible examples for crispy forms with signup.html and login.html. I've installed packages fine, but now don't know how to beautify login.html and signup.html from that tutorial: {% extends 'base.html' %} {% block title %}Sign Up{% endblock %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> {% endblock %} I don't know where to go with this, but the docs for regular django-crispy links to a gist for an eg form, and the index.html {% load crispy_forms_tags %} and {% crispy form %}. I've put them in which mostly left the page unchanged except for messing up the formatting. I think I now need to modify class CustomUserCreationForm(UserCreationForm) in forms.py but … -
DRF: How to pass extra context data to serializers
I was searching the net and found the similar problem but it doesn't work in my case, Idk why. I try to put some extra data to context in serializer, but get only 3 default fields: request, view and format and no mention for my custom data. My model: class Match(models.Model): sender = models.ForeignKey( Client, on_delete=models.CASCADE, related_name='senders' ) recipient = models.ForeignKey( Client, on_delete=models.CASCADE, related_name='recipients' ) class Meta: app_label = 'clients' db_table = 'matches' verbose_name = 'match' verbose_name_plural = 'matches' constraints = [ models.UniqueConstraint( fields=['sender', 'recipient'], name='unique_match' ) ] My Serializer: class MatchSerializer(serializers.ModelSerializer): sender = serializers.HiddenField(default=serializers.CurrentUserDefault()) def validate(self, data): if data['sender'] == self.context['recipient']: raise serializers.ValidationError('You cannot match yourself') return data def create(self, validated_data): return Match.objects.create( sender=validated_data['sender'], recipient=self.context['recipient'] ) class Meta: model = Match fields = ['sender']` My ModelViewSet: class MatchMVS(ModelViewSet): queryset = Match.objects.all() serializer_class = MatchSerializer http_method_names = ['post'] permission_classes = [IsAuthenticated] # without and with doesn't work def get_serializer_context(self): context = super(MatchMVS, self).get_serializer_context() context.update({ "recipient": Client.objects.get(pk=23) # extra data }) return context @action(detail=True, methods=['POST'], name='send_your_match') def match(self, request, pk=None): sender = request.user recipient = Client.objects.get(pk=pk) serializer = MatchSerializer(context={'request': request, 'recipient': recipient}, data=request.data) data_valid = serializer.is_valid(raise_exception=True) if data_valid: recipient = serializer.save() is_match = Match.objects.filter(sender=recipient, recipient=sender).exists() if is_match: send_mail( f'Hello, {sender.first_name}', f'You … -
Adding uploaded text file to textbox field - Django
I am pretty new to Django and still learning, but I am having a hard time trying to figure out how to let a user upload a .txt file but instead have the uploaded .txt file overwrite in the textfield itself. Example: When uploaded https://imgur.com/a/jdCjlVS I haven't been able to find understandable resources, but this is all I have at the moment: forms.py class NewInput(forms.Form): text = forms.CharField(label='Input', max_length=1000, required=False) file = forms.FileField(required=False) models.py class Collection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="collection", null=True) text = models.TextField(max_length=1000, default='') create.html {% extends 'main/base.html' %} {% load crispy_forms_tags %} {% block title %} New Input {% endblock %} {% block content %} <center> <h3>Create a New Input:</h3> <p class="text-primary"></p> <form method = "post" action = "/create/" class="form-group" enctype="multipart/form-data"> {% csrf_token %} {{form|crispy}} <div class="input-group mb-3"> <div class="col text-center"> <button type="submit" name="save" class="btn btn-success">Create</button> </div> </div> </form> </center> {% endblock %} views.py def create(response): if response.user.is_authenticated: username = response.user.username if response.method == "POST": form = NewInput(response.POST) if form.is_valid(): n = form.cleaned_data["text"] t = Collection(text=n) t.save() response.user.collection.add(t) return HttpResponseRedirect("/collections/%s" % username) else: form = NewInput() return render(response, "main/create.html", {"form": form}) else: return HttpResponseRedirect("/login") I tried adding a separate class as a form field but I was … -
Get "Foo" queryset of ForeignKey relationships for initial "Bar" queryset?
I have a simple ForeignKey relationship: class Foo(models.Model): id = UUIDField() class Bar(models.Model): id = UUIDField() foo = ForeignKey(foo) If I have an initial queryset of Bar objects, how can I get a queryset of related Foo object for each respective Bar? I'm currently doing this but I'm wondering if there's a better way: bar_qs = Bar.objects.all().select_related("foo") foo_ids = [] for i in bar_qs: foo_ids.append(i.foo.id) foo_qs = Foo.objects.filter(id__in=foo_ids) -
Why does assigning value to Django Object change the value from NoneType to Tuple?
I am polling an API and I am returned a dictionary. I take this dictionary and attempt to take the data from it and assign it to a new django object: def write_object(account, data): #account is a Django object #data is a dictionary from an API if Obj.objects.filter(account=account, pk=data['id']).exists() == False: #create new Obj.objects.create(account=account, pk=data['id']) #object already exists, fetch relevant application object obj = Obj.objects.get(account=account, pk=data['id']) #assign the values from data to the object obj.name = data['name'], obj.notes = data['notes'], obj.status = data['status'], obj.created_at = iso8601_to_datetime(data['created_at']) This all works fine: print(type(data)) -> <class 'dict'> print(data['notes']) -> None print(type(data['notes'])) -> <class 'NoneType'> print(obj.notes) -> (None,) print(type(job.notes)) -> <class 'tuple'> print(data['opened_at']) -> 2022-02-28T15:23:11.000Z print(obj.opened_at) -> datetime.datetime(2022, 2, 28, 15, 23, 11, tzinfo=),) print(type(obj.opened_at)) -> <class 'tuple'> My question is: How do the data types become tuples when I assign it to the object? -
Error While Deploying Django Application on Heroku
I have been following a tutorial to deploy my application on Heroku, however, when I try running the application it gives me an error. I was not able to understand the logs properly from Heroku nor find any information over the internet. This is the error that I get when I run the application: The error image Hope somebody can answer this or at least let me know where within django project I can find this error. As I need some sort of leads towards this issue. Do let me know if you require further information from me. Thanks -
Django project How to change an object from for loop (its a JSON response) to readable by Java-Script
I would like to make easy math in my currency Django project but I got response in google chrome inspect that one object (that which comes from API JSON response) is undefined but second is a String When I change code a little bit to this below I got response in console inspect And I can see clearly this object is there but I can't get it out of class .value console.log(amount1, amount2); <p id="crypto-price">3289.00221916 </p> <option id="user-wallet">15000 </option> static/js/javascript.js const amount1 = document.getElementById("crypto-price"); const amount2 = document.getElementById("user-wallet"); function calculate() { console.log("YESS"); **console.log(parseInt(amount1.value) * parseInt(amount2.value));** console.log(typeof amount1.value, typeof amount2.value); } calculate(); YESS javascripts.js:13 NaN javascripts.js:14 undefined string Django templates where are both objects "crypto-price" "user-wallet" comes from the for loop {% extends "web/layout.html" %} {% block body %} <div class="row"> {% for crypto_detail in crypto_detail_view %} <div class="col-lg-12 col-md-6 mb-4"> <div class="card h-100"> <div class="card-body"> <img class="rounded mx-auto d-block" src="{{crypto_detail.logo_url}}" width="50" height="50"> <h4 class="card-title text-center" id="crypto-name">{{ crypto_detail.name }} </h4> </div> <div class="card-footer text-center"> <p id="crypto-price" >{{crypto_detail.price}} </p> <p>{{fiat_currency}}</p> </div> <div class="card-footer text-center" > <p href="">Price Date: {{ crypto_detail.price_date }}</p> </div> </div> </div> {% endfor %} <div class="row g-3 align-items-center"> <p>Your Money:</p> <select class="form-select" aria-label="Default select example"> <option selected>which currency do … -
How to a calender with Django that will highlight seven days from the user's input
Hi I need your help guys I'd like to make an app in Django to take a date from the user then replay with the next seven dates, those seven days will be shown as highlighted dates on the calendar on the web page and the same on a mobile app, and I a don't know how can I do it. PS. I'm working with the rest framework -
OSError: [Errno 24] Too many open files when uploading 9000+ csv files through Django admin
I've been struggling to upload csv files containing data to populate the database of my Django project. I am serving my project using Django 3.1 and Gunicorn if that is important. I've referred to multiple stack overflow posts regarding the same issue, but none of them have resolved this problem. Just to list out the steps I've taken to solve this problem: Ran ulimit -n 50000 in terminal to increase the max number of files that can be opened as suggested by this post. Used ulimit -n to find the max number of files that can be opened and changed the configurations of this limit in the limits.conf file, as suggested by this post, to changed the system limits. I confirmed it was changed by running ulimit -a I believed it might be a memory issue and that Linux was limiting the max amount of space available on the heap so I changhed the configuration for that as well. Fortunately, it was not a memory issue since RAM usage appeared to be extremely stable according to my control panel Here is the code related to my issue: admin.py class CsvImportForm(forms.Form): csv_upload = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) @admin.register(dummyClass) class dummyClassAdmin(admin.ModelAdmin): search_fields = search … -
Getting bad request 400: Unable to submit formset with DRF
I have two models, one is Voucher and another one is Journal. I created a formset with django forms to create a voucher for a set of journals. Each voucher must contain at least two transactions of journal. Here's my model below: class Voucher(models.Model): transactions_date = models.DateField(default=now) voucher_type = models.CharField(max_length=2) voucher = models.CharField(max_length=50, blank=True, null=True) narration = models.CharField(max_length=100) debit = models.DecimalField(max_digits=10, decimal_places=2, default=0) credit = models.DecimalField(max_digits=10, decimal_places=2, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name="+", blank=True, null=True, on_delete=models.SET_NULL) updated_by = models.ForeignKey(User, related_name="+", blank=True, null=True, on_delete=models.SET_NULL) is_deleted = models.BooleanField(default=False) def __str__(self): return str(self.voucher) class Meta: verbose_name = 'Voucher' verbose_name_plural = 'Vouchers' default_related_name = 'voucher' def get_voucher(self): return self.voucher_type + now().strftime('%Y-%m-%d-' + str(int(self.id))) def get_debit(self): transactions = Journal.objects.filter(voucher=self) total = 0 for item in transactions: total += item.debit return total def get_credit(self): transactions = Journal.objects.filter(voucher=self) total = 0 for item in transactions: total += item.credit return total def save(self, *args, **kwargs): self.voucher = self.get_voucher() self.debit = self.get_debit() self.credit = self.get_credit() super(Voucher, self).save(*args, **kwargs) class Journal(models.Model): account = models.ForeignKey('Account', blank=True, null=True, on_delete=models.SET_NULL) voucher = models.ForeignKey('Voucher', blank=True, null=True, on_delete=models.CASCADE) debit = models.DecimalField(max_digits=10, decimal_places=2, default=0) credit = models.DecimalField(max_digits=10, decimal_places=2, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name="+", blank=True, null=True, … -
Error running WSGI application, no module named django
I have some problem while deploying my website to Pythonanywhere.com i've done all things step by step like it was in a guide-line and at the end i catch an error: error log 2022-03-27 20:07:23,699: Error running WSGI application 2022-03-27 20:07:23,700: ModuleNotFoundError: No module named 'django' 2022-03-27 20:07:23,700: File "/var/www/usitingshit_pythonanywhere_com_wsgi.py", line 88, in <module> 2022-03-27 20:07:23,700: from django.core.wsgi import get_wsgi_application 2022-03-27 20:07:23,700: i've tried to change wsgi.py file import os import sys path = '/home/usitingshit/deploy_course_work/' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] ='/home/usitingshit/deploy_course_work/vodprojectstroy_site/wsgi.py' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() structure of my project: has anybody had the same problem? how can i fix that? sorry if this question is silly, coz i am a beginner in django -
django login without password
I'm looking for a way how to login without password. During create new user I noticed that, password field has default value empty, but not null. How can I do login with empty password? Because not all user needed to have password set. models.py class user(AbstractUser): database: | username | password | | -------- | -------------- | | A | | | B | 123 | views.py user = authenticate(request, salary_number='A', password='') if user is not None: login(request, user) return redirect('index') -
Vercel CLI Pyhon version issue when deploying Django project
When running the vercel command in Ubuntu terminal: Error! Command failed: python3.6 /tmp/2de7da56/get-pip.py --user ERROR: This script does not work on Python 3.6 The minimum supported Python version is 3.7. Please > use https://bootstrap.pypa.io/pip/3.6/get-pip.py instead. python --version returns 3.8.10. pip --version returns 22.0.4. vercel --version returns 24.0.1 requirements.txt just has Django == 4.0.3 What I tried: Ran the script linked in the error message and added its installation directory to PATH. Updated pip in default directory to 22.0.4. Even aliased python3.6 to python at one point. Tried on both Windows and Ubuntu. -
django export data to excel template
I installed django-import-export and it's working fine with export to excel file. But I would like to insert data into prepared excel file because of some macro. It's possible to do like that? And how can I achieve it? -
Let user add user but not change the user in Django admin, is that possible, and if so how?
In my Django 4.0 it's impossible to let staff user "add User" but not "change user" in the Admin interface. Is that possible to let staff user to not change user in the admin interface but still be able to add user? -
user accessible in template without passing to context
i have the following code. @login_required(login_url='login') def ListDeleteNoteView(request, pk): query_note = Note.objects.filter(id=pk).get() if request.method == 'POST': query_note.delete() return redirect('dashboard') context = { 'note': query_note } return render(request, 'notes/note.html', context) in the template,am able to access {{user}}. i dont understand why am able to do soo. i never passed it to context.why is this soo guys??. It also didnt come from the inherited base.html -
How to pass arguments to reverse so it is accessible in a django view
I'm trying to understand how reverse works with arguments and my goal here is to pass the body of a post request from one view (callerView) to another (demoView) through a function. In other words, I want demoVIew to return the body of the json request that was sent to callerView (I intend to do some manipulation of the data in demoView later on). Urls - "api/v2/ada/demo", views.demoView.as_view(), name="ada-demo", ), path( "api/v2/ada/caller", views.callerView.as_view(), name="ada-caller", ), ] Function - ada_response = reverse("ada-demo", args=payload) return ada_response Views - permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): body = request.data response = demo(body) return Response(response, status=status.HTTP_200_OK) class demoView(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): body = request.data return Response(body, status=status.HTTP_200_OK) Tests- def test_caller( self ): rp_payload = { "contact_uuid": "49548747-48888043", "choices": 3, "message": ( "What is the issue?\n\nAbdominal pain" "\nHeadache\nNone of these\n\n" "Choose the option that matches your answer. " "Eg, 1 for Abdominal pain\n\nEnter *back* to go to " "the previous question or *abort* to " "end the assessment" ), "step": 6, "value": 2, "optionId": 0, "path": "/assessments/assessment-id/dialog/next", "cardType": "CHOICE", "title": "SYMPTOM" } user = get_user_model().objects.create_user("test") self.client.force_authenticate(user) response = self.client.post( reverse("ada-caller"), rp_payload, ) print(response) self.assertEqual(response.status_code, 400, response)``` Error: ```django.urls.exceptions.NoReverseMatch: Reverse … -
Is it safe to delete all .pyc files from the django root directory?
Is it safe to delete all .pyc files from the Django root directory? I ran the command below in my Django root directory: find . -name "*.pyc" -exec git rm -f "{}" \; to delete .pyc files that I saw in my git check-in but the process went for quite some time and deleted hundred of .pyc files within every directory. I am a beginner in Python, Git and I am a bit concerned if this will have an impact on my Django code? -
persist indiviual data between views
I am playing with Django. I have a view where i repr 1 object, below them there is 4 cards with options related to that object. I want the user to click in one of the cards, then rear first obj, clicked option and 4 new options related to clicked option. I am not really sure about how to dev that. I was thinking about use forms or session (?). Because I really don't want to use urls kwargs. Hope u can guide me, thanks! I tried with context but didn't achieve anything plausible -
How can I load my Django project into celery workers AFTER they fork?
This question might seem odd to folks, but it's actually a creative question. I'm using Django (v3.2.3) and celery (v5.2.3) for a project. I've noticed that the workers and master process all share the same code (probably b/c celery loads my app modules before it forks the child processes for configuration reasons). While this would normally be fine, I want to do something more unreasonable :smile: — I want the celery workers to each load my project code after they fork (similar to how uwsgi does with lazy-apps configuration). Some responses here will ask why, but let's not focus on that (remember, I'm being unreasonable). Let's just assume I don't want to write thread-safe code. The risks are understood, namely that each child worker would load more memory and be slow at restart. It's not clear to me from reading the celery code how this would be possible. I've tried this to no avail: listen to the signal worker_process_init (source here) then use my project's instantiated app ref and talk to the DjangoFixup interface app._fixups[0] here and try to manually call all the registered signal callbacks for the DjangoFixupWorker here Any ideas on the steps to get this to work … -
I want to add products to my cart and display the cart details like cart list. but the code is not showing the details on the page?
views is written as def cart_details(request, tot=0, count=0, cart_items=None): try:ct = cartlist.objects.get(cart_id=c_id(request)) ct_items = item.objects.filter(cart=ct, active=True) for i in ct_items: tot += (i.prodt.price * i.quan)count += i.quan except ObjectDoesNotExist: pass return render(request, 'cart.html', {'ci': cart_items, 't': tot, 'cn': count}) def c_id(request): ct_id = request.session.session_key if not ct_id: ct_id = request.session.create() return ct_id cart>models class cartlist(models.Model): cart_id = models.CharField(max_length=250, unique=True) date_added = models.DateTimeField(auto_now_add=True) class item(models.Model): prodt = models.ForeignKey(product, on_delete=models.CASCADE) cart = models.ForeignKey(cartlist, on_delete=models.CASCADE) quan = models.IntegerField() active = models.BooleanField(default=True) cart>urls urlpatterns = [' path('cartDetails', views.cart_details, name='cartDetails'), path('add/<int:product_id>/', views.add_cart, name='addcart'), ] cart.html <tr> {% for i in ci %} <td><a href="#"><img src="{{i.prodt.img.url}}" alt="img"></a></td> <td><a class="aa-cart-title" href="#">{{ i.prodt.name }}</a></td> <td>${{ i.prodt.price }}</td> {% endfor %} <tr> this is the cart page to get the view code has some mistakes, while adding the products the create the cart id and then the products are added but which is not shown in the chart HTML page -
Django Auth with Nginx works with Postman but not with Axios
I am using the default auth system from django (served with gunicorn and nginx) and it is working fine when I try the requests with Postman, but when I try the same requests from the browser with Axios. It seems that django receives the headers properly when the request comes from Postman, but when the request come from the browser/axios the header is incomplete. Thus, the user is never logged in after login in browser/axios. Header received by django from postman: {'Host': 'SERVER_NAME', 'X-Real-Ip': 'REAL_IP', 'X-Forwarded-For': 'IP', 'X-Forwarded-Proto': 'http', 'Connection': 'close', 'User-Agent': 'PostmanRuntime/7.29.0', 'Accept': '*/*', 'Postman-Token': '9342a13d-1db9-4c38-bbd9-0c66fd8ac727', 'Accept-Encoding': 'gzip, deflate, br', 'Cookie': 'csrftoken=CSRFTOKEN; sessionid=SESSIONID'} Header received by django from axios: {'Host': 'SERVER_NAME', 'X-Real-Ip': 'REAL_IP', 'X-Forwarded-For': 'ip', 'X-Forwarded-Proto': 'http', 'Connection': 'close', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0', 'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3', 'Accept-Encoding': 'gzip, deflate', 'Access-Control-Allow-Origin': 'true', 'Origin': 'http://localhost:8080', 'Referer': 'http://localhost:8080/', 'Cache-Control': 'max-age=0'} My nginx config is: server { listen 80; server_name SERVER_NAME; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/plataforma/backend/plataforma-back-end/pvanalytics_backend; } location / { include proxy_params; proxy_pass http://unix:/home/plataforma/backend.sock; proxy_set_header HTTP_Country-Code $geoip_country_code; proxy_pass_request_headers on; } }