Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JavaScript Fetch API is reluctant to include cookies in its requests
My program includes a Django backend and a React frontend that communicate with each other. If I log in via the corresponding endpoint of the django backend, the "sessionid" cookie is set correctly in the browser. (In the application tab of Chrome I can see the "sessionid" cookie). So far so good. However, when I send a request containing this cookie from the frontend to my backend, I can see in the networks tab that the cookie is not sent with the request. I have the 'credentials' option of my fetch requests set to 'include'. Additionally, React is running on 'localhost:3000' and Django on 'localhost:8000' (therefore there should not be any issues concerning cross-origin requests). My fetch request: fetch("http://127.0.0.1:8000/user", { method: "GET", credentials: "include", }); The cookie in the browser: No cookie included in the request to the Django backend by the browser: Another peculiar thing is that the 'sessionid' cookie is included in the requests made by React automatically, as can be seen here: Moreover, I have implemented the CORS-middleware in Django. I am quite sure that the issue is not related to CORS. I tried doing the request with axios and setting 'withCredentials: true'. But this does not … -
allauth twitch oauth 2.0 and Login
Is it possible to get the twitch access_token using the allauth library, and, at the same time, log in? If so, how do you do it? And, if so there was the access_token, it will be automatically saved in the socialaccount_socialtoken table SOCIALACCOUNT_PROVIDERS = { 'twitch': { 'APP': { 'client_id': '', 'secret': '', 'key': '' }, 'SCOPE': { 'user:read:chat', 'user:read:follows', 'bits:read', 'user:read:subscriptions', 'moderation:read', 'moderator:read:chatters', 'moderator:read:followers', 'moderator:read:blocked_terms', 'channel:read:redemptions', 'channel:read:vips', 'channel:read:subscriptions', 'moderator:manage:banned_users', 'moderator:manage:blocked_terms', 'moderator:manage:chat_messages', 'channel:manage:broadcast', 'channel:manage:polls', 'channel:manage:vips', 'channel:manage:redemptions', 'clips:edit', 'channel:edit:commercial', }, 'LOGIN_CALLBACK_URL': 'http://127.0.0.1:8000/accounts/twitch/login/callback/', 'AUTH_PARAMS': { 'response_type': 'code' }, # 'AUTH_PARAMS': { 'response_type': 'token' }, }, } -
Django Error 405 - Method Not Allowed (POST), can't figure out the cause
I'm using Python 3.10.6, Django 4.2.10, Django REST Framework 3.15.1 I have a login page in JavaScript sending POST request to Django with user credentials (and CSRF token in header), but the login view doesn't even open, I immediately get said error: Method Not Allowed (POST): api/users/login Method Not Allowed: api/users/login "POST api/users/login HTTP/1.1" 405 0 views.py @csrf_protect def login_view(request): if request.method == "POST": .... urls.py from .views import login_view, ... urlpatterns = [ ... path('api/users/login', login_view, name='login_view'), ... ] I can't figure out what's causing the 405 I tried deleting the @csrf_protect but didn't change anything error405 -
loading the provider_login_url tag on my login page
I'm trying to configure all-auth in my django project and after clicking on my login button i configured everything in the backend I'm getting the following error on line 95 TypeError at /accounts/login/ string indices must be integers 95 <a class="google-btn" href="{% provider_login_url 'google' %}> I've loaded the {% load socialaccount %} and this is the button: <a class="google-btn" href="{% provider_login_url 'google' %}> Log in with Google </a> in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Fashion', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google' ] tried loading the tag on a different page, same error -
How to customize style of django-autocomplete-light Forms
I need your help on customizing the style of TextInput Box while using django-autocomplete-light. Specifically, I have a data model TextHeader, UserInputDataSearch then I'm creating a view object as # views.py class DataSearchAutocomplete(autocomplete.Select2QuerySetView): model = UserInputDataSearch form_class = SearchDataForm success_url = 'data_access' def get_queryset(self): qs = TextHeader.objects.all() if self.q: qs = qs.filter(keywordFinder__istartswith=self.q) return qs The forms.py is as below class SearchDataForm(forms.ModelForm): userSearch = forms.ModelChoiceField( queryset=TextHeader.objects.all(), widget = autocomplete.ModelSelect2( url='dataSearch-autocomplete', attrs={ 'data-html': True, "type":"search", "class":"form-control", "id":"autoCompleteData", "autocomplete":"off", }, ) ) dateRange = fields.DateRangeField( input_formats=['%d/%m/%Y'], widget=widgets.DateRangeWidget( format='%d/%m/%Y', ) ) class Meta: model = UserInputDataSearch fields = ["userSearch"] Then, on html template, I write down these lines #htmlTemplate <form method="POST"> {% csrf_token %} <div class="row g-3"> <div class="col-lg-6"> <div> {{ form.userSearch|as_crispy_field }} </div> </div><!--end col--> <div class="col-lg-6"> <div> {{ form.dateRange|as_crispy_field }} </div> </div><!--end col--> <div class="col-lg-12"> <div class="text-left"> <button type="submit" class="btn btn-primary">Find</button> </div> </div><!--end col--> </div><!--end row--> </form> However, it renders my page with difference style of two boxes as a screenshot below, I wonder how to make them in the same style -
"This field is required" when all fields are filled in Django(5.0.6)
So, I ran into an error during developement of a django project and someone asked the same question 5 years ago so stackoverflow won't let me ask it again. Here's the question. "This field is required" when all fields are filled in Django But the answer did not fix the error for me. The current answer is out-of-date and require revision given recent changes. view.py from django.shortcuts import render,redirect from .forms import ProductForm # Create your views here def Upload(request): if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = ProductForm() if request.user.is_superuser: return render(request, r'../templates/upload.html', {'form': form}) else: return redirect('home') forms.py from django import forms from .models import Product CategoryChoices = { ('Overwhelming', "Overwhelming"), ('Outrageous', "Outrageous"), ('Mnmlsm', "Mnmlsm"), ('Gothic', "Gothic") } class ProductForm(forms.ModelForm): title = forms.CharField(widget=forms.Textarea) image1 = forms.FileField(label='select an image') image2 = forms.FileField(label='select an image',required=False) image3 = forms.FileField(label='select an image',required=False) image4 = forms.FileField(label='select an image',required=False) image5 = forms.FileField(label='select an image',required=False) category = forms.ChoiceField(choices=CategoryChoices) price = forms.IntegerField() price.widget.attrs.update({'placeholder': 'Enter Price'}) title.widget.attrs.update({'placeholder': 'Enter product title'}) class Meta: model = Product fields = ['title', 'image1', 'image2', 'image3','image4','image5','category','price'] upload.html {% extends 'base.html' %} {% block content3 %} <title>Henkan - Login</title> {% endblock %} {% block content1 %} … -
Django route cannot be accessed during fetch POST method but can be accessed during manual GET method
When I attempt to delete a faction from my application using the route saga/delete/2 after clicking the deleteSubmit button, the program returns the following error: "POST /saga/delete/2/ HTTP/1.1" 404 3048 Not Found: /saga/delete/2/ My application uses the following relevant url patterns saga/ edit/<int:factionId> [name='edit'] saga/ delete/<int:factionId> [name='delete'] This JavaScript handles the form submission factionForm.addEventListener('submit', function(event) { //prevent the default form submission event.preventDefault(); //If the Save Changes button is clicked if (event.submitter === saveSubmit){ console.log("Save Changes Pressed"); // Code to handle form submission and save changes to the database } //Otherwise if the Delete changes button is clicked else if(event.submitter === deleteSubmit){ console.log("Delete Faction Pressed"); //Attempt to send data to server fetch(`/saga/delete/${factionId.value}/`, { method: 'POST', headers: { 'X-CSRFToken': getCSRF(), }, }) //Get response from server .then(response => { if (response.ok) { console.log('Faction deleted successfully'); } else { //If a problem occurred display the response console.error('Error deleting faction',response); } }) //If There is an error output it .catch(error => { console.error('Error:', error); }); } //Otherwise if neither approved button submitted the form something went wrong else { console.log(event.submitter, "somehow submitted the form, check and correct the code near that element"); } }) The code I am using for the getCSRF() function is … -
Typed-ast ailed building wheel required to install pyproject.toml-based projects
I tried to install the requirements in Django project using pip install -r requirements.txt but it always generates the same error. I am not able to find the solutions and I tried everything suggested on the internet. The versions I used are: Python - 3.11.1 typed-ast==1.4.2 I downgraded both python and typed-ast version to see if it worsk...but it didnt work. h(457): error C2143: syntax error: missing '{' before '*' C:\Users\Aliza Paudel\AppData\Local\Temp\pip-install-13jms7r1\typed-ast_5878f64c514840fdb0c3d18010aba49b\ast27\Custom\../Include/Python-ast.h(457): error C2059: syntax error: ')' C:\Users\Aliza Paudel\AppData\Local\Temp\pip-install-13jms7r1\typed-ast_5878f64c514840fdb0c3d18010aba49b\ast27\Custom\../Include/Python-ast.h(459): error C2143: syntax error: missing ')' before '*' C:\Users\Aliza Paudel\AppData\Local\Temp\pip-install-13jms7r1\typed-ast_5878f64c514840fdb0c3d18010aba49b\ast27\Custom\../Include/Python-ast.h(459): fatal error C1003: error count exceeds 100; stopping compilation error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.39.33519\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for typed-ast Failed to build typed-ast ERROR: Could not build wheels for typed-ast, which is required to install pyproject.toml- based projects (venv) PS C:\ALL_FILES\Projected\kvwsmb> My requirements.txt looks like this. pytz==2021.1 # https://github.com/stub42/pytz python-slugify==4.0.1 # https://github.com/un33k/python-slugify argon2-cffi==20.1.0 # https://github.com/hynek/argon2_cffi redis==3.5.3 # https://github.com/andymccurdy/redis-py hiredis==1.1.0 # https://github.com/redis/hiredis-py typed-ast==1.4.2 tablib # Django # ------------------------------------------------------------------------------ django==3.1.7 # pyup: < 3.2 # https://www.djangoproject.com/ django-environ==0.4.5 # https://github.com/joke2k/django-environ django-model-utils==4.1.1 # https://github.com/jazzband/django-model-utils django-allauth==0.44.0 # https://github.com/pennersr/django-allauth django-crispy-forms==1.11.1 # https://github.com/django-crispy-forms/django-crispy-forms … -
Django request is slow but sql seem to be fast, need advice on how to debug
Django admin pages take very long time to load, debugged using django-debug-toolbar. It shows the request is taking very long time However, the sql queries seem to fast What exactly does this mean? Is the time spent on processing and returning the request but not on the sql execution? Appreciate any advice on how to debug this further. -
Django render() and redirect() produce unintended url
I'm sure I'm not understanding render() and redirect() correctly, but why does this: return render(request, 'catalog/add.html', {'form': form}) (where the app name is 'catalog') Produce this url: http://127.0.0.1:8000/catalog/add/catalog_add This happens with this function: def catalog_add(request): if request.method == 'POST': form = ArtworkForm(request.POST) if form.is_valid(): form.save() return redirect('catalog') else: form = ArtworkForm() return render(request, 'catalog/add.html', {'form': form}) The GET finds the html page (catalog/add.html) and correctly populates it with an empty form, but the POST results in 'Page not found… The current path, catalog/add/catalog_add, didn’t match any of these.' Both render() and redirect() have the same behavior. -
Problems with custom model user in Django 5.0
I'm pretty new in this world of django apps so I'm still learning how the things works. I'm trying to do a CRUD for my work, so we can register some things like clients info, ours tasks, assistance... etc. In an entuthiastic and young learning spirit I decided to make a custom user model in order to be able to add a profile picture of the users of this app. I was part succeded while I was able to add users and edit its info in the app but some problems came to me later: I can create users from Django admin pannell but then this users can't logging neither the app nor the admin pannell even when I created this with the superuser and staff marks on. I can make a relation between my users and groups of the model auth.Group. To solve 1) or at least to live with it, I found I can create users with the terminal and the command 'createsuperuser' and remove permissions later altought I suspect this 'removing permission' don't work at all. But for the purpose of this project I tought it wold be fine anyway at least for now. I include this … -
Django-how to set the schema of mySql database in settings.py?
I have a database connection in settings.py to mySql database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'options': '-c search_path=xxx', }, 'NAME': 'xxx', 'USER': 'xxx', 'PASSWORD': 'xxx', #fixed 'HOST':'localhost', 'PORT':'3306', } I want to set the schema of this DB. But settings the options like that trigger the following error: connection = Database.connect(**conn_params) TypeError: Connection.__init__() got an unexpected keyword argument 'options' What is triggering the error ? -
Django: Allowing a User being able to see, then update, form of their information
Im trying to create a game tracking app and I wanted the user to be able to see, then update if they wanted, a form that turns on and off features to track. I know this should be quite simple but I cannot for the life of me get the form to populate with the user's data, then be able to update it. Thanks in advance. views.py @login_required(login_url='my-login') def track_pref(request): user = User.objects.get(username=request.user) print(user) if request.method == "POST": print('first if') form = UpdateTrackPrefForm(request.user, request.POST) if form.is_valid(): print('Form Valid') obj = form.save(commit=False) obj.user = user obj.save() return HttpResponseRedirect('/view-games') else: print("else statement") form = UpdateTrackPrefForm() context = {'form': form, 'user': user, } return render(request, 'gametracker_app/track-preference.html', context=context) forms.py class UpdateTrackPrefForm(forms.ModelForm): track_cedh = forms.BooleanField(required=False) track_wincon = forms.BooleanField(required=False) track_tournament = forms.BooleanField(required=False) track_medium = forms.BooleanField(required=False) class Meta: model = TrackPref fields = {'track_cedh', 'track_wincon', 'track_tournament', 'track_medium', } models.py class TrackPref(models.Model): track_cedh = models.BooleanField(default=True) track_wincon = models.BooleanField(default=True) track_tournament = models.BooleanField(default=True) track_medium = models.BooleanField(default=True) track_note = models.BooleanField(default=True) user = models.ForeignKey(User, max_length=100, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.user) html <div class="container shadow-md p-5 form-layout"> <h1 class="">Update Tracking</h1> <form action="" method="POST" autocomplete="off"> {% csrf_token %} {{ user }} <br> {{ form.track_cedh|as_crispy_field }} {{ form.track_wincon|as_crispy_field }} {{ form.track_tournament|as_crispy_field }} {{ form.track_medium|as_crispy_field … -
How do I deploy Wagtail CMS to Ionos Standard Web Hosting
I have tried to deploy Wagtail CMS to Ionos Standard hosting using the instructions at How can I deploy Django App to 1and1 (ionos) but I am just getting an internal server error. Any ideas how I can go about doing this? I have the following in wavecruiseclub/cgi-bin/application.fcgi: # -*- coding: UTF-8 -*- import os import sys import traceback home = '(htdocs location)/htdocs/wavecruiseclub' try: project = os.path.join(home, 'wavecruiseclub') # Add a custom Python path. sys.path.insert(0, project) # Switch to the directory of your project. os.chdir(project) # Set the DJANGO_SETTINGS_MODULE environment variable. os.environ['DJANGO_SETTINGS_MODULE'] = "wavecruiseclub.settings" from django_fastcgi.servers.fastcgi import runfastcgi from django.core.servers.basehttp import get_internal_wsgi_application wsgi_application = get_internal_wsgi_application() runfastcgi(wsgi_application, method="prefork", daemonize="false", minspare=1, maxspare=1, maxchildren=1) except: traceback.print_exc(stdout) with open(os.path.join(home, 'tmp/error.log'), 'w') as fp: traceback.print_exc(file = fp) I also have set up the .bashrc, .bash_profile and .htaccess files as detailed in the instructions. -
Specifying large polygons in Django GEOS
I am getting results I don't understand when creating or combining polygons to cover most of the globe. If I use one polygon, GEOS assumes the shortest boundary between coordinates. So the following specifies a 0.2° wide shape, not a 359.8° wide shape: from django.contrib.gis.geos import MultiPolygon, Polygon Polygon([(-179.99, -85), (-179.99, 85), (179.99, 85), (179.99, -85), (-179.99, -85)], srid=4326) So I create two polygons, so that each boundary is less than 180°, and combine in a multi-polygon: west = Polygon(((0, 85), (-179, 85), (-179, -85), (0, -85), (0, 85)), srid=4326) east = Polygon(((0, 85), (179, 85), (179, -85), (0, -85), (0, 85)), srid=4326) big = MultiPolygon(east, west) feature.geography = big feature.save() But I don't get any matches in the east: from django.contrib.gis.geos import Point queryset.filter(feature__geography__intersects=Point(-2.5, 2.5, srid=4326)) # match queryset.filter(feature__geography__intersects=Point(-2.5, -2.5, srid=4326)) # match queryset.filter(feature__geography__intersects=Point(2.5, -2.5, srid=4326)) # no match queryset.filter(feature__geography__intersects=Point(2.5, 2.5, srid=4326)) # no match If I just search on east, ie, feature.geography = east, all four of the above queries match. If I split the globe into four zones along the equator like so: northwest = Polygon(((0, 0), (0, 85), (-179, 85), (-179, 0), (0, 0)), srid=4326) northeast = Polygon(((0, 0), (0, 85), (179, 85), (179, 0), (0, … -
Django modification of UserCreationForm
My problem is that I am trying to modify the Django default UserCreationForm and its default messages, but it does not work. I also heard that some of the checks and initial messages are defined separately and should be customized separately, but I did not find a lot on that. I tried to search around, but most of what I found was either old and not working for current django version or did just modify the fields and not the error messages. I am importing the UserCreationForm in forms.py like this: from django.contrib.auth.forms import UserCreationForm And then I tried to modify it like this: The fields and everything is completely functional just the messages are still the default and not the custom I was trying to set. class UserSignUpForm(UserCreationForm): username = forms.CharField(label="custom", error_messages={'required': 'custom.', 'unique': 'custom.'}) password1 = forms.CharField(label="custom", widget=forms.PasswordInput, error_messages={'required': 'custom.'}) password2 = forms.CharField(label="Potvrďte custom", widget=forms.PasswordInput, error_messages={'required': 'custom.', 'password_mismatch': 'custom.'}) class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields error_messages = { 'password_mismatch': {"password_mismatch": "custom"}, 'password_too_short': {"password_too_short": "custom"}, 'password_common': {"password_common": "custom"}, 'password_entirely_numeric': {"password_entirely_numeric": "custom"}, } If someone knows how to solve this, please let me know. I would appreciate any feedback. -
Django DRF how do I display not user: 1, but user_id: 1 when sending serialize.data
I came from FastAPI and Laravel and I'm more used to seeing the foreign key id as user_id rather than just user and the like, how can this be done? -
Can't send json reponse in requests mock
I'm looking for a way to test a function called fetch_options that basically renders a returned JSONResponse from an internal API. My approach to this test is to mock requests because the internal API is located in another app which has already tested in a different test suite. I've got a gut feeling that the function is properly patched with the mock but for some reason my render call can't get the response data, I might be wrong about this though. planner/views/meals.py def fetch_options(request, meal, field): if field == "ingredients": index = 1 else: index = 0 try: response = requests.get("log/api/send_" + field) #Trying to mock requests here, request fetches from /log/views/api.py except ConnectionError: requests.raise_from_exception() else: return render(request, {"meal": meal, "options": list(response)[index]}) # throws list index out range in tests /log/views/api.py def send_data(request, option): match option: case "ingredients": data = Log.objects.first().recipe_ingredients case "areas": data = Log.objects.first().recipe_area case "categories": data = Log.objects.first().recipe_categories case "activities": data = Log.objects.first().activities response = JsonResponse(data, status=200, safe=False) return response planner/tests/test_meals_view.py from unittest import MagicMock, patch @patch("planner.views.meals.requests") def test_fetch_options(self, mock_requests): mock_response = MagicMock() mock_response.status_code = 200 mock_response.json_data = [{"id": "357", "strIngredient": "Orange"}] mock_requests.get.return_value = mock_response self.assertContains( fetch_options("request", "breakfast", "ingredients"), status_code=200 ) Can anyone tell me what I'm … -
My Django website (hosted on EC2) is unable to connect with my newly purchased domain (Namecheap) via Rout53 DNS
I have a basic Django website hosted on EC2. It is accessabile over the internet when I use the ipaddress. But I want to use my newly purchased domain example.net (purchased from Namecheap). I configured Rout53 for DNS services. When I try to access my website using example.net it doesn't do anything and gives below error on browser: "This site can’t be reached example.net refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED" When I checked the logs on my EC2 server, it does not show any log if I hit example.net on browser but it shows logs when I hit "ip address". I performed all below checks and all is working fine as expected: DNS Records: Verify DNS records in Route 53. - I checked both A and CNAME record and it is correct Security Groups: Confirm security group rules allow HTTP and HTTPS traffic. - Both HTTP and HTTPS inbound rules are open for all. Verify ALLOWED_HOSTS in Django - This is how my ALLOWED_HOSTS looks like in my Django settings.py ['my EC2 elastic ip', 'example.net'] Firewall Settings: Confirm ufw is inactive or appropriately configured. - I don't have any firewall configured Domain … -
RelatedObjectDoesNotExist when trying to count number of objects in a Query Set
I know that this error is not unique to me. I have come across many posts asking what the error is and how to fix it. One of the answers I saw was to use hasattr on the returned objects in a for loop before you try to get the attribute of the object. The problem is, is that I actually want to count() on the QuerySet. I saw some other post use some Django model aggregate function inside of the query, but I don't think that is appropriate or necessary here. The query should be literally as easy as: font_count = Fonts.objects.filter(origin=location, font_name=font_name).count() but it says: my_app.models.Fonts.origin.RelatedObjectDoesNotExist: Fonts has no origin. Seems straight forward enough - I'll just open the interactive django shell and make sure that I can't get the origin of the Fonts already loaded into the DB... Well, what do you know?! I can access every origin of every font that I have loaded! What is this garbage?! I am on Django version "4.1.dev20211216191317" and python 3.9. origin is a foreign key and font_name is a text field. Thank you :) -
How do I stop field deleting when updating in Django?
I have a form update page. I had originally just been using date fields, but was asked by a user to include a date picker, so I moved to the code below. Now each time I update a date field (say payment 3 date), it updates ok, but it also deletes the other date fields. Any ideas as to why? I'm new to the DateInput() widgets. In views.py: def ParticipantPayments(request, pk): page_heading = "Update Participant's Payments" order = Order.objects.get(pk=pk) payment = ParticipantPayment.objects.get(customer=order.customer) customer = int(order.customer.id) firstname = payment.customer.first_name lastname = payment.customer.last_name form = UpdatePaymentForm(instance=payment) if request.method == 'POST': form = UpdatePaymentForm(request.POST, request.FILES, instance=payment) if form.is_valid(): form.save() messages.info(request, 'Your Form has been successfully submitted. ') return redirect('finance_participants') context = {'form':form,'customer':customer,'page_heading': page_heading, 'order':order, 'firstname':firstname, 'lastname':lastname} return render(request, 'accounts/part_payments.html', context) In models.py file: class ParticipantPayment(models.Model): #other code not relevant customer = models.ForeignKey(Customer, on_delete= models.CASCADE, null = True) fee = models.IntegerField(verbose_name = "Registration Fee", blank=False, default = 750) currency = models.CharField(verbose_name = "Currency", max_length=10, null=True, choices=MONEY,default='GBP') crowd_fund = models.DecimalField(verbose_name = "Crowd Fund Amount", max_digits=5,decimal_places=2, default = 0) ir_discount = models.DecimalField(verbose_name = "Euro Discount Amount", max_digits=5,decimal_places=2, default = 0) bursary = models.DecimalField(verbose_name = "Bursary Amount", max_digits=5,decimal_places=2, default = 0) payment_1_amount = models.DecimalField(max_digits=5, decimal_places=2, default = … -
AWS AppRunner timeout in a Docker image using Django / Gunicorn
I need help with deploy of Docker image (from ECR) where I use Django and Gunicorn. Gunicorn always leaves a "Critical - Timeout" log and apparently the code is never executed. I have already validated that the network has no problems regarding outgoing and incoming connections (use a Netcat image). My Dockerfile has the following: # Use the official Python image # https://hub.docker.com/_/python FROM python:3.7-slim # Needed to capture stderr output # https://github.com/bottlepy/bottle/issues/1130#issuecomment-478096704 # https://stackoverflow.com/a/59812588/109102 ENV PYTHONUNBUFFERED=1 # Set the working directory in the container WORKDIR /app # Intall system level dependencies RUN apt-get update && apt-get install -y \ git \ g++ \ gcc \ gettext \ libxmlsec1-dev \ libxmlsec1-openssl \ && apt-get clean \ && rm -rf /var/lib/apt/lists/\* # Copy the dependencies file to the working directory COPY requirements.txt . # Install dependencies RUN pip install --no-cache-dir -r requirements.txt # Copy the content of the local src directory to the working directory COPY . . # Expose port 8000 to the outside world EXPOSE 8000 CMD ["gunicorn", "MyProject.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "3", "--timeout", "120", "--log-level", "debug"] The health check is successful when configured as TCP but when I configure it as HTTP it fails because it returns timeout. … -
Use of CSRF_COOKIE_MASKED setting while upgrading django version to 4.1?
I am upgrading django version from 4.0 to 4.1, and in the release notes it says: CsrfViewMiddleware no longer masks the CSRF cookie like it does the CSRF token in the DOM. And it gives a setting as well called CSRF_COOKIE_MASKED for transition: The new CSRF_COOKIE_MASKED transitional setting allows specifying whether to mask the CSRF cookie. My question is how to decide whether to use this CSRF_COOKIE_MASKED setting or not while upgrading to 4.1? Also, what kind of testing can I do to verify such changes? -
Trying to deploy Django API to Azure Web app
Currently trying to deploy my Django backend on to Azure. The project runs locally no problem. It also builds and deploys fine on Azure but when I visit the default domain I get a 404 not found. At first I though the issue to be around the settings module as I have 2 depending on local or if its run on Azure like is shown in this Azure tutorial with the code here in the settings.py and production.py files but it seems to be working. I have tried different setups in the production.py and including adding all the modules there but it has no effect. The logs on Azure don't return any errors only a 404 error when I try to access the site. Could the issue have something to do with how I set up the URLS? The api Url look like this from django.urls import path # from .views import * from . import views urlpatterns = [ path("posts/", views.PostsListCreate.as_view(), name="post-view-create"), path("replies/", views.RepliesListCreate.as_view(), name="reply-view-create") ] While the project urls look like this below from django.urls import path, include from django.contrib import admin urlpatterns = [ path('', include("api.urls")), path('admin/', admin.site.urls), ] Here are my views as well from rest_framework … -
How to do a commit from digitalOcean periodically for saving data during the deployment into my django project
I have deploy a django project on digital ocean, the project mainly save documents like xlsx and csv, but while the web app is deploy users send documents to the platform, my question is how could I keep those documents saved aside of downloading one by one from the the admin panel of Django, or how could be the approach for dealing with that? I was thinking in creating a template for downloading all the data with one click, and then do a commit to the repository with that data that I downloaded previously, and digital ocean would take all the repository and make a redeploy, but the main dificulty woulb be that If I do that, I would need to do that manually