Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to pull Google Reviews with Python/Django, failed by ChatGpt, Claude and DeepSeek
I have a django app where user sign’s in with google and gives permission to access google business profiles to pull reviews. I store those google tokens in my database. But when I try to pull google reviews, it can not pull. It can not even get google business profile data. I tried Chatgpt, Claude, Deepseek but failed. Here is my django and python code what I tried before. Google sign in code in Django: def google_integration(request, location_id): app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL gb_url = request.GET.get('gb_url') gb_incentive = request.GET.get('gb_incentive') params = f'?location={location_id}&redirect_url={request.META.get("HTTP_REFERER")}' params += f'&gb_url={gb_url}' params += f'&gb_incentive={gb_incentive}' return redirect(app_url + reverse('business:google_integration_from_origin') + params) #@subscribed_business_only def google_integration_from_origin(request): location_id = request.GET.get('location') previous_page = request.GET.get('redirect_url') gb_url = request.GET.get('gb_url') gb_incentive = request.GET.get('gb_incentive') if not location_id: messages.error(request, 'Location not found') return redirect('dashboard:index') app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL flow = Flow.from_client_secrets_file( 'client_secrets.json', scopes=['https://www.googleapis.com/auth/business.manage'], redirect_uri=app_url + reverse('business:google_callback') ) auth_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true', prompt='consent' # Forces Google to show the permission screen again ) request.session['google_auth_state'] = state request.session['location_id'] = location_id request.session['google_callback_redirect_url'] = previous_page or reverse('dashboard:index') request.session['gb_url'] = gb_url request.session['gb_incentive'] = gb_incentive return redirect(auth_url) # @subscribed_business_only def google_callback(request): state = request.session.get('google_auth_state') location_id = request.session.get('location_id') app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL gb_url … -
collaborative plateform Real time cursor problem in web socket
My problem is a cursor position in my project. When the web socket open and at setTimeout send code to the another connection room. then my cursor position and text is not showing currently and my cursor go back. and i am facing experience like gaming ping issues., i am also keep track cursor. My script code is: //This is onmessage if (data.action === "code_update") { if (editor.getValue() !== data.code) { // Prevent redundant updates const cursorPosition = editor.getCursorPosition(); console.log("Cursor: ",cursorPosition) editor.setValue(data.code,-1); // Update without moving cursor to the end editor.moveCursorTo(cursorPosition.row, cursorPosition.column); } } // Send code updates on editor changes (debounced to reduce spam). let debounceTimeout; let lastSentCode = ''; editor.session.on("change", function () { clearTimeout(debounceTimeout); debounceTimeout = setTimeout(() => { const currentCode = editor.getValue(); if (currentCode.trim() !== lastSentCode.trim()) { sendCodeUpdate(currentCode); lastSentCode = currentCode.trim(); // Update the last sent code } },100); }); // Send code updates on the WebSocket async function sendCodeUpdate(code) { const cursorPosition = editor.getCursorPosition(); // Store cursor position await chatSocket.send(JSON.stringify({ action: "code_update", username: username, code: code, cursor_position: cursorPosition, // Send cursor position })); } please check and help me -
how to refer back to the model from utils.py in a Django object
I'm trying to create a field in a django model, that forces a unique value in the model. I'm using utils.py to generate the value. The error I get is: File "/Users/evancutler/PycharmProjects/DjangoProject1/MCARS/utils.py", line 2, in <module> from MCARS.models import Profile ImportError: cannot import name 'Profile' from partially initialized module 'MCARS.models' (most likely due to a circular import) (/Users/evancutler/PycharmProjects/DjangoProject1/MCARS/models.py) Here's my model: class Profile(models.Model): # Managed fields user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) memberid = models.CharField( max_length = 10, blank=True, editable=True, unique=True, default=utils.create_new_ref_number() ) avatar = models.ImageField(upload_to="static/mcars/img/avatars", null=True, blank=True) birthday = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=constants.GENDER_CHOICES, null=True, blank=True) invited = models.BooleanField(default=False) registered = models.BooleanField(default=False) height = models.PositiveSmallIntegerField(null=True, blank=True) phone = models.CharField(max_length=32, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) number = models.CharField(max_length=32, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) zip = models.CharField(max_length=30, null=True, blank=True) here's my utils: import random from MCARS.models import Profile def create_new_ref_number(): not_unique = True while not_unique: unique_ref = random.randint(1000000000, 9999999999) if not Profile.objects.filter(memberid=unique_ref): not_unique = False return str(unique_ref) how do I tell the utils.py to refer back to the model to check if the value is unique and if not, to try again? Thanks! -
Issue with cron django
I am trying implementing django crontab into my django project. Everything works fine except logging, in the docker container folder with logging does not exist. My settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_crontab', 'core', 'crypto', ] CRONJOBS = [ ('* * * * *', 'crypto.management.commands.run_cron_job', '>> /var/log/cron.log 2>&1'), ] Cron task from django.core.management.base import BaseCommand from django.utils.timezone import now import logging logging.basicConfig(filename="/var/log/cron.log", level=logging.INFO) class Command(BaseCommand): def handle(self, *args, **kwargs): logging.info(f"Cron ran at {now()}") self.stdout.write(f"Cron ran at {now()}") Docker compose file version: '3.8' services: db: image: postgres container_name: postgres_server ports: - "5432:5432" networks: - local_network volumes: - db_data:/var/lib/postgresql/data environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} pg_admin: image: dpage/pgadmin4 environment: PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL} PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD} networks: - local_network ports: - "8080:80" depends_on: - db web: working_dir: /app container_name: app image: python ports: - "8000:8000" networks: - local_network command: > bash -c " apt-get update && apt-get install -y cron vim && mkdir -p /var/log && touch /var/log/cron.log && chmod 777 /var/log/cron.log && service cron start && pip install -r requirements_test.txt && pip install -r requirements_dev.txt && python manage.py makemigrations && python manage.py migrate && python manage.py crontab add && python manage.py createsuperuser --noinput && python manage.py runserver 0.0.0.0:8000" volumes: … -
Django Scraper Matching Issue: match_maker Only Returns 4 Members Instead of 150
Question: I'm working on a Django project that uses Scrapy to scrape member profiles from a website. The scraped data is processed by a method called match_maker. However, I'm encountering an issue where match_maker only returns 4 members, despite having 150 members in the database (excluding 3 staff members). Details: Database: Contains 153 members; 3 are staff members, leaving 150 regular members. Profile Types: Each member has a profile_type of either 'Man', 'Woman', 'Trans', or 'Couple'. Issue: In the match_maker method, there's a loop that processes rooms and assigns them to members. A set named used_rooms is used to track assigned rooms to ensure each room is only assigned once. The relevant code snippet is: if room["username"] in used_rooms: continue When this condition is active, only 4 members are returned. If I comment out this check, the method processes all 150 members, but the number of available rooms exceeds one million, which is incorrect. Objective: I need each room to be assigned to only one member, ensuring no more than one member owns a particular room. I'm looking for guidance on how to resolve this issue so that match_maker correctly processes all 150 members without assigning multiple members to the … -
Django Streaming Video / Audio - RangedFileResponse
Folks, For ages I've been using RangedFileResponse to enable streaming (particularly with Safari), but to allow ranged streaming with Django. (Please note, it's been forked quite heavily, the one I've been using is from https://github.com/devmonkey22/django-ranged-fileresponse. Now, I've been always wondering if there was a more up-to-date way to do this, since there hasn't seemed to be a better answer? I just recently started to use django-extensions more fully, and bumped into the Werkzeug extensions when I enabled SSL for the Dev environment. But I also found that Werkzeug can help with the Ranged file response. This is what I came up with, and it seems to be faster than using the django-ranged-fileresponse. Sometimes significantly faster. from werkzeug.http import parse_range_header from django.http import FileResponse, HttpResponseNotAllowed, HttpResponseBadRequest def stream_video(request, fqpn, content_type="video/mp4"): file_size = os.path.getsize(fqpn) if request.method != 'GET': return HttpResponseNotAllowed(['GET']) if request.is_secure(): range_header = request.META.get('HTTPS_RANGE') else: range_header = request.META.get('HTTP_RANGE') ranges = parse_range_header(range_header) if not ranges: return FileResponse(open(fqpn, 'rb')) # For simplicity, handle only single range requests start, end = ranges[0] with open(fqpn, 'rb') as file_to_send: file_to_send.seek(start) data = file_to_send.read(end - start + 1) response = FileResponse(data, content_type='application/octet-stream') response['Content-Length'] = len(data) response['Content-Range'] = f'bytes {start}-{end}/{file_size}' response['Accept-Ranges'] = 'bytes' response.status_code = 206 # Partial … -
Why transition-duration along with transform scale could not be set via js/css? (But could be set via DevTools)
The problem is setting transition-duration along with transform scaling results in transformation with zero duration (although style shows up in DevTools as expected) if being set through css, js or html style. But results correctly if being set manually through browser DevTools (changing aforesaid style in DevTools). The MRE is just: <div style="transform: scale(~times~); transition-duration: ~time~"> sandy </div> Working through Django latest version. In the meantime, opacity trasition-duration works as expected, so the trouble is about scaling. Checked the issue in firefox, edge and chrome Though the MRE works as expected in fiddle -
why request.post only send csrftoken, not my form's field
im new in django and this is my first project. I create a loginform and when I want to use it, It just send csrftoken not my requierd fields this my form: class MyLoginForm(forms.Form): username = forms.CharField(max_length=50) password = forms.CharField(widget=forms.PasswordInput()) and this is my views: def login_view(request): if not request.user.is_authenticated: if request.method == "POST": form = MyLoginForm (request.POST) print(request.POST) if form.is_valid(): print('valid!!!') data = form.cleaned_data username = data["username"] password = data["password"] try: account = Account.objects.get(username=username) except Exception as error: print(error) return HttpResponseRedirect(reverse("login")) if account is not None: if password == account.password: login(request, account) return render(request, "home.html", {"account": account}) else: return HttpResponseRedirect(reverse("login")) else: return HttpResponse(f"<h2>No such a User : {username}</h2>") else: print(form.errors) # Print form errors to debug return HttpResponse("form is not valid") else: form = MyLoginForm(request.POST) return render(request, template_name="login.html", context={"form": form}) else: return HttpResponseRedirect(reverse("home")) and this is my html: <form method="post" action = ""> {% csrf_token %} <div class="form-group"> <label for="username">نام کاربری</label> <input type="text" id="username" name="username" required> </div> <div class="form-group"> <label for="password">کلمه عبور</label> <input type="password" id="password" name="password" required> </div> <button type="submit">ورود</button> </form> and Im getting this: <QueryDict: {'csrfmiddlewaretoken': ['rxjKh3oNsgdRBtT20rT1uVWLw2qOR2oQqjOct9iPhEsnJiHAUVgriiDj3Tg1qoog']}> usernameThis field is required.passwordThis field is required. -
How to store images
I store various image files in my media file in the Django framework and I use MongoDB to store my data, but as far as I understand, storing photos directly in MongoDB is not a preferred method. What path should I follow at this point to get a more efficient result? I thought about using tools like AWS S3, but I'm not sure if this is the right way, and I'm inexperienced in data management. I would appreciate it if you could briefly explain how to do it. -
How to Dockerize a Django and Vite app in a Single docker-compose Setup?
I have a Django project that connected with a Vite app, and I’m trying to set up Docker Compose to run both together. However, I’m facing issues while building and running the containers. I'm using vite for installing the tailwind and everything is working fine without docker, I already configure the django project in docker, but need to configure the frontend vite app which is called webapp, it's in the same directory as django. Goal: Django backend → runs on 8000 Vite frontend → runs on 3000 and connects to Django Both services should run using docker-compose up --build However, when I try to run docker-compose up --build, I get several erros, or even the docker will build without the vite working. Issue: When running docker-compose up --build, I get various errors, including: failed to solve: failed to read dockerfile: open Dockerfile: no such file or directory Vite does not start properly in the container, even if Django works. My file directory: For_Testing_Purpose-1/ django_project ┣ __pycache__ ┣ asgi.py ┣ settings.py ┣ urls.py ┣ wsgi.py ┗ __init__.py homepage ┣ migrations ┣ __pycache__ ┣ admin.py ┣ apps.py ┣ models.py ┣ tests.py ┣ urls.py ┣ views.py ┗ __init__.py templates ┗ home.html webapp ┣ … -
Select2 Drop downs not loading in multi-modals django page
I have an issue with a Django front I'm trying to implement. I'm using select2 to show dropdown menus in which I can search in. The problem is that I have two different modals, each has it's dropdown menus. When I click on the button that shows the first modal, dropdown menus data load and the search bar appears and is functional. However, when I quit the first modal (no page reload) and I click on the button that shows the second modal, the dropdown menus are empty, and the search bar doesn't show. Here the HTML code I use for this page : {% extends 'listings/base.html' %} {% block content %} {% load static %} <script type="text/javascript"> $(document).ready(function () { $('#createCustomerModal').on('shown.bs.modal', function () { console.log("Modal create opened"); $('.django-select2').djangoSelect2('destroy'); $('.django-select2').djangoSelect2({ dropdownParent: $('#createCustomerModal .modal-content') }); }); $('#modifycustomerModal').on('show.bs.modal', function (event) { console.log("Modal modify closed"); var button = $(event.relatedTarget); var affectation_id = button.data('id'); var modal = $(this); $.ajax({ url: "{% url 'customer-update' %}", type: 'GET', data: { 'id': affectation_id }, success: function (data) { modal.find('.modal-body').html(data); $('.django-select2').djangoSelect2('destroy'); $('.django-select2').djangoSelect2({ dropdownParent: $('#modifycustomerModal .modal-content') }); } }) }); }); </script> <div class="d-flex justify-content-between align-items-center mb-3"> <h1>Customer list</h1> </div> <div class="d-flex justify-content-between align-items-center mb-3"> <form method="post" enctype="multipart/form-data"> {% … -
Ubuntu + Apache (mod_wsgi) + Django - HTTPSConnectionPool NewConnectionError - [Errno 111] Connection refused
Environment: Ubuntu 24.04, Apache 2.4 (+ libapache2-mod-wsgi-py3 5.0.0-1build2), Python 3.12 (+ requests 2.32.3), Django Admin 5.1.6 Error: I have connected a Django project through Apache (mod-wsgi) and it is running fine (at 'https mysub.mydom.com/myapp') except the requests.post in the python codes failing with: HTTPSConnectionPool(host='mysub.mydom.com', port=443): Max retries exceeded with url: /myapp/api/v1/endpoint (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7191eb589e50>: Failed to establish a new connection: [Errno 111] Connection refused')) 'https mysub.mydom.com/myapp/api/v1/endpoint' is working (200) from the browser. "Apache Full" is allowed from ufw. mysub.mydom.com.conf (for Apache sites-enabled alongwith mysub.mydom.com-le-ssl.conf generated by certbot): Define wsgi_daemon "mydjango_proc" <VirtualHost *:80> ServerName mysub.mydom.com ServerAdmin webmaster@mydom.com DocumentRoot /home/myuser/my_django/my_project <IfModule mpm_itk_module> AssignUserId myuser www-data </IfModule> ErrorLog /home/myuser/my_django/log/my_project.error.log CustomLog /home/myuser/my_django/log/my_project.access.log common Alias /static /home/myuser/my_django/my_project/static <Directory /home/myuser/my_django/my_project/static> Require all granted </Directory> <Directory /home/myuser/my_django/my_project/my_project> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/myuser/my_django/my_project> Require all granted </Directory> <IfDefine !wsgi_init> WSGIApplicationGroup %{GLOBAL} WSGIProcessGroup %{GLOBAL} WSGIDaemonProcess ${wsgi_daemon} python-home=/home/myuser/my_django/sklp_env python-path=/home/myuser/my_django/my_project user=myuser socket-user=myuser WSGIProcessGroup ${wsgi_daemon} WSGIScriptAlias / /home/myuser/my_django/my_project/my_project/wsgi.py Define wsgi_init 1 </IfDefine> </VirtualHost> The Django location + structure: home |-- myuser |-- my_django (group: www-data) |-- sklp_env `-- my_project (group: www-data) |-- myapp |-- my_project |-- static |-- db.sqlite3 (group: www-data / permission: 664) `-- manage.py Some settings of the project (/home/myuser/my_django/my_project/my_project/settings.py): ... ALLOWED_HOSTS = … -
ModuleNotFoundError: No module named 'app.project' when running pytest on a Django project in GitLab CI
I'm having trouble running my tests with pytest in a Django project on GitLab CI. My project structure looks like this: my-project/ ├── app/ │ └── app/ │ ├── settings.py │ └── (other Django files) ├── project/ │ ├── __init__.py │ ├── models.py │ └── tests/ │ ├── __init__.py │ └── test_models.py └── conftest.py In my test file (project/tests/test_models.py), I import my modules like this: from project.models import User, Course, Lesson, Exercise I also have the following in my pytest configuration (pytest.ini): [pytest] DJANGO_SETTINGS_MODULE = app.app.settings When I run pytest from GitLab CI pipeline: docker --context digitavox compose -f docker-compose.yml exec -T app bash -c 'export DJANGO_SETTINGS_MODULE=app.settings && export PYTHONPATH=$(pwd):$(pwd)/app && pytest -v --collect-only --disable-warnings' I get the following error: ModuleNotFoundError: No module named 'app.project' I have verified that: All necessary init.py files are present. The tests use the import statement from project.models import ... (without the “app.” prefix). The conftest.py file is located at the project root, so the project root should be added to sys.path automatically when pytest runs. My question is: How should I configure the PYTHONPATH or adjust my imports/structure so that pytest can correctly locate my modules when running on GitLab CI? Do I need … -
I'm trying to deploy a python app to azure but it doesn't work even with a quickstart sample app
Here's an article from Microsoft with a quickstart guide for python app at azure. So I'm trying to deploy a python app on azure using free tier but it simply doesn't work. I've tried multiple things already. I've cloned sample project code from here as the article suggests. Then I've tried to run it locally using python 3.12. That version is the latest supported for an azure web app at the moment. It works locally on my pc even though /admin/ doesn't work there, but whatever: at least some page opens successfully. I've ran it via pycharm community with a virtual environment. Then I've tried to upload these folders and files to the site/wwwroot folder: folder: .venv hello_azure quickstartproject static .env.sample db.sqlite3 manage.py requirements.txt Before doing that I've created a web app on free tier, chose python 3.12 and opened public access to the website. In the overview of the app it's running. I've also tried to add as a startup command these: manage.py runserver, site/wwwroot/manage.py runserver, python manage.py runserver, python site/wwwroot/manage.py runserver, but non of that worked. On attempt to open the website it shows this error: :( Application Error If you are the application administrator, you can access … -
Django CSRF Token Suddenly Stopped Working
I've been programming a Django application for over a year now. I got the CSRF token working fine in the beginning and there haven't been any problems since. But now, it's suddenly stopped working, both locally and in my development environment despite pushing no changes to it. Does anyone know why this might be, and how I could fix it? Here is a list of everything I've tried: Going through the list of 5 recommendations given in the error report: Browser is accepting cookies: YES Passing a request to the render method: YES Using {% csrf_token %} inside form tag: YES Using CsrfMiddleWare: YES Form has valid csrf token: YES, because I'd reset the cookies manually Removing mismatched data the following ways: Clearing cached data, cookies, and browsing history Restarting my computer Updating Chrome Using Incognito Mode Clearing user session data before every form submission Using decorators '@ensure_csrf_cookie' and '@csrf_protect' either individually or in combination before my view functions. Used this syntax: from django.views.decorators.csrf import ensure_csrf_cookie from django.views.decorators.csrf import csrf_protect ... @ensure_csrf_cookie @csrf_protect def templateFunc(request): In settings.py, making sure to assign the correct localhost to csrf variables, with and without the port numbers: ALLOWED_HOSTS = ['127.0.0.1', 'localhost', ".awsapprunner.com", "dev.org"] CSRF_COOKIE_DOMAIN … -
Key Error when trying to remove slug from my models
I am getting this error when I run migrations: *old_field = model_state.fields.pop(name) KeyError: 'slug'* I have no reference to a slug apart from in my migrations where I had added it then tried to removed it. I am reluctant to delete any migrations but I cannot see another way of moving past this error. I have found this code, in this file env\Lib\site-packages\django\db\migrations\state.py: def remove_field(self, app_label, model_name, name): model_key = app_label, model_name model_state = self.models[model_key] old_field = model_state.fields.pop(name) if self._relations is not None: self.resolve_model_field_relations(model_key, name, old_field) # Delay rendering of relationships if it's not a relational field. delay = not old_field.is_relation self.reload_model(*model_key, delay=delay) Which is where the error is pointing but I don't think this should be touched. I have tried to run a fake migration for the removal of the slug migration and although that goes through; the next time I ran a migration I got the same error again. I am using a postgres DB. -
what dose clean functions do in model django? NOT IN FORMS
I was reading THIS-SOLUTION and I wonder what dose "clean function" do ? is clean where we should put our checkings ? then I found this picture : enter image description here so we have bunch of clean functions , I just want to know what they do . and is it correct to use "clean" if we want to add a filter which makes sure we wont have more than x object from one model(table)? I think using " def save() " seems more suitable to solve this kind of checking but Im not sure. -
HTMX Form in Django: Errors not updating in the DOM after failed validation
I am using HTMX with Django to submit a contact form without refreshing the page. When the form has errors, my backend correctly returns the contact_messages.html template, but the errors do not appear in the page after the request. I can see the correct response in the Network tab, and contact_messages.html contains the expected validation messages. However, HTMX does not update the div#contact-messages in my contact.html file. Before trying to use HTMX, Django's built-in form validations work perfectly. However, as everyone knows, the process is synchronous, and I want to make it asynchronous with HTMX. This's mi view: class ContactView(FormView): template_name = 'contact/contact.html' form_class = ContactForm success_url = reverse_lazy('contact') def form_valid(self, form): messages.success(self.request, "Your message has been sent. We will be in touch with you as soon as possible.") return redirect(self.success_url + '#contact-section') def form_invalid(self, form): messages.error( self.request, "There were some errors in your submission. Please review the highlighted fields and try again", extra_tags="danger") if self.request.headers.get("HX-Request"): return render(self.request, "contact/contact_messages.html", {"form": form}, content_type="text/html", status=400) return super().form_invalid(form) This's my form in contact.html: <form id="contact-form" method="post" hx-post="{% url 'contact' %}" hx-target="#contact-messages" hx-swap="innerHTML" novalidate> {% csrf_token %} <div id='contact-messages'> {% include 'contact/contact_messages.html' %} </div> <div class="form-group mb-0"> <button class=" btn btn-primary w-100"> <span>Send Message</span> … -
What is best practice in working with Freelancers on Django project? [closed]
I have a website written using Django, Bootstrap5, jQuery. As the project gets increasingly time consuming, I want to let freelance developers contribute. What is best practice in this regard. Is there a practicle method to let developers access the relevant parts of the code, without having to share all of it? I understand, that there is the possibility of extracting modules (i.e. django app) into reusable apps. However, that makes setting it up time consuming, especially if dependencies to other django apps exist. What are suggestions? Are there ressources (tutorial, blogs, books, ...) which would help? -
How to trigger multiple views in Django with one button using HTMX?
I’m working on a Django project where I need to call two different views when clicking a single button using HTMX. Scenario: First, I need to send a POST request to edit a task (edit_positions_tasks view). After the first request completes, I need to send a GET request to create a task (create_position_tasks view). The second request should only execute after the first request is successfully processed. Current Code: <button hx-post="{% url 'hrm_tenant:edit_positions_tasks' task.id %}" hx-target="#task_{{ task.uuid }}" hx-swap="outerHTML" hx-on::after-request="htmx.ajax('GET', '{% url 'hrm_tenant:create_position_tasks' empty_position.id %}', {target: '#task_table', swap: 'beforeend'})" > Update </button> Problem: The first POST request works correctly and updates the task. However, the GET request to create_position_tasks doesn’t seem to fire or execute properly after the first request finishes. What I Need Help With: Is my approach correct for chaining two requests in HTMX? If not, what is the recommended way to ensure the second request only fires after the first one completes successfully? Are there better ways to handle this in HTMX or JavaScript? Any insights would be greatly appreciated! -
Sending large base64 files through RabbitMQ to consume on workers
I'm using RabbitMQ and Celery to process email attachments using the gmail API. In my first celery task it fetches batches of emails with large attachments in base64 strings greater than 25mb per file. The current RabbitMQ default limit is 16mb, but I don't want to raise it because I read a few articles about how keeping the message size small is a better practice. What is the best practice here? While the first task is pulling emails, I want to create multiple other celery workers that processes those files (with OCR and storing it in a database) concurrently to optimize the speed of the process. A few solutions (that I'm not sure if it's a good practice because I'm a newbie) I came up with: Raising the RabbitMQ message size limit Storing the file in memory and referencing that in the second celery task (Not sure if this is a good idea, because my server I'm running is 32gb of ram) In the first celery task that's pulling emails, I can directly upload that to a cloud storage service, and then reference that url to the file in the second celery task. But the downside of that is I … -
Should I Perform Geocoding on the Frontend or Backend in a Django Application?
I'm developing a web application using Django and need to convert user-provided addresses into geographic coordinates (latitude and longitude) using a geocoding service like the Google Maps Geocoding API. I'm trying to determine the best practice for where to handle this geocoding process: Frontend: Collect the address from the user, send it directly to the geocoding API from the client's browser, and then send the obtained coordinates to the Django backend for storage and further processing. Backend: Collect the address from the user via the frontend, send it to the Django backend, perform the geocoding server-side by making a request to the geocoding API, and then store and process the coordinates as needed. I'm trying to determine the best practice for where to handle this geocoding process -
Issues when tryin to deploy using Nginx and Docker?
I’m deploying my backend using Nginx and Docker (containerized DRF app), but I’m encountering an issue when trying to access the admin panel. I get the following error: "403 Forbidden – CSRF verification failed. Request aborted." To fix this, I reviewed my configuration and added some parameters to my settings.py file, ensuring that CSRF_TRUSTED_ORIGINS is pointing to the correct domain but unforthunately didn't fix the problem, any hints ? -
"Cannot query 'admin': Must be 'User' instance"
I’m working on a Django REST Framework project where I have a Cart model, and I want to allow authenticated users to add items to their cart via a POST request. However, I keep getting the following error: ValueError: Cannot query "admin": Must be "User" instance. Here’s the relevant part of my Cart model: class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='carts') album = models.ForeignKey(Album, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) added_at = models.DateTimeField(default=timezone.now) And here’s the CartView where the issue occurs: class CartView(APIView): permission_classes = [IsAuthenticated] def post(self, request): user = User.objects.get(id=request.user.id) # Force correct User instance album_id = request.data.get('album_id') if not album_id: return Response({"error": "Album ID is required"}, status=400) try: album = Album.objects.get(id=album_id) except Album.DoesNotExist: return Response({"error": "Album does not exist"}, status=404) cart_item, created = Cart.objects.get_or_create(user=user, album=album) if not created: cart_item.quantity += 1 cart_item.save() return Response({"message": f"Added {album.title} to cart", "quantity": cart_item.quantity}, status=201) In Postman, I include the Authorization header with a valid token: Authorization: Token fcbb7230bb0595694200e3e6effbe67d1c43fb7c Ensured request.user is properly authenticated. Verified that the token belongs to the correct user in the admin panel. Logged type(request.user) and found it’s not always an instance of User. Explicitly retrieved the User instance using User.objects.get(id=request.user.id). -
How to use django-allauth for Google API?
How is django-allauth implemented to obtain authorization using Oauth2 for a Google API (in my case the Gmail API)? Additionally, I am looking to implement this separately from using django-allauth to have users log in with Google, so I would need to store it separately, and also call it in a view. Thanks!