Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Guest checkout business logic for server/database with Stripe
I am making an a simple app which allows users to post ads to the website for a fee, as in pay per post. No account is required, it is in essence a guest checkout by default. The issue I am dealing with is the order and best way to implement the business logic on the server side. My flow is as follows: (Front end) User fills out a form with ad details (Front end) User hits submit (Back end) Post request is processed, new database entry is created (Back end) User is redirected to Stripe checkout Payment fails or succeeds Notice how in this flow I create an object/entry in my database before any payment has been made. This already feels wrong because I feel the entry shouldn't exist unless it has been paid for. Because spammer could in theory fill my database with endless entries by filling the form and not completing payment. So if Stripe payment fails in step 5, I have a choice: delete the entry, or return the user to the form prefilled. Clearly, the later is the better option, however if the user never finishes or fixes the payment I will still have a … -
Python Request save cookie response in browser
i have a django web app that use request to post to my gofiber api in response it get a session cookie i need that session cookie in my js fetch in the frontend but my request does not set the cookie in the browser def login(request): email = "" password = "" if request.method == 'POST': session = requests.Session() email = request.POST['email_test'] password = request.POST['password'] email = "test@test.com" password = "Test" url = "http://localhost:8006/auth/login" myobj = {'email': email, "password": password} x = session.post(url, json=myobj) if x.status_code == 200: print(x.cookies) session_cookies = dict(x.cookies) request.session['session_id'] = session_cookies print("Session cookies: " + str(session_cookies)) print(session_cookies) return HttpResponseRedirect(reverse("index")) return HttpResponse("Login failed") return render(request, "webadmin/login.html", { "email": email, "password": password }) print(x.cookies) <RequestsCookieJar[<Cookie kronborg_id=3f6be328-c4e1-4faf-a26b-7b04bc48d006 for localhost.local/>]> print(session_cookies) {'kronborg_id': '3f6be328-c4e1-4faf-a26b-7b04bc48d006'} -
How can I combine three docker images running on different ports to a single docker image
I am trying to create a Docker setup with multiple services including Django, Next.js, and Nginx, where Nginx serves as a reverse proxy for both Django (backend) and Next.js (frontend) applications. I want it to work in such a way that these 3 images are combined into one image for deployment. I have tried to used the multi-staged docker build, but i can't get the configuration right. PROJECT FILES: ./schoolduo-backend/Dockerfile.prod: ########### # BUILDER # ########### # pull official base image FROM python:3.11.4-slim-buster as builder # set work directory WORKDIR /usr/src/schoolduo-backend # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install system dependencies RUN apt-get update && \ apt-get install -y --no-install-recommends gcc # lint RUN pip install --upgrade pip RUN pip install flake8 COPY . /usr/src/schoolduo-backend/ RUN flake8 --exclude env --ignore=E501,F401 . # install python dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/schoolduo-backend/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.11.4-slim-buster # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup --system app && adduser --system --group app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN … -
How to create index condition on boolean field with `is`
When I create a composite index with condition like this class Meta: indexes = [ models.Index( name="test_boolean_idx", fields=["field1", "field2"], condition=Q(field2=False), ), ] the resulting SQL gives CREATE INDEX ON table (field1, field2) WHERE NOT field2; Trouble is this index is not used when filtering by SELECT * FROM table WHERE field2 IS false; only for SELECT * FROM table WHERE field2 = false; I can work around by creating an index manually with WHERE field2 is false Is there a way to create such an index condition with Django models? -
QuerySet when you have an instance
I have a query set which filters a resource based on whether a user has access to it or not: resources = Resource.objects.user_access(user).all() Let's say I have a single resource instance already. Should I then implement a property in my Resource model with the same logic as in my user_acesss Query Set. where I again check if they has access? Like this: resource.has_user_access(user) I suppose I'm conscious of the fact that I'm repeating the logic that checks if the user has access in two places. If I were to put that logic into its own method, I guess it would be a static method in the Resource class. -
Django routing integration with React
We have a Django React project. we are already in the step that when user enters home URL, the app will show(Django response the react project and the home page) and also my React Routing is working(im using React-router-dom for routing). i also know that react routing and Django routings are different and separately. now my problem is if someone(client) enters any other URL than homepage URL for example someone bookmarked a "example.com/shop" and so many others like this that they are not homepage URL, Django side question: how could django has to find out the client dont have react and send the application (my react app)to it in every URL. React side question: for example user in the example.com/shop and Django send the react to client but react how can find out whitch page is the rout we do R&D about the routing but everything is all about the homepage, but there is no other pages or when user bookmarked something else than homepage.... we also watches the courses for integration but they also working on just homepage... -
django.urls.exceptions.NoReverseMatch: 1 pattern(s) tried: ['link/edit/(?P<pk>[0-9]+)/\\Z']
I am trying to use Django with HTMX. My task is to do editable row in the link list with HTMX. When I click the edit button in the row, I am getting NoReverseMatch error. raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'link_update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['link/edit/(?P[0-9]+)/\Z'] [17/Oct/2023 12:54:42] "GET /link/edit/97/ HTTP/1.1" 500 118059 I've tried so many methods on stackoverflow but I didn't figure it out. Here my code is: # urls.py in my project urlpatterns = [ path('', home, name='home'), path('admin/', admin.site.urls), path("user/", include("user_profile.urls", namespace="user")), path("link/", include("link.urls", namespace='link')), ] # urls.py in my link app from django.urls import path from link.views import tag_view, category_view, delete_links, delete_link, get_row_view, LinkUpdateView, LinkyListView app_name = 'link' urlpatterns = [ path('edit/<int:pk>/', LinkUpdateView.as_view(), name='link_update'), path('edit/<int:pk>/get_row_view/', get_row_view, name='get_row_view'), path('tag/<slug:tag_slug>/', tag_view, name='tag_view'), path('category/<slug:category_slug>/', category_view, name='category_view'), path('delete/', delete_links, name='delete_links'), path('delete-item/<int:pk>/', delete_link, name='delete_link'), path('list', LinkyListView.as_view(), name='link_list_view'), ] # views.py in my link app def get_row_view(request, pk): link = LinkUrl.objects.get(pk=pk) context = dict( link=link, ) return render(request, 'link/row.html', context) class LinkUpdateView(UpdateView): model = LinkUrl form_class = LinkModelForm template_name = 'link/edit_link_form.html' def get_success_url(self): return reverse_lazy('link:link_update', kwargs={'pk': self.object.pk}) row.html <tr id="link_list_{{link.pk}}"> <td>{{ link.title }}</td> <td>{{ link.get_full_url }}</td> <td> <span class="p-1 border fs-12 rounded text-light bg-primary"> <a … -
Why can't my terminal use the command "django-admin"(my system is windows and I have added path to the environment)
My terminal and cmd cannot identify the command "django-admin" in any folders. However, when I use the terminal inside pyCharm, it functions normally. Can someone help me with the problem and explain why it happens? Thanks a lot. I have added paths to my environment. enter image description here But it didn't help. -
Uploading file directly to Google Cloud Document AI
I am trying to upload a file directly to Google Cloud Document AI for processing. I am receiving the error 400 Request contains an invalid argument. [field_violations { field: "raw_document.content" description: "Inline document content must be provided." My code: def upload(request): template_name = "upload.html" # if this is a POST request we need to process the form data if request.method == "POST": # create a form instance and populate it with data from the request: form = UploadReceiptForm(request.POST, request.FILES) if form.is_valid: docai_client = documentai.DocumentProcessorServiceClient( client_options=ClientOptions( api_endpoint=globals.GOOGLE_CLOUD_DOCUMENT_AI_ENDPOINT ) ) # The full resource name of the processor version, e.g.: # `projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}` name = docai_client.processor_version_path( globals.GOOGLE_CLOUD_PROJECT_ID, globals.GOOGLE_CLOUD_DEFAULT_LOCATION, globals.GOOGLE_CLOUD_DEFAULT_PROCESSOR_ID, globals.GOOGLE_CLOUD_DEFAULT_PROCESSOR_VERSION_ID ) # Configure the process request image_content = request.FILES["file"].read() request = documentai.ProcessRequest( name=name, raw_document=documentai.RawDocument(content=image_content, mime_type="image/jpeg"), ) result = docai_client.process_document(request=request) # redirect to a new URL: return HttpResponseRedirect("/upload/") # if a GET (or any other method) we'll create a blank form else: form = UploadReceiptForm() return render(request,template_name, {"form": form}) Thanks in advance for the help! -
how to make query in django pytest test user
I have a django code which is for reset password and if user is authenticated the process goes on as change password. I write a test in pytest for this code, and i use a test user to auth and check change password stage, in code for process we need user national id and when user is already online we take national id from profile. so is provided national id in test user as well but the problem is that it's not wrking and my test user not return national id. does anybody has any idea whats problem? andis this any oher way to make test user for this test. views.py @method_decorator(csrf_protect, name='dispatch') class ResetPassword(APIView): permission_classes = (permissions.AllowAny, ) try: # read input nid = request.data.get('nationalId') #....take more input to conside stage based on them .... if not request.user.is_anonymous and request.user.is_authenticated: user = request.user nid = user.profile.identity_number tests.py @pytest.fixture def test_user_nid(): user = User.objects.create_user( username="8835246563", password="upass123", ) profile = Profile.objects.update(user=user, identity_number="8835246563") return user @pytest.mark.django_db class Test: def test_change_password_stages(self, api_client, test_user_nid): api_client.force_authenticate(user=test_user_nid) print("User ID:", test_user_nid2.id) print("User Profile Identity Number:", test_user_nid2.profile.identity_number) data = { "tfaCode": 12345 } response = api_client.post(self.url, data, format='json') # assert response.status_code == status.HTTP_200_OK response_data = response.json() print(">>>>", response_data) … -
Monthly Celery Beat task also runs after celery restart
I have a task that is set to run on the first day of every month at 05:00 using celery beat. It has been set as follows in settings.py: CELERY_BEAT_SCHEDULE = { 'generate_monthly_reports': { 'task': 'api.tasks_reports.generate_monthly_reports', 'schedule': crontab(minute=0, hour=5, day_of_month=1) }, } This works well and runs reliably. However, I have recently discovered that it is also run whenever Celery is restarted, e.g. when a server code update is made and celery restarted via supervisor. I am using Celery 5.2.6, Python 3.8 and Django 4.0.4. How can I prevent this task running when Celery is restarted please? -
Deploy python django project on cyberpanel at hostinger using openlitespeed
I am trying to Deploy python django project on cyberpanel at hostinger using openlitespeed. I have setup all things but i am facing the 503, service unavailable error, My WSGI Script is runnig fine when i test it alone in a different directory. docRoot $VH_ROOT/public_html vhDomain $VH_NAME vhAliases www.$VH_NAME adminEmails aristonvillagepizza@gmail.com enableGzip 1 enableIpGeo 1 index { useServer 0 indexFiles index.php, index.html } errorlog $VH_ROOT/logs/$VH_NAME.error_log { useServer 0 logLevel WARN rollingSize 10M } accesslog $VH_ROOT/logs/$VH_NAME.access_log { useServer 0 logFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" logHeaders 5 rollingSize 10M keepDays 10 compressArchive 1 } scripthandler { add lsapi:arist7587 php } extprocessor arist7587 { type lsapi address UDS://tmp/lshttpd/arist7587.sock maxConns 10 env LSAPI_CHILDREN=10 initTimeout 600 retryTimeout 0 persistConn 1 pcKeepAliveTimeout 1 respBuffer 0 autoStart 1 path /usr/local/lsws/lsphp81/bin/lsphp extUser arist7587 extGroup arist7587 memSoftLimit 2047M memHardLimit 2047M procSoftLimit 400 procHardLimit 500 } phpIniOverride { } module cache { storagePath /usr/local/lsws/cachedata/$VH_NAME } rewrite { enable 1 autoLoadHtaccess 1 } context /.well-known/acme-challenge { location /usr/local/lsws/Example/html/.well-known/acme-challenge allowBrowse 1 rewrite { enable 0 } addDefaultCharset off phpIniOverride { } } vhssl { keyFile /etc/letsencrypt/live/aristonvillagepizza.uk/privkey.pem certFile /etc/letsencrypt/live/aristonvillagepizza.uk/fullchain.pem certChain 1 sslProtocol 24 enableECDHE 1 renegProtection 1 sslSessionCache 1 enableSpdy 15 enableStapling 1 ocspRespMaxAge 86400 } context / … -
Django proxy-model returning wrong ContentType
Let's say we have a model Company and subtype Client like so: class Company(models.Model): name = models.CharField(max_length=100) related_companies = models.ManyToManyField('self', symmetrical=True) is_customer = models.BooleanField(default=False) class ClientManager(Manager): def get_queryset(self): return QuerySet(self.model, using=self._db).filter(is_customer=True) class Client(Company): objects = ClientManager() class Meta: proxy = True Next you go into CLI, create an instance and fetch its content-type from django.contrib.contenttypes.models import ContentType In[38]: company = Company.objects.create(name='test', is_customer=True) In [39]: ContentType.objects.get_for_model(c) Out[39]: <ContentType: contacts | company> That returns the concrete model for the company class. So far so good. Next, according to the docs, the follows should return the Client content-type. In [40]: ContentType.objects.get_for_model(c, for_concrete_model=False) Out[40]: <ContentType: contacts | company> Yet, it does not. I'm still receiving the concrete model Company instead of Customer Do you see my mistake? -
Unable to generate Models using InspectDB
I am using Django inspectdb to auto generate models from an existing mongodb database deployed on the cloud. It was configured using NodeJS and now client wants to change it to Django. In my settings.py, I have: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'dbname', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://string' } } } When I run python manage.py inspectdb, I get the following error for each table: # The error was: 'NoneType' object is not table_name # Unable to inspect table 'table_name' I have the following packages installed in my virtualenv: Package Version ----------------- ------------ asgiref 3.7.2 Django 4.1.12 djongo 1.3.6 dnspython 2.4.2 pip 23.2.1 pymongo 3.12.3 pytz 2023.3.post1 setuptools 68.2.2 sqlparse 0.2.4 typing_extensions 4.8.0 wheel 0.41.2 -
How to add other field which related to many-to-many inline admin on Django
I have Transaction model and Match model which has many-to-many field relationship class Transaction(models.Model): amount = models.DecimalField(max_digits=16, decimal_places=2) card_no = CleanTextField(null=True, blank=True) date = models.DateField() class Match(models.Model): match_at = models.DateTimeField(auto_now_add=True) a_transactions = models.ManyToManyField(Transaction, related_name="a_matches") b_transactions = models.ManyToManyField(Transaction, related_name="b_matches") And also have admin inline and model admin class ATransactionInline(admin.TabularInline): model = Transaction.a_matches.through extra = 0 class BTransactionInline(admin.TabularInline): model = Transaction.b_matches.through extra = 0 class TransactionAdmin(admin.ModelAdmin): list_display = ["amount", "date"] inlines = [ATransactionInline, BTransactionInline] admin.site.register(Transaction, TransactionAdmin) So in Transaction admin page there're display the match object in inlines But I need to display a and b transactions which related to that match object Is there any solution? -
AWS Elastic Beanstalk/Django: How do I get static files to work?
I'm running the newest Django/Python version on Elastic Beanstalk, which I believe runs on Amazon Linux 2023. My Django website is finally deployed (after much blood, sweat and tears). My website correctly displays all HTML/Database info, but it's missing CSS/JS, which are contained within the static files. Some of the elastic beanstalk documentation is a bit deprecated - I tried following this guide: But my configuration contained absolutely no mentions of static files at all. What am I missing, and how can I add them? Thanks. -
How to succesfully make a POST request with JS fetch to a Django REST API
I've been trying unsuccesfully to make a POST request to my API end point, and I always get an error. My setup is a django server with a rest API, and I'm trying to add a reservation to the Booking Model, using fetch. This is the code inside my "onSubmit" js function (when the submit button is clicked): csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value; const formdata = new FormData(form); fetch('/api/booking/', { method: 'POST', headers: { "X-CSRF-Token":csrf, "Content-Type": "application/json" }, credentials: "same-origin", body: formdata }) .then(res => res.json()) .then(data => console.log(data)); models.py class Booking(models.Model): client = models.ForeignKey(User, on_delete=models.CASCADE, null=True) date = models.DateField(null=True) hour = models.SmallIntegerField( null=False, default=12, validators=[ #from 8am to 10pm MaxValueValidator(22), MinValueValidator(8) ], ) class Meta: unique_together = ('date', 'hour') forms.py class BookingForm(ModelForm): class Meta: model = Booking fields = ['date', 'hour', 'client'] views.py (of the api endpoint /api/booking/ class BookingView(generics.ListCreateAPIView): queryset = Booking.objects.all() serializer_class = BookingSerializer So this is the error I get in the Chrome JS console: book:159 POST http://127.0.0.1:8000/api/booking/ 400 (Bad Request) onSubmit @ book:159 book:169 {detail: 'JSON parse error - Expecting value: line 1 column 1 (char 0)'}detail: "JSON parse error - Expecting value: line 1 column 1 (char 0)"[[Prototype]]: Object Any idea what is the problem? -
Unit testing in Python on a function that doesn't have a return value? Is including test-specific code in a function bad practice?
I am writing a mock-up Auction site in Django as part of my self-learning to code. I'm at the point where I'm learning to write tests for my software but I've encountered the problem where a number of my functions used for the web app do not normally return a value. In this one example, I included a boolean parameter for a function that checks whether it is being tested or not. If the parameter is true, it executes a block of code that then does return value that I can then assert with unittest. This is the function: def cleantags(testing=False) -> None: """Executed on listing update, delete, or accept. Purges tags in 'Category' that are no longer used""" unused_tags = Category.objects.filter(Q(listing__isnull=True) | Q(listing__sold=True)) for _tag in unused_tags: _tag.delete() if testing: deleted_tags = [] for _tag in unused_tags: deleted_tags.append(_tag.__str__()) return deleted_tags This is the unittest: def test_tag_deleted(self): """Checking that cleantags() will purge tags in Catergories that don't belong to a listing or to one that has sold.""" # ['Lions','Tigers','Bears','Foo','Bar'] tag_objs = self.generate_tags() self.listing1.tags.add(tag_objs[0]) self.listing1.tags.add(tag_objs[1]) self.listing2.tags.add(tag_objs[2]) self.listing2.sold = True del_tags = listmng.cleantags(True) self.assertQuerySetEqual(del_tags, ['Foo','Bar']) I guess my main question is if this is considered bad coding practice, and if so is … -
Fetch user roles from keycloak using django-allauth
I've managed to get Django to login using Keycloak via openid-connect. I did this with django-allauth. The problem I have now is that I can't figure out how to determine (in Django) which roles a user has (these are defined in Keycloak), in order to give the user appropriate permissions to do things. -
mysqlclient Python Package stop working after Sonoma update
I'm working on a project that uses Django, which connects to a MySQL database, and one of the packages that is used to perform this operation is mysqlclient. But, early this day my laptop was forced to update his OS to Sonoma (I'm working on a Mac), and after that, when I tried to run the project again, it stopped working, and now it throws this error: enter image description here I've tried reinstalling my mysql-client with brew and exporting these variables into my .zshrc file without success. export LDFLAGS="-L/usr/local/opt/mysql-client/lib" export CPPFLAGS="-I/usr/local/opt/mysql-client/include" export PKG_CONFIG_PATH="/usr/local/opt/mysql-client/lib/pkgconfig" Could someone please help me with a solution about this issue? -
Django Orm implementation of connection between unrelated fields by geometry
I am trying to return the closest node locations to a starting node where the 2 database tables have no relation defined between one another. Therefore, I need to find a method to create a full cross join between the tables/subsets of data according to a filter or a facsimile of one. Models: class WaysVerticesPgr(models.Model): objects = CTEManager() id = models.BigAutoField(primary_key=True) cnt = models.IntegerField(blank=True, null=True) chk = models.IntegerField(blank=True, null=True) ein = models.IntegerField(blank=True, null=True) eout = models.IntegerField(blank=True, null=True) the_geom = models.PointField(srid=3857, blank=True, null=True) class Meta: managed = True db_table = 'ways_vertices_pgr' class Pois(models.Model): objects = CTEManager() id = models.BigIntegerField(primary_key=True) name = models.TextField(blank=True, null=True) tags = models.JSONField(blank=True, null=True) geom = models.PointField(srid=3857) class Meta: managed = False db_table = 'pois' Query 1 - q1 - is getting points from the Pois table that fit any criteria, the result I want is the nodes inside the waysverticespgr table of the routing section of the database and return each node reachable in a set time (i.e. within walking distance <= 10 min) with the minimum distance from any of the starting nodes and annotate the resulting nodes with the actual distance. I have working sql for this query but implementing with django orm or django_cte … -
How can I create an "Artist" instance from my Django model when an instance of a User class is created?
I am building a web API in Django and DRF. I have an Artist model that contains different fields and a OneToOnefield to a user which was inherited from an AbstractBaseUser class that contains the following fields: username, email, first_name, last_name, is_artist. I want a situation whereby once a user is created, an instance of the Artist model is also created. Note: I am handling authentication endpoints using Third-Party packages and libraries using Djoser. So I didn't define any views for the user model. How can I achieve what I have described above? Here's my code: The User model: import uuid from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class User(AbstractBaseUser, PermissionsMixin): pkid = models.BigAutoField(primary_key=True, editable=False) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) username = models.CharField(verbose_name=_("Username"), max_length=255, unique=True) first_name = models.CharField(verbose_name=_("First Name"), max_length=50) last_name = models.CharField(verbose_name=_("Last Name"), max_length=50) email = models.EmailField(verbose_name=_("Email Address"), unique=True) is_artist = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "first_name", "last_name", "is_artist"] objects = CustomUserManager() class Meta: verbose_name = _("User") verbose_name_plural = _("Users") def __str__(self): return self.username @property def get_full_name(self): return f"{self.first_name} {self.last_name}" def get_short_name(self): … -
cannot be loaded because running scripts is disabled on this system. For more information,
When I want to active my env on my vs code it says : "cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3" So I go to my administrator powershell and use this command : Set-ExecutionPolicy RemoteSigned now I can activate my env on my code and I have a very simple project with one app and this view : from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("<h1>Hello world</h1>") Now when I run the code it shows the default page of Django (The install worked successfully! Congratulations! You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs.) though it has to show the "hello world" message for me. Now I use vs code debugging terminal and I can see the "hello world" message on my "localhost:8000". I uninstall and install virtualenv and I added to my path but nothing changed. I'm facing this error for 1 week please someone help me I'm expecting when I run the server in env vs code it shows me the "hello world" message which is shown on debugging mode … -
Error While installing GDAL in Github Actions while deploying to Azure
My work flow file is on: push: branches: - main workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Set up Python version uses: actions/setup-python@v2 with: python-version: '3.9' - name: Install Django run: | pip install django - uses: conda-incubator/setup-miniconda@v2 with: activate-environment: SERVIR_AppTemplate environment-file: environment.yml auto-activate-base: false - run: | conda info conda list - run: conda install -c anaconda django - run: python -c "import sys; print(sys.path)" - name: Install GDAL run: | sudo apt-get update sudo apt-get install -y libgdal-dev sudo apt-get install -y python3-dev - name: Install GDAL Python Package run: | pip install GDAL - name: Upload artifact for deployment jobs uses: actions/upload-artifact@v2 with: name: python-app path: | . !venv/ deploy: runs-on: ubuntu-latest needs: build environment: name: 'Production' url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: python-app path: . - name: 'Deploy to Azure Web App' uses: azure/webapps-deploy@v2 id: deploy-to-webapp with: app-name: 'EcoDynlab' slot-name: 'Production' publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_ }} I'm getting error while installing gdal Collecting gdal Downloading GDAL-3.7.2.tar.gz (777 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 777.0/777.0 kB 27.6 MB/s eta 0:00:00 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python … -
How to create session based authentication with django_rest_framework?
I have been trying to create a simple login with a react and django. When my user first enters the page there is no csrftoken and sessionid. After filling the credentials and clicking on the Log in button a POST request is sent to /api/login. The request is succesful and the csrftoken and sessionid are stored as cookies and the user is redirected to the main application. In the main application there's a Log out button which sends a POST request to /api/logout which is ought to log out the user and flush the session. However I seem to be unable to access the logout route. The console error from the axios call reads: POST http://localhost:8000/api/user-logout/ 403 (Forbidden) and in the Network tab the response reads: { "detail": "CSRF Failed: Origin checking failed - http://localhost:3000 does not match any trusted origins." } Now I obviously did include the origin http://localhost:3000 to the list CORS_ALLOWED_ORIGINS but nevertheless this error keeps occuring. I want to use the django_rest_framework for the SPA application, but in combination with session based authentication. Basically I was hoping to authenticate each request with the session state when the application is to be used via the browser, but …