Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is a good throttling rate limit for drf views to secure endpoints
I have two drf class based views endpoints one for login and one for password reset I want to use throttling to prevent bruteforce related attacks to these two endpoints I found a lot of questions discussing the implementation and the throttling classes but none were talking about what is a good rate limit to protect the endpoints So what are the actual numbers to use? per second or per minute or per hour , what is the actual rate that a user shouldn't pass otherwise it's considered illegal TLDR: What is the number of requests to allow in a period of time to make sure a login api endpoint can't be bruteforced -
fix django login bug
I'm working on a django project, after I finished the code of registration and login feature (serializers and viewsets) I tested theses features, so when the registration feature seems working like a charm, the login feature bug,so when I try login with a registered user credetials I get this error message "detail": "No active account found with the given credentials" I used django rest framework for the logic and rest framewok JWT for token authentication HOw can I fix the bug? I reviewed all the logic of authentication and permission , I axpect to fix the bug so I can login safely -
How to get an object for editing transfer to a form?
I don't know how to get my announcement to insert into the form for editing my model: class Announcement(models.Model): category = models.CharField(choices=professions, blank=False) title = models.CharField(max_length=40, blank=False) slug = models.SlugField(max_length=250, unique_for_date='publish', ) price = models.IntegerField(default=None, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='announcement_work') publish = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=500, blank=False) company = models.CharField(max_length=30, blank=False) experience = models.CharField(choices=Experience, blank=False) address = models.CharField(max_length=30, blank=False) city = models.CharField(max_length=30, blank=False) country = models.CharField(max_length=30, blank=False) Favorites = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Favorites', blank=True) class Meta: ordering = ['-id'] indexes = [ models.Index(fields=['-id']) ] def __str__(self): return self.title def get_absolute_url(self): return reverse('account:announcement_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) tags = TaggableManager() my form class AnnouncementForm(forms.ModelForm): class Meta: model = Announcement fields = ['category', 'title', 'price', 'country', 'city', 'description', 'experience', 'company', 'address', 'tags'] i try write views and url, but see error: django.urls.exceptions.NoReverseMatch: Reverse for 'announcement_edit' with no arguments not found. 1 pattern(s) tried: ['account/(?P<announcement_id>[0-9]+)/edit/\Z'] [26/Mar/2024 22:21:09] "GET /account/2024/3/21/employer-and-user/ HTTP/1.1" 500 154441 django.urls.exceptions.NoReverseMatch: Reverse for 'announcement_edit' with no arguments not found. 1 pattern(s) tried: ['account/(?P[0-9]+)/(?P[0-9]+)/(?P[0-9]+) /(?P[-a-zA-Z0-9_]+)/edit/\Z'] i try transmit data to url : '{% url 'account:announcement_edit' year month day slug %}' i try use include i don't understand how get edit form and i have another one question: how to make favorites announcement without … -
Проблема з порядком urls django
Вітаю! Потрібно ваша допомога. Виникла проблема з url, структура наступна: головний файл проєкта urls.py urlpatterns = [ path('admin/', admin.site.urls), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('shop.urls')), path('', include('informations.urls')), ] shop urls urlpatterns = [ path('', views.index, name="index"), path('contact', views.Contact, name="contact"), path('<str:category_slug>/', views.TireListByCategory, name='category_list'), path('pdf/<int:id>/', views.render_pdf_detail_view, name='test-pdf-view'), path('pdf/category/<str:category_slug>/', views.render_pdf_category_view, name='category_pdf_list'), path('brand/<str:slug>/', views.BrandDetail, name='brand_detail'), path('<str:category_slug>/<str:slug>/', views.TireDetail, name='tire_detail'), path('brands/<str:brand_slug>/<str:slug>/', views.BrandModelDetail, name='brand_model_detail'), ] informations.urls urlpatterns = [ path('blog/', views.page_info_blog, name='page_info_blog'), path('<str:category_info_slug>/', views.category_info_detail, name='category_info_detail'), path('<str:category_info_slug>/<str:page_info_slug>/', views.page_info_detail, name='page_info_detail') ] Перший include('shop.urls') працює добре Другий, помилка 404 Також при заміні місцями, працює тільки перший по списку, другий - помилка 404 Будь ласка, підкажіть про рівні urls. М Міняю місцями, то працю тільки перший по списку. Другий видає помилку 404 -
Python & Django web app - auto emails not sending
I had a web app developed but found the automated emails are not sending. I found the .py file for sending the email, but cannot find another file calling this. filetree showing .py file Is there a standard file to place a call to the send_due_email.py file? If I find that there is nothing calling this file to run, where should the code be placed? I want the emails sent once a week - maybe every sunday -
How to exclude instances with empty querysets in prefetch_related?
I have two models - Project and Contract. They have one-to-many relationship. class Contract(models.Model): project = models.ForeignKey(Project) I get a qs of Project instances with relevant Contract instance(s). projects = Project.objects.filter(active=True).prefetch_related( Prefetch('contract_set', queryset=Contract.objects.filter(**filters), to_attr='contracts') ) But now I need to get Project instances with exact Contract instance by putting Contract guid to filters. filters: Dict = { 'guid': some_guid, } But I receive all Project instances where only one has not empty contracts attr and others Project instances have empty contracts attr. I found such issues: How to exclude rows with empty prefetch_related field Filter prefetch_related empty in django but they do not help me. I tried such options: a) using OuterRef and Exist: projects = Project.objects.filter(**filters_projects).annotate( has_contracts=Exists( Contract.objects.filter(project_id=OuterRef('pk'), **filters_contracts) ) ) projects = projects.filter(has_contracts=True) b) using annotate: projects = ( Project.objects.filter(**filters_projects) .annotate(num_contracts=Count('contract')) .exclude(num_contracts=0) .prefetch_related( Prefetch('contract_set', queryset=Contract.objects.filter(**filters_contracts), to_attr='contracts') ) ) They do not work for me... How can I implement the required functionality? -
Django application hosted in vagrant not available at localhost
I have the Vagrant configuration that used to work some time ago, but now the application is not available at localhost after starting in virtual machine. Vagrant file content: # -*- mode: ruby -*- # vi: set ft=ruby : ENV["LC_ALL"] = "en_US.UTF-8" ENV["VAGRANT_DETECTED_OS"] = ENV["VAGRANT_DETECTED_OS"].to_s + " cygwin" Vagrant.configure("2") do |config| config.vm.box = "generic/rocky8" config.vm.network "forwarded_port", guest: 8080, host: 1234 config.vm.synced_folder ".", "/vagrant", type: "rsync", rsync__auto: true config.vm.provider "virtualbox" do |vb| vb.memory = "1024" end if Vagrant.has_plugin?("vagrant-vbguest") config.vbguest.auto_update = false config.vbguest.no_remote = true end end Django application is started using following command python manage.py runserver 0.0.0.0:8080 When running curl http://0.0.0.0:8080 in the Vagrant machine it returns expected result and Django logs "GET / HTTP/1.1" 200 20766, while in the host machine: curl http://127.0.0.1:1234 curl: (56) Recv failure: Connection was reset Also, web browsers fail to connect returning either ERR_CONNECTION_RESET or ERR_INVALID_HTTP_RESPONSE. Additional thing I checked: vagrant port The forwarded ports for the machine are listed below. Please note that these values may differ from values configured in the Vagrantfile if the provider supports automatic port collision detection and resolution. 22 (guest) => 2222 (host) 8080 (guest) => 1234 (host) I am on Windows 11 and tried a lot of different … -
How can I let a task run all the time on a linux v-server?
I would like to develop a web game. It is based on a database (MySQL) and is intended to run on a Linux server. My question is: Can I write a Python program that I store on the server and that runs nonstop and performs actions on the data in the database? And then run a website on the same server that can then access the data in the database and also carry out actions on it? Later I would also like to create this website as an Android or iOS app. So far I've mainly read up on Django to develop the web game. But it doesn't seem to be 100% suitable for developing the web game with. So which tool would be best suited to develop the game with? -
Dictionary with unknown depth in Python Django
i have following data: [ {'I. Intangible Assets': ['1. Concessions, Licenses']}, {'II. Tangible Assets': [ '1. Land, Buildings and Similar Rights', '2. Machinery and Equipment', {'3. Other Facilities, Operating and Business Equipment': ['Cars', 'Trucks']} ]}, {'III. Financial Assets': ['1. Equity Interests in Affiliated Companies']} ] sourcecode: {% for group in structure %} {% for parent, elements in group.items %} <hr> <b>{{ parent }}</b><br> {% for child in elements %} {{ child }} <br> {% endfor %} {% endfor %} {% endfor %} The code works up to the second level without any problems. However, if there is a third level, this is only displayed as a dictionary. Therefore, the output is "{'3. Other Facilities, Operating and Business Equipment': ['Cars', 'Trucks']}" Iterating over them with for key, val in child do not work. Any ideas? -
django formset management_form null value for id_form-TOTAL_FORMS
I have a form with an inlineformset_factory. When the button to add more forms is clicked I receive the error Uncaught TypeError: totalForms is null $addFormset http://localhost:8000/static/js/site-js.js:21 line 21 of site-js.js totalForms.setAttribute('value', '${formsetNum + 1}'); // Increment the Number of Total Forms in the Management Form Data I see that client_formset.management_form creates the following 4 hidden input fields in my form. <input type="hidden" name="client_set-TOTAL_FORMS" value="1" id="id_client_set-TOTAL_FORMS"> <input type="hidden" name="client_set-INITIAL_FORMS" value="0" id="id_client_set-INITIAL_FORMS"> <input type="hidden" name="client_set-MIN_NUM_FORMS" value="0" id="id_client_set-MIN_NUM_FORMS"> <input type="hidden" name="client_set-MAX_NUM_FORMS" value="1000" id="id_client_set-MAX_NUM_FORMS"> when I log totalForms I receive a null value instead of the value for id_client_set-TOTAL_FORMS. index.html {% load static %} <!DOCTYPE html> <html> <body> {% block body_content %} <form method="post" id="form"> {% csrf_token %} {{ construction_form }} {% if client_formset %} <h3>Clients</h3> {{ client_formset.non_form_errors }} {{ client_formset.management_form }} {% for form in client_formset %} <div class="formset-container {{ client_formset.prefix }}"> <div class="first-name">{{ form.first_name.label }}: {{ form.first_name }}</div> <div class="last-name">{{ form.last_name.label }}: {{ form.last_name }}</div> {% if client_formset.can_delete %} <div class="delete">{{ form.DELETE }} {{ form.DELETE.label }}</div> {% endif %} </div> {% endfor %} {% endif %} <button id="add-formset" type="button">Add Another</button> <input type="submit" value="Save"> </form> {% endblock %} <script type="text/javascript" src="{% static 'js/site-js.js' %}"></script> </body> </html> site-js.js let formsetContainer = document.querySelectorAll('.formset-container'), form … -
How to get data from a form and paste them into template?
I'm trying to make search functionality in my project. There is a form where a person can enter a title of an article and redirect to the page of this article if it exists. But it always gives me "None". It gives me this line in the terminal if I for example enter 'CSS': "GET /search?csrfmiddlewaretoken=yzuY5iPKEJGJgFZE7D9GKoRhSxE2EsUVmVcvJvTuCG6Q2sEBHtiuzUJx2ZPu4fwb&title=CSS HTTP/1.1" 200 1264. What to do? Util.py: import re from django.core.files.base import ContentFile from django.core.files.storage import default_storage def list_entries(): """ Returns a list of all names of encyclopedia entries. """ _, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename) for filename in filenames if filename.endswith(".md"))) def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None Views.py: from django.shortcuts import render, redirect from django import forms from . import util from django.http import HttpResponseRedirect def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, title): return render(request, "encyclopedia/details.html", { … -
Can't display page content in Django
There is an application posts. There is a model: class Post(models.Model): text = models.TextField() pub_date = models.DateTimeField("date published", auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") group = models.ForeignKey(Group, on_delete=models.SET_NULL, related_name="posts", blank=True, null=True) def __str__(self): # выводим текст поста return self.text There is a urls: path('posts/<str:username>/<int:post_id>/', views.post_view, name='post'), There is a views: @login_required def post_edit(request, username, post_id): post = get_object_or_404(Post, pk=post_id, author__username=username) print(post.text) if request.user != post.author: return redirect('post', username=username, post_id=post_id) form = PostForm(request.POST or None, instance=post) if form.is_valid(): form.save() return redirect('post', username=username, post_id=post_id) return render(request, 'post_new.html', {'form': form, 'post': post}) When checking here in Views everything is displayed correctly: print(post.text). However, nothing works on the HTML page? There is a HTML: <main role="main" class="container"> <div class="row"> <div class="col-md-12"> <div class="card mb-3 mt-1 shadow-sm"> <div class="card-body"> <p class="card-text"> <a href="{% url 'profile' user.username %}"> <strong class="d-block text-gray-dark">@{{ post.author.username }}</strong> </a> {{ post.text }} </p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <p>Author: {{ post.author.get_full_name }}</p> <p>ID: {{ post.author.username }}</p> </div> <small class="text-muted">{{ post.pub_date }}</small> </div> </div> </div> </div> </div> </main> What is the problem. Nothing works here? post.pub_date, post.author.get_full_name... Why does this work in context: {% for post in posts %} .... {{post.text}} ... Works through {{ posts.0.author.username }}. But it doesn't work: … -
Connecting CSS in Django project
Please tell me what the error is. After running the python manage.py collectstatic files were generated, the js scripts work, but the css file is not connected. base.html <!doctype html> {% load static %} <html lang="en"> <head> .... <!--Custome CSS--> <link rel="stylesheet" href="{% static 'static/css/style.css' %}"> <title>{% block title %} {% endblock %}</title> </head> Folder: enter image description here settings.py STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / STATIC_URL I tried adding the code from the documentation: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Python & Django web app how to delete database values without affecting reports
I had a web app developed that is a simple crm used to create estimates, service reports and invoices. It includes a module for tracking inventory. I found if I deleted an item from inventory that the estimates, service reports and invoices that include this item will fail to load and cause an error. Is there a way to work around this? I am guessing it is referencing the id of the inventory item and then cannot find the details. How can I delete inventory items without affecting existing reports? The datbase file where the inventory is stored is named db.sqlite3 -
Payfort - (00073) Invalid request format
I hope everyone is doing well. I'm trying to set up payfort in Django, but I keep encountering this strange error. I believe I'm following all the necessary steps, but whenever I attempt to send a request after tokenization, I receive the following error. {'response_code': '00073', 'response_message': 'Invalid request format', 'status': '00'} Tokenization Code: def initiate_tokenization(request): current_timestamp = str(int(time.time())) requestParams = { 'service_command': 'TOKENIZATION', 'merchant_identifier': settings.MERCHANT_IDENTIFIER, 'merchant_reference': current_timestamp, 'language': settings.LANGUAGE, 'access_code': settings.ACCESS_CODE, 'return_url': 'http://localhost:8000/callback', } signature = calculate(requestParams, settings.SHA_REQUEST_PHRASE) requestParams['signature'] = signature redirectUrl = 'https://sbcheckout.payfort.com/FortAPI/paymentPage' response = "<html>\n<head>\n<title>Standard Merchant Page Sample</title>\n</head>\n<body>\n" response += "<h1 style='text-align:center'>Standard Merchant Page iFrame Sample</h1>\n" response += "<center><iframe style='width: 100vw; height: 500px; border:6px dotted green' name='myframe' src=''></iframe></center>\n" response += "<form action='" + redirectUrl + "' method='post' id='' target='myframe'>\n" for key, value in requestParams.items(): response += "\t<input type='hidden' name='" + html.escape(key) + "' value='" + html.escape(value) + "'>\n" response += "\t<input value='Show Payment Form' type='submit' id='form1'>\n" response += "</form>\n</body>\n</html>" resp = HttpResponse(response) resp['X-Frame-Options'] = 'ALLOWALL' return resp Purchase Code: import requests import time import hashlib def calculate(unsorted_dict, sha_phrase, sha_method=hashlib.sha256): sorted_keys = sorted(unsorted_dict, key=lambda x: x.lower()) sorted_dict = {k: unsorted_dict[k] for k in sorted_keys} result = "".join(f"{k}={v}" for k, v in sorted_dict.items()) result_string = f"{sha_phrase}{result}{sha_phrase}" signature = sha_method(result_string.encode()).hexdigest() … -
Show user location in django admin
There was a task to implement a map in the admin interface in Django. I have a model that stores data about users GPS. class Geoposition(BaseModel): created_by = models.ForeignKey("User", on_delete=models.CASCADE, verbose_name=_("User")) task = models.ForeignKey("Task", on_delete=models.SET_NULL, verbose_name=_("Task"), null=True, blank=True) longitude = models.CharField(max_length=20, default="", verbose_name=_("Longitude")) latitude = models.CharField(max_length=20, default="", verbose_name=_("Latitude")) battery_level = models.CharField(max_length=20, default="", verbose_name=_("Battery Level")) speed = models.CharField(max_length=20, default="", verbose_name=_("Speed")) Here I refer to the "Task" model by Foreign Key. In Django admin in Task model I have Inlines class TaskTransitInline(admin.TabularInline): model = Geoposition I need that when you click on Inline inside the Task model, a map displaying the user’s tracking will open Maybe someone has encountered this problem and can help me I looked at several libraries, but I have no idea which one might be useful to me -
Wagtail 6/ Django: TypeError: 'tuple' object is not callable creating a ListBlock with custom StructBlocks
I want to create a ListBlock with custom StructBlocks. I use the following code: card_group.py # Other custom blocks will be added in the future CARD_BLOCKS = [ ("text_block", TextBlock()) ] class CardGroup(blocks.StructBlock): cards = blocks.ListBlock( blocks.StructBlock(CARD_BLOCKS) ) class Meta: template = "blocks/card_group.html" label = _("Card group") I Get the following error: TypeError: 'tuple' object is not callable. I also use the same setup on different parts in the project for example in the homepage models.py. The only difference is that i have the list in parentheses like this: COMMON_BLOCKS = ( ("text_block", TextBlock()), ("button", Button()), ("button_group", ButtonGroup()) ("card_group", CardGroup()) ) HEADER_BLOCKS = () + COMMON_BLOCKS HOMEPAGE_BLOCKS = () + COMMON_BLOCKS That works for these lists but when i want to use this aproach for the CARD_BLOCKS i get the following error: ValueError: too many values to unpack (expected 2) But it works on the other blocks, i am clearly missing something. The usage in the models.py: header_content = StreamField( HEADER_BLOCKS, verbose_name=_("Header Content"), blank=True, null=True, ) content = StreamField(HOMEPAGE_BLOCKS, verbose_name=_("Content"), null=True, blank=True) I use wagtail 6 I want to create a ListBlock with custom StructBlocks. I use the following code: card_group.py # Other custom blocks will be added in the … -
ERROR 403 in Django even after configuring the django-cors-headers package
Is the django-cors-headers exclusive to the DRF? If not, why am I getting an error 403 if I am not using DRF in my project? I already configured the django-cors-header package. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:8000', ] -
Missing email key in fields for UserCreationForm in Django
I am having an issue with the UserCreationForm in Django, namely, I receive an error related to the email field, which is my USERNAME_FIELD, not being found in self.fields I subclass the UserCreationForm as such class UserCreationForm(UserCreationForm, CheckUserEmailExtension): """ A UserCreationForm with optional password inputs. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["password1"].required = False self.fields["password2"].required = False # If one field gets autocompleted but not the other, our 'neither # password or both password' validation will be triggered. self.fields["password1"].widget.attrs["autocomplete"] = "off" self.fields["password2"].widget.attrs["autocomplete"] = "off" class Meta: model = User fields = ( 'first_name', 'last_name', 'email', 'is_pi', 'password1', 'password2', ) And the error occurs at authtools/forms.py, line 95, in __init__ self.fields[User.USERNAME_FIELD].validators.append(validate_uniqueness_of_username_field) due to email not being in self.fields in fact, if I check the local variables, I see only is_pi;password1;password2 in self.fields Local Vars __class__ <class 'authtools.forms.UserCreationForm'> args () kwargs {'initial': {'_changelist_filters': 'q=patt'}} self <UserForm bound=False, valid=Unknown, fields=(is_pi;password1;password2)> validate_uniqueness_of_username_field <function UserCreationForm.__init__.<locals>.validate_uniqueness_of_username_field at 0x7f255fb58540> Yet, when ModelForm is called, email is there form = ModelForm(initial=initial) Local Vars ModelForm <class 'django.forms.widgets.UserForm'> add True extra_context {'auto_populated_fields': (), 'username_help_text': ''} fieldsets ((None, {'description': "Enter the new user's name and email address and click Save. " 'The user will be emailed a link allowing him/her … -
"My weather site should show images based on weather. How to fix?" [closed]
I'm developing a weather website. How can I make it display images based on the weather data? For example, if it's sunny, I want it to show a sunny weather image. Currently, it doesn't display the images correctly. How can I fix this?" "I attempted to integrate image display based on weather data into my weather website, expecting it to show relevant images such as sunny weather pictures. However, the expected images aren't being displayed as intended. What could be the issue?" -
Using Django as API gateway & authorizations service in Microservice
I wanted to create a Microservice that will use Django as its API Gateway for the GraphQL. This is the desired output of my service architecture. Can some one please explain to me how to reach to this end, or provide a meaningful resources to create a microservice with Django. -
React and Django connection with channel setup - WebSocket connection failed
I'ved tried to setup Django with channels to provide notification to React. https://github.com/axilaris/react-django-channels <-- I have put my project code here. in backend/backend/settings.py INSTALLED_APPS = [ .. 'channels', ] CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer' } } ASGI_APPLICATION = 'backend.routing.application' in backend/backend/asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter #import backend.routing import user_api.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter( user_api.routing.websocket_urlpatterns #backend.routing.websocket_urlpatterns <-- not sure if should be this ), }) in backend/user_api/routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from . import consumers application = ProtocolTypeRouter({ "websocket": URLRouter([ path("ws/notifications/", consumers.NotificationConsumer.as_asgi()), ]), }) in backend/user_api/consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): print "XXX connect" await self.accept() async def disconnect(self, close_code): print "XXX disconnect" pass async def receive(self, text_data): print "XXX receive" text_data_json = json.loads(text_data) message = text_data_json['message'] await self.send(text_data=json.dumps({ 'message': message })) Finally in Reach, App.js useEffect(() => { const ws = new WebSocket('ws://localhost:8000/ws/notification/'); ws.onopen = () => { console.log('Connected to notification websocket'); }; ws.onmessage = e => { const data = JSON.parse(e.data); setMessage(data.message); }; ws.onerror = e => { console.error('WebSocket error', e); }; ws.onclose = e => { console.error('WebSocket closed', e); }; return () => … -
Auto Pagination issues in Django, how to fix?
Auto Pagination issues in Django, how to fix? How to resolve duplication with automatic pagination? There's a template home.html and home_list.html; In home_list.html, JSON format is successfully passed, but Ajax misbehaves and creates a bunch of duplicate posts during automatic pagination; how to fix? home.html: <script> $(document).ready(function(){ var nextPageUrl = '/load-posts/'; // Using URL for loading posts function loadMorePosts() { // Display loading element //$('#loading').text('Loading...'); // Perform a GET request to the server $.get(nextPageUrl, function(data) { // Hide loading element //$('#loading').text('Load more'); // Append HTML with posts to the end of the container $('#post_contenter').append(data.posts_html); // Update URL for the next page nextPageUrl = data.next_page_url; }).fail(function() { // Handle request error if it occurs console.error('Error loading posts'); // Hide loading element $('#loading').hide(); }); } // Event handler for page scroll $(window).scroll(function() { if($(window).scrollTop() + $(window).height() >= $(document).height()) { // Call the function to load additional posts loadMorePosts(); } }); // Initialize loading of the first page of posts when the page is loaded loadMorePosts(); }); </script> views.py: from django.shortcuts import render, redirect from usercreatepost.forms import PostForm from publication.models import Userpublication from user.models import Profile****, Subscription from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.urls import reverse from django.http … -
How to Prioritize Celery Tasks When Processing Large Numbers of Files to Prevent Long User Wait Times?
I am working on a Django application where users can upload files to be processed by Celery tasks. Each file upload triggers a Celery task that processes the file individually. The problem arises when a user uploads a large batch of files (e.g., 10,000 files), as it causes subsequent users' uploads (e.g., 100 files) to wait until the first user's batch has completely processed. This results in significant delays and a poor user experience for those uploading smaller batches of files. Tasks are segregated into user-specific queues. Each queue is named following the pattern user-{user_id} (e.g., user-1, user-2, ..., user-10). My objective is to achieve a round-robin processing strategy across these queues: after processing a task from user-1's queue, the worker should move on to process a task from user-2's queue, and so on, cycling through the queues in a round-robin fashion until all tasks are processed. Stuck on: I have not been able to configure Celery to listen to queues using a pattern (e.g., user-.*). The queue list for the Celery worker must be predefined and cannot dynamically adjust to match new user-specific queues as they are created. Question: Is there a way to configure Celery workers to process … -
Django migrations not creating tables on PostgreSQL despite successful execution
Description: I'm encountering an issue with Django migrations on a PostgreSQL database. Despite running python manage.py migrate successfully without any errors, the tables are not being created in the database. Details: Environment: Django version: Django 4.2 PostgreSQL version: PostgreSQL 15.6 Operating System: Ubuntu server 22.04.4 Issue Description: When I run python manage.py migrate, it executes successfully without any errors. However, upon checking the database, no tables are created in the specified schema. Steps I've Taken: Checked the permissions for the database user used by Django. It has all privileges, including the ability to create tables. Verified the configuration in settings.py to ensure the database settings are correct. Looked for error messages in both the Django logs and PostgreSQL logs, but found no relevant errors. Specifically created a new PostgreSQL database and user, intentionally not granting any permissions. Troubleshooting Attempted: Checked the database user permissions. Examined Django and PostgreSQL logs for errors. Ensured that migrations are applied in the correct order and do not contain errors. Expected Outcome: After running python manage.py migrate, I expect the tables specified in the migrations to be created in the PostgreSQL database. Additional Context: This issue occurs specifically on the production server. On my local …