Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why this error shows when deploying a django projejct on verce;l
Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt ERROR: Ignored the following versions that require a different python version: 5.0 Requires-Python >=3.10; 5.0.1 Requires-Python >=3.10; 5.0.2 Requires-Python >=3.10; 5.0a1 Requires-Python >=3.10; 5.0b1 Requires-Python >=3.10; 5.0rc1 Requires-Python >=3.10 how do i fix the issue -
How to create a Django decorator that creates a signal for a model?
I want to create a custom decorator in Django that I can put on my model, and it creates a signal with my business logic. The logic is the same for each signal, the only thing changing is the model it is being attached to. I am having trouble understanding how to accomplish this. Given a model such as: class Post(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) title = models.CharField(max_length=100) I ideally would want a functionality with my decorator to put it on my model such as: @custom_signal_decorator() class Post(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) title = models.CharField(max_length=100) And it would create a signal such as this one: @receiver(post_save, sender=sender) def notify_created(sender, instance, created, **kwargs): channel_layer = channels.layers.get_channel_layer() group_name = f'notifications_{instance.company.id}' async_to_sync(channel_layer.group_send)( group_name, { "type": "notify_change", } ) The end goal is tracking changes in real time by sending a notification to the frontend when a new post is created. This all works when creating a signal by hand for each model, but I feel like a decorator would make more sense, to put on models we want to track. Any kind of input to how I would go about implementing this would be helpful, or another way that you think might work … -
Django 5.0.2: TypeError: Cannot filter a query once a slice has been taken
Why is this not working? I get the error "Cannot filter a query once a slice has been taken." What can I do to solve this? class LogbookLastViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = LogbookSerializer permission_classes = [permissions.IsAuthenticated] filterset_fields = ['organizationID'] def get_queryset(self): queryset = Logbook.objects.filter(organizationID='1111').order_by('-created')[:10] return queryset I need something like this: SELECT * FROM logbook WHERE organizationID='1111' ORDER_BY created LIMIT 10; -
Trying to iterate through numbers in a table rather than displayng all the values for each number in each cell
I am currently attempting to make a table which takes the lab number for a sample and returns the 'Value 2' of that number(I know it's a bad name but it's what I'm being made to work with) so far I can retrieve the data when a specific lab number is searched for, however if I just have a list of lab numbers in the table, it either displays as 'None' or it starts listing every lab number in order in each cell, as a dictionary. The code that isn't displaying the data properly: def GetValue2(self, _pageOfWorkflowCases): _resultsDict = {} for row in _pageOfWorkflowCases: LabNumber = row['LABNO'] with connection.cursor() as _cursor: _cursor.execute("{CALL dbo.uspShireXGetValue2(%s)}", [LabNumber]) _results = self.utilities.ConvertCursorListToDict(_cursor) if _results: _resultsDict[LabNumber] = _results.get['VALUE2'] return _resultsDict The code that displays a lab number when it's searched for: def GetValue2(self, _LabNumber): with connection.cursor() as _cursor: _cursor.execute("{CALL dbo.uspShireXGetValue2(%s)}", [_LabNumber]) _results = self.utilities.ConvertCursorListToDict(_cursor) if _results: _results = self.utilities.ConvertCursorListToDict(_cursor) return _results -
Django form fields don't appear in my html render page
i have a problem in my django project. Im quite new and im try to create a base form to create a new item in my database. this is forms.py from django import forms from .models import Progetto class Myprogetto(forms.ModelForm): class Meta: model = Progetto fields = ['nome', 'descrizione', 'data_inizio', 'data_fine'] this is my views.py from django.shortcuts import render,redirect from .models import Progetto from django.http import JsonResponse, HttpResponseRedirect from .forms import Myprogetto def aggiungi_progetto(request): if request.method == "POST": form = Myprogetto(request.POST) if form.is_valid(): nome = form.cleaned_data['nome'] Myprogetto_object=form.save(commit=False) Myprogetto_object.save() return HttpResponseRedirect("/thanks/") else: form = Myprogetto() return render(request, 'lista_progetti.html', {"form": form}) this is my lista_progetti.html <form id="popUpForm" display="none" action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Salva"> </form> the problem is that when i lauch the server the form appear empty with just the button <salva>. I added a screenshot. my form view in html render Anyone can help me? Thank you i tried to use both forms.ModelForm class and forms.Form class but the result is the same. I also try to write a simple form in html using html syntax and the fields appears but then i have problems in django to send the data to database cause it … -
Troubles with postgres while building docker container
I am trying to lauch DJANGO + POSTGRES inside a single container with DOCKERFILE. I have the folowing dockerfile which basicly installs all the python dependencies and postgresql. Then it lauches the script to create db and user (presented below). FROM python WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . RUN apt update && apt -y install postgresql postgresql-contrib RUN service postgresql start && su -c "bash config.db.bash" postgres WORKDIR /app/psql RUN python manage.py makemigrations && python manage.py migrate #Error EXPOSE 8000 CMD service postgresql start && python manage.py runserver 0.0.0.0:8000 Here is the script "config.db.bash" #!/bin/bash psql <<-INPUT CREATE USER docker; ALTER USER docker WITH PASSWORD 'password'; CREATE DATABASE docker; GRANT ALL PRIVILEGES ON DATABASE docker TO docker INPUT requirements.txt asgiref==3.7.2 Django==5.0.2 sqlparse==0.4.4 tzdata==2024.1 psycopg2 Here is the DJANGO`s settings.py -> Database config (psycopg_2 module installed) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "docker", "USER": "docker", "PASSWORD": "password", "HOST": "localhost", "PORT": 5432, } } It works just fine until this line RUN python manage.py makemigrations && python manage.py migrate Then docker says that error occured during this operation. Log basicly says that DJANGO cant connect to postgress DB. > [9/9] RUN python manage.py … -
make a choice list from a field into other field through the Foreign key Django
I have two models connected with foreign key with each other as below : class Service(models.Model): title = models.CharField(max_length=100) counter = models.PositiveIntegerField() def __str__(self) -> str: return f'{self.title}' class Reservation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) turn = models.PositiveIntegerField() def __str__(self) -> str: return f'{self.user}' What I want to do is turn field in Reservation get option choices and choice values are from 1 to service.counter. service is the foreign key here. for example if counter in Service model is 5 the turn field in Reservation would be something like this : turn = models.PositiveIntegerField(choices=[1,2,3,4,5]). for loop won't work obviously :) . Should I create a property field or Meta class ? anyway, How can I change my field like this? Any help will appreciate and grateful. -
Python: Extract year from datetime.datetime.today().date()
I registered a date to system with dates that is in this format: DateRegistered = datetime.datetime.today().date() . So I want to get the number of user that registered this year. I used this: len(Applicant.objects.filter(DateRegistered=datetime.datetime.today().year)) But it returned 0. Is there other way on how to extract the year? -
Redirect error due to context being passed to template - Django
I am working on an e-commerce site using Django. I have encountered a problem which I can't think of a solution. My site processes normal products and custom orders. I have a view to update the quantity of custom orders and a separate view to update the products quantity. I am using a form with some template logic in the URL to decide which URL pattern I need depending if it is a custom order or a product. bag.html <form class="form" action="{% if custom_orders %}{% url 'custom_order_update' item.custom_order.id %}{% else %}{% url 'update_bag' item.product_id %}{% endif %}" method="POST"> {% csrf_token %} <div class="col-12"> <div class="form-group w-100"> <div class="input-group"> <div class="input-group-prepend"> <button class="btn btn-main rounded-0 decrement" id="decrement_{{item.product.id}}" data-product_id="{{ item.product.id }}"> <span class="icon"> <i class="fa-sharp fa-solid fa-less-than"></i> </span> </button> </div> <input class="form-control quantity" type="number" name="quantity" value="{{item.quantity}}" min="1" max="50" id="quantity_{{item.product.id}}" data-product_id="{{ item.product.id }}"> <div class="input-group-append"> <button class="btn btn-main rounded-0 increment" id="increment_{{item.product.id}}" data-product_id="{{ item.product.id }}"> <span class="icon"> <i class="fa-sharp fa-solid fa-greater-than"></i> </span> </button> </div> </div> </div> </div> <button class="btn btn-main btn-sm rounded-0 mt-2"> Update </button> </form> If i add normal products to the bag application and then add a custom order i get a redirect error stating: Reverse for 'custom_order_update' with arguments '('',)' not … -
How can I call a function from within a Javascript fetch event?
I'm trying to call startTimer() from within the Javascript fetch().then() call, but it isn't going through. How can the fetch() see the startTimer() function and execute it? This happens even when I create an empty test() function that simply prints to console, so I know it isn't related to the code within the startTimer() function. <script> $(document).ready(function(){ function startTimer(duration, display) { var timer = duration, minutes, seconds; const interval = setInterval(function () { minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); // minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) { clearInterval(interval); } }, 1000); } }); const form = document.querySelector('#data'); form.addEventListener('submit', (event) => { event.preventDefault(); var subject = $("#subject").val(); var sender = $("#sender").val(); var email = $("#email").val(); fetch('', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ 'csrfmiddlewaretoken': document.querySelector('[name=csrfmiddlewaretoken]').value, 'subject': subject, 'sender': sender, 'email': email }) }) .then(response => response.json()) .then(data => { const filename = data.filename; const email = data.email; startTimer(60, document.querySelector('#timer')); var msg = `Your ${filename} was sent successfully to ${email}!`; alert(msg); }) .catch(error => { … -
Django 5: best practice way to creating an AJAX registration form via UserCreationForm
As simple as it sounds, what is the effective way to creating a user registration: forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user HTML - index.html: <div class="container"> <form method="post" action="{% url 'base_app:register' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Register</button> </form> </div> HTML - register.html: {% block content %} <div class="container"> <h2>Register</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary" action="">Register</button> </form> <a href="{% url 'base_app:index' %}">Already have an account? Log in here.</a> </div> {% endblock %} views.py: class RegisterView(TemplateView): template_name = 'base_app/register.html' form_class = RegisterForm success_url = reverse_lazy('/mvp/') # Update this to your actual success URL def form_valid(self, form): form.save() return super().form_valid(form) def get(self, request, *args, **kwargs): form = RegisterForm() return render(request, self.template_name, {'form': form}) urls.py: path('register/', views.RegisterView.as_view(), name='register'), I get the following error: [29/Feb/2024 23:14:08] "POST /register/ HTTP/1.1" 405 0 -
Slides Transition using Javascript and Python
I have a database table with images and I want to display it using slides. The problem I encountered here is that it only shows one image and then just fades away. How can I display the other images too? views.py def dashboard(request): image = Events.objects.all() return render(request, 'dashboard-events.html', {'image': image}) dashboard-events.html <div class="slider" role="listbox"> <div class="slider-inner"> {% for slides in image %} <div class="slides {% if forloop.first %} active{% endif %} fade"> <img src="{{ slides.image.url }}"> <div class="slide-caption"> {{ slides.title }} </div> </div> {% endfor %} </div> <div class="slider-buttons"> <button class="prev" type="button" onclick="plusSlides(-1)"> <button class="next" type="button" onclick="plusSlides(1)"> </div> </div> script var timer; var slideIndex = 1; showSlides(slideIndex); function plusSlides(n) { showSlides(slideIndex += n); } var slideIndex = 0; showSlides(); function showSlides() { var i; var slides = document.getElementsByClassName("slides"); for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } slideIndex++; if (slideIndex > slides.length) {slideIndex = 1} slides[slideIndex-1].style.display = "block"; clearTimeout(timer); timer = setTimeout(() => plusSlides(1), 2000); } -
Getting error on Vercel while trying to deploy Django
Hello everyone, I build my django project and tried to deploy it in vercel. but I get this error message in vercel. my python version = 3.10.0 this is the error code on vercel [02:35:58.935] Running build in Washington, D.C., USA (East) – iad1 [02:35:59.090] Cloning github.com/LetcodeitwithDave/BookHaven (Branch: master, Commit: e6ac0c7) [02:35:59.101] Skipping build cache, deployment was triggered without cache. [02:36:00.037] Cloning completed: 946.92ms [02:36:00.592] Running "vercel build" [02:36:01.084] Vercel CLI 33.5.3 [02:36:01.311] WARN! Due to `builds` existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings [02:36:02.677] Collecting asgiref==3.7.2 (from -r requirements.txt (line 1)) [02:36:02.711] Downloading asgiref-3.7.2-py3-none-any.whl.metadata (9.2 kB) [02:36:02.741] Collecting certifi==2024.2.2 (from -r requirements.txt (line 2)) [02:36:02.746] Downloading certifi-2024.2.2-py3-none-any.whl.metadata (2.2 kB) [02:36:02.841] Collecting charset-normalizer==3.3.2 (from -r requirements.txt (line 3)) [02:36:02.846] Downloading charset_normalizer-3.3.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (33 kB) [02:36:02.866] Collecting dj-database-url==2.1.0 (from -r requirements.txt (line 4)) [02:36:02.901] Downloading dj_database_url-2.1.0-py3-none-any.whl.metadata (11 kB) [02:36:03.002] Collecting Django==4.2.10 (from -r requirements.txt (line 5)) [02:36:03.018] Downloading Django-4.2.10-py3-none-any.whl.metadata (4.1 kB) [02:36:03.039] Collecting django-browser-reload==1.12.1 (from -r requirements.txt (line 6)) [02:36:03.049] Downloading django_browser_reload-1.12.1-py3-none-any.whl.metadata (9.8 kB) [02:36:03.101] Collecting django-cors-headers==4.3.1 (from -r requirements.txt (line 7)) [02:36:03.106] Downloading django_cors_headers-4.3.1-py3-none-any.whl.metadata (16 kB) [02:36:03.129] Collecting django-environ==0.11.2 (from -r requirements.txt (line 8)) [02:36:03.139] Downloading django_environ-0.11.2-py2.py3-none-any.whl.metadata … -
Is there any order for inheriting PermissionRequiredMixin in Django?
I encountered this problem while following the Django tutorialDjango tutorial 8. I can redirect to the login page when I put PermissionRequiredMixin class first. class AuthorCreate(PermissionRequiredMixin, CreateView): model = Author fields = '__all__' initial = {'date_of_death': '05/01/2018', } permission_required = 'catalog.add_author' result of First But when I put it in second position it doesn't work and goes directly to the page where the permission doesn't allow it. class AuthorCreate(CreateView, PermissionRequiredMixin): result of Second I want to know is whether I should always put the PermissionRequiredMixin class at the first position. And how about LoginRequiredMixin? or what if I inherit both? -
How to update the quantity of a custom order?
I am trying to update the quantity of a custom order in my bag. In a Django e-commerce application. I am getting an error stating: argument of type 'int' is not iterable, however I am wrapping the custom_order_id in a string. I need the bag to be in the format bag = {[{195,2},{187:3}]} def custom_order_update(request, custom_order_id): """ Updates the quantity of custom orders added to the bag""" bag = request.session.get('bag', {}) quantity = int(request.POST.get('quantity')) custom_orders = bag.get('custom_orders', []) for quantity_dict in custom_orders: if str(custom_order_id) in quantity_dict: quantity_dict[str(custom_order_id)] = quantity break bag['custom_orders'] = custom_orders request.session['bag'] = bag return redirect(reverse('view_bag')) -
How to create hierarchical parent/child relationships with specific permissions in an already build Django (DRF) app
I need to build out a data model in an already existing Django app that uses DRF and I am quite new to Django. The rules are as follows: There are ParentOrganizations and ChildOrganizations that Users can belong to. A ParentOrganization can have many ChildOrganizations An app user can can belong to many ChildOrganizations, but all ChildOrganizations they belong to, must belong to the same parent There is a caveat here that internal super users will have access to all parent and child orgs A app user can have different permissions on each ChildOrganization that they belong to. We will use Django Admin to create users and assign them to their parent and child organizations along with the permissions for each child organization A few questions and some code: This app already exists so it seems that I missed the boat on building out the custom user class without some hacky stuff. Does any of the above warrant extending the auth.User? I'm thinking this isn't necessary. Would the built in Django groups and roles be an okay way to accomplish this? I'm worried about getting locked into things as our use cases become more complex. Assuming I build this out … -
Retrieving Single User Data in Django View Returns Multiple Users
i have encountered an issue with retrieving user data in my view. I have implemented a view to retrieve data for a single user using their ID. However, when I make a request to this view, instead of getting data for just the specified user, I receive data for all users in the system. def test_retrieve_custom_user(self): test_user = CustomUser.objects.create( .... ) test_user_id = test_user.id request = self.factory.get(f"/users/{test_user_id}/") force_authenticate(request, user=self.admin_user) response = self.view(request, pk=test_user_id) print(response.data) print(response.data) The print(response.data) statement outputs data for multiple users, even though I expect to retrieve data for only the user with the specified ID (test_user_id). ...[OrderedDict([('id', 6), ('password', 'pbkdf2_sha256$720000$eUORH8514yvMMuVwQ3m19Q$VId/VYtfaFqVu3fDIxDBXpENptb06tsVtH6qWxpsB0Y='), ('last_login', None), ('is_superuser', True), ('username', 'superuser'), ('first_name', ''), ('last_name', ''), ('email', 'superuser@email.com'), ('is_staff', True), ('is_active', True), ('date_joined', '2024-02-29T22:36:57.909754Z'), ('groups', []), ('user_permissions', []), ('address', None), ('phone_number', None)]), OrderedDict([('id', 7), ('password', 'testpassword'), ('last_login', '2024-02-29T00:00:00Z'), ('is_superuser', False), ('username', 'existinguserew123123'), ('first_name', 'Test'), ('last_name', 'User'), ('email', 'test@example.com'), ('is_staff', False), ('is_active', True), ('date_joined', '2024-02-29T00:00:00Z'), ('groups', []), ('user_permissions', []), ('address', 4), ('phone_number', 4)]), OrderedDict([('id', 8), ('password', 'testpassword'), ('last_login', '2024-02-29T00:00:00Z'), ('is_superuser', False), ('username', 'existinguseresadw123123'), ('first_name', 'Test'), ('last_name', 'User'), ('email', 'test@example.com'), ('is_staff', False), ('is_active', True), ('date_joined', '2024-02-29T00:00:00Z'), ('groups', []), ('user_permissions', []), ('address', 4), ('phone_number', 4)])]``` -
Django app taking around 24 seconds to load webpage after retrieving data from PostgreSQL database
I have a Django application where I'm querying a PostgreSQL database using raw SQL queries in my views.py file. Once I retrieve the data, I process it and send it to the index.html file. However, every time I load the webpage, it takes approximately 24 seconds to fully load. Here's an overview of my setup: I have a Django app configured to connect to a PostgreSQL database. In my views.py file, I'm using raw SQL queries to fetch data from the database using Django models. After processing the data, I pass it to the index.html template for rendering. I've added print statements in views.py to measure the time taken to retrieve and process the data. Additionally, I'm tracking the time it takes for the webpage to load using JavaScript in the DOM of index.html. Despite optimizing my SQL queries and processing logic, I'm still experiencing significant delays in webpage loading. I'm seeking guidance on potential reasons for this delay and strategies to improve the loading time of my Django application. Any insights or suggestions would be greatly appreciated. Thank you! -
Dynamic mocking using patch from unittest in Python
I'm going to mock a Python function in unit tests. This is the main function. from api import get_users_from_api def get_users(user_ids): for user_id in user_ids: res = get_users_from_api(user_id) I'm trying to mock get_users_from_api function in the unit test because it's calling the 3rd party api endpoint. This is the test script. @patch("api.get_users_from_api") def test_get_users(self, mock_get_users) user_ids = [1, 2, 3] mock_get_users.return_value = { id: 1, first_name: "John", last_name: "Doe", ... } # mock response get_users(user_ids) # call main function The issue is that I'm getting the same result for all users because I only used one mock as the return value of get_users_from_api. I want to mock different values for every user. How can I do this? -
Why is Django REST Framework APITestCase unable to create the test database which is hosted on ElephantSQL?
I am currently trying to learn how to run tests in Python/Django REST Framework. I've created a database which is stored on ElephantSQL, using their free tier (tiny turtle) plan. I've connected the database successfully and have been able to create tables on there. However, I'm trying to learn unit testing so I'm currentlt trying to use APITestCase to test the register view. My test is written as below: import json from django.contrib.auth.models import User from django.urls import reverse from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase from rest_framework import status from users.serializers.common import RegistrationSerializer, UserSerializer class RegistrationTestCase(APITestCase): def test_registration(self): data = {'username': 'testuser', 'email': 'test@email.com', 'password': 'super_unique_password', 'password_confirmation': 'super_unique_password'} # Add a test user to database response = self.client.post('/api/auth/register/', data) # Test that 201 status is receieved self.assertEqual(response.status_code, status.HTTP_201_CREATED) My databases in settings.py are set up like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('DATABASE_NAME'), 'HOST': env('DATABASE_HOST'), 'PORT': 5432, 'USER': env('DATABASE_USER'), 'PASSWORD': env('DATABASE_PASS'), }, 'test': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('DATABASE_NAME'), 'HOST': env('DATABASE_HOST'), 'PORT': 5432, 'USER': env('DATABASE_USER'), 'PASSWORD': env('DATABASE_PASS'), } } When I run python manage.py test --verbosity=2 I get the following error: Found 1 test(s). Skipping setup of unused database(s): test. Creating test database for alias 'default' … -
How to document server sent-event with drf-spectacular
I am migrating from drf-yasg to drf-spectacular and I am having trouble migrating the documentation for a server sent event / StreamingHttpResponse. This is the code that worked in drf-yasg. How would you write this with drf-spectacular? class EventStreamData(SwaggerAutoSchema): def get_produces(self): return ["text/event-stream"] def get_consumes(self): return ["text/event-stream"] @api_view(["GET"]) @renderer_classes([EventStreamRenderer]) response = StreamingHttpResponse(event_stream(), content_type="text/event-stream") response['Cache-Control'] = 'no-cache' return response swagger_info = extend_schema(methods='GET', auto_schema=EventStreamData, tags=['2. Server Sent Events'], responses={200: openapi.Response( description="text/event-stream", examples={ "text/event-stream": "data: { " "'field1': '', " "'field2': '', " "'field3': '', " "'field4': '', " "}" }) }) data_stream = swagger_info(data_stream) -
Is there a reason to individualize Django class based views?
In a Django tutorial I am watching someone writes: class GetUserProfileView(APIView): def get(self, request, format=None): # user profile get code class UpdateProfileView(APIView): def put(self, request, format=None): # user profile put code whereas to me a beginner it seems to make way more sense to organize it in one view: class ProfileView(APIView): def get(self, request, format=None): # user profile get code def put(self, request, format=None): # user profile put code Is there a reason for organizing them into different views or is the tutorial maker unexperienced? -
NextCloud user_oidc (as RP) with django-oidc-provider (as OP) fails
My goal is to authenticate NextCloud (v.28.0.2) users against my own Django (v.4.2.7) based web service. I decided to integrate two "libraies": OpenID Connect Login (v.5.0.1) and django-oidc-provider (v.0.8.2). Details: Integration starts, "authorize" endpoint seems to work fine but finally (see last line): INFO 2024-02-29 18:25:23,644 basehttp 142 139883821131456 "GET /oidc/authorize?client_id=989432&response_type=code&scope=openid+email+profile&redirect_uri=https%3A%2F%2Farch.stg.leonarski.pl%2Fapps%2Fuser_oidc%2Fcode&claims=%7B%22id_token%22%3A%7B%22email%22%3Anull%2C%22name%22%3Anull%2C%22quota%22%3Anull%2C%22groups%22%3Anull%7D%2C%22userinfo%22%3A%7B%22email%22%3Anull%2C%22name%22%3Anull%2C%22quota%22%3Anull%2C%22groups%22%3Anull%7D%7D&state=JSEINWUTEKPX53VRYGWSM57JG03RXB6L&nonce=S1Q1SVUP854OIAA05HENUOCXPQBSQ12B HTTP/1.0" 302 0 WARNING 2024-02-29 18:25:24,106 basehttp 142 139883821131456 "GET /oidc/token HTTP/1.0" 405 0 I applied default (I think) settings on both sites and expect "happy end". Also I tried with another package on Django site (django-oauth-toolkit v.2.3.0) but found the same error: WARNING 2024-02-29 18:25:24,106 basehttp 142 139883821131456 "GET /oidc/token HTTP/1.0" 405 0 Question: according to resourecs I found, "token" endpoint should be reached with POST method. So why there is a GET request sent from NextCloud? BTW, status code 405 is reasonable here. Finally, as I belive I'm not the first person worldwide trying this kind of integration then I must be wrong somewhere. But who knows where? Regards, Dariusz -
Vue.js (using nginx, Django, + gunicorn) site being served at wrong url: www.myurl.com/static/ instead of www.myurl.com/
I am using Vue.js for the frontend and Django RF for the backend of my project. When developing locally, the project works as intended with the root of the Vue project functioning at localhost:8081/#/ and accessing components like "Example.vue" at localhost:8081/#/example. I am using nginx on an AWS Ubuntu instance to serve my project. After running 'npm run build', my project is served successfully and works with my Django backend as expected, however, only if accessing the project at www.myurl.com/static. When navigating to www.myurl.com, I am served a basic html page that says "My Project is coming soon". I must have created this file at some point but cannot figure out where it lives in ubuntu file system. Ultimately I need to fix whatever I've misconfigured so that navigating to www.myurl.com serves my Vue.js files. enter image description here This is my current Vue file structure. enter image description here This is how my static path is configured with Django's settings.py - I am not sure if this would affect my setup for the Vue files, however, I wanted to include it for reference. enter image description here This is my nginx.conf file This is my sites-available project file which … -
Does Faust Streaming Consumer retry the offset commit if it fails?
After investigating my consumer logs I found out the following error: [ERROR] OffsetCommit failed for group gaming-processor on partition TopicPartition(topic='my_topic', partition=3) with offset OffsetAndMetadata(offset=29426192, metadata=''): UnknownTopicOrPartitionError This error occurred when my kafka broker leader pod on GKE was rotating. I think this error is expected while rebalancing is occurring my question is if the application is going to retry to commit this offset again or will it only commit the next offset in the next commit wave? Additionally I would like to know if this can cause the consumer to re-read older messages that were already consumed or to lose any message that wasn't yet consumed.