Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding number line on scanned PDFs
This is a scanned PDF that I want to add some number lines and I have tried pytesseract, reportlab but am not getting the needed outcome. What I am looking for is below Here is my code, Its working with normal text PDF but not on scanned PDF import sys from collections import defaultdict from io import BytesIO from pypdf import PdfReader, PdfWriter from reportlab.pdfgen.canvas import Canvas # Initialize dictionaries to hold positions and sizes POSITIONS = defaultdict(lambda: sys.maxsize) SIZES = {} def record_line_positions(text, cm, tm, font_dict, font_size): """Record the positions of lines in the PDF.""" if not text.strip(): # Skip empty lines return x, y = tm[4], tm[5] # Extract x and y positions if POSITIONS[y] > x: # Record the leftmost x for each y POSITIONS[y] = x SIZES[y] = font_size # Store font size for the y position # Specify the paths to the original PDF and output PDF pdf_file_path = r'C:\PyCharm Projects\folder\media\20240925131414249.pdf' output_pdf_path = r'C:\PyCharm Projects\folder\media\text.pdf' # Open the original PDF file for reading with open(pdf_file_path, 'rb') as pdf_file: pdf_reader = PdfReader(pdf_file) pdf_writer = PdfWriter() # Iterate through each page for page_num in range(len(pdf_reader.pages)): page = pdf_reader.pages[page_num] POSITIONS.clear() # Reset positions and sizes for each page … -
Angular+Django CSRF token not being saved as cookie
I have a webapp with Angular frontend and Django backend. Everything works fine locally so I deployed the backend to PythonAnywhere. I use CSRF tokens so as soon the user opens the page, an empty request is sent to the backend, which responds with the token which is automatically saved as a cookie. However this does not work when I deploy the backend. I can see the token is in the response, but it does not appear in the browser storage, and it cannot be used for the following requests. I'm not sure how to even debug this. What could be causing this to begin with? This is the relevant part of my setttings.py: ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOWED_ORIGINS = ( 'http://localhost:4200', ) CSRF_TRUSTED_ORIGINS = ( 'http://localhost:4200', ) CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True I get the same problem when I deploy the frontend (then I also add it as a trusted origin but I skipped that in this extract). Like I said, I can see the token in the response in … -
Django Cart View: Total Amount Showing 0
I’m encountering an issue with my Django cart view where the total cart amount is showing as 0. Below are the relevant parts of my code and the logs. JavaScript (AJAX): $(document).ready(function() { $("#add-to-cart-btn").on("click", function(){ let quantity = $("#product-quantity").val(); let product_title = $(".product-title").val(); let product_id = $(".product-id").val(); let product_price = $("#current-product-price").text(); let product_image = $(".product-image").val(); let product_pid = $(".product-pid").val(); let this_val = $(this); // Log the values console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("PId:", product_pid); console.log("Image:", product_image); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); // Check if product price is valid if (!product_price || isNaN(parseFloat(product_price))) { console.error("Product price is invalid: " + product_price); return; } $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'pid': product_pid, 'image': product_image, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(res){ this_val.html("Go to Cart"); console.log("Added products to cart"); $(".cart-items-count").text(res.totalcartitems); $(".total").text(res.cart_total_ammount); } }); }); }); Django View: from decimal import Decimal, InvalidOperation from django.shortcuts import render, redirect from django.contrib import messages from .models import Coupon def cart_view(request): cart_total_amount = 0 coupon_discount_decimal = Decimal(0) coupon_code = "" coupon_discount_percentage = 0 if 'cart_data_obj' in request.session: print("Cart Data:", request.session['cart_data_obj']) # Log cart data for p_id, item in request.session['cart_data_obj'].items(): try: item_price = float(item['price']) except … -
When the page is fully loaded, the visibility limits part of the page
In the first option - page loading mode - this is if you interrupt it at the loading stage and not completely. The page is not completely loaded. In this case - option - all the content is displayed in the browser - the content that has time to load is loaded accordingly - which had time to load before the interruption. In the second option - page loading - this is if you do not interrupt the loading and the loading is complete. All the content on the page is completely loaded. But at the moment - immediately upon complete loading - there is a cut-off - a reduction in the visibility of the content - you cannot fully view the - seemingly fully loaded page. The content is cut-off. It is possible that something is not working somewhere. Could this be - is it because of the side menu? I'm trying to create a shell for Django Python. And I have a strange thing - visibility - content availability is limited. Although everything seems to load when loading - but then when fully loaded for some reason - there is a limitation - there is no scrolling of … -
Optimizing One-to-Many Relationships for Large Datasets in Sales Prediction
One to many relationships for huge dataset in an iteration? I tried to predict the future sales using store and product for which each store is mapping with all products which is taking huge time to process the data i tried batch processing and multi threads but still for 1200 stores and 750 products mapping takes 20-30 min which is too much for such small data set of 18000 rows how can i scale if i have huge data in millions.I want the process to happen in minutes for any amount of data even if it is taking too long for my processing. -
Possible to use axios to open page in new window in order to download csv from api view?
I have a Django view that downloads a large dataset from the database to a local .csv using StreamingHttpResponse. This works great; however, when I try to add authentication with [IsAuthenticated] permissions_classes tag, the url (of course) becomes unvisitable without including a valid user Bearer token in the header. Here is the relevant code from views.py: import csv from django.http import StreamingHttpResponse class Echo: def write(self, value): return value def streaming_csv_view(request): queryset = Emissions.objects.all().values_list('year', 'value') echo_buffer = Echo() csv_writer = csv.writer(echo_buffer) labels=[('Year', 'Value')] rows = (csv_writer.writerow(row) for row in chain(labels,queryset)) response = StreamingHttpResponse(rows, content_type="text/csv") response["Content-Disposition"] = 'attachment; filename="Emissions.csv"' return response I achieve this elsewhere in my code for more standard API calls (i.e. retrieving data), but can't wrap my head around how to make this work for my csv download, which requires that the user visit the page... Can I use an axios call to open this page in a new window to initiate the download and then close the window when the download is complete? I'm having trouble finding examples of axios being used in this way I feel like I'm missing something...any help would be greatly appreciated. Here's a typical axios GET request to the endpoint, which won't … -
where should i learn DJANGO? kindly help me out i am begginer in python backend web development. suggest me the best sources [closed]
where should i learn DJANGO from? kindly help me out i am begginer in python backend web development. suggest me the best sources for django. where should i learn DJANGO from? kindly help me out i am begginer in python backend web development. suggest me the best sources. -
Django Q tasks stuck in Queued
I think I have a broken task somewhere that is holding up all other scheduled tasks. Is there a way to delete all tasks in Django Q Queued Task list? I don't want to delete the actual ScheduledTasks but just the Queued instances? Is the a command that can be executed to quickly wipe them all as on the Django Admin panel I can only delete them in batches of 100 and there are thousands backed up. Thanks in advance -
Frozen day in Django form
I use django, nginx, gunicorn. Please help, this form records the date of record creation. For a long time everything worked fine, but recently the date was fixed at 2024-10-07, although it was 2024-10-09. The time on the server is correct. Restarting gunicorn helped, but now it records 2024-10-09. Can you indicate the reason for the failure? class MyForm(forms.ModelForm): create_date = forms.DateField(input_formats=['%Y-%m-%d'], widget=forms.DateInput(attrs={'type': 'date', 'value': (datetime.today() + timedelta(hours=3)).strftime('%Y-%m-%d'), 'readonly': True}), label='Create date') product_cost = forms.IntegerField(label='Cost') -
How can I serialize Cloudinary fields?
I'm trying to use Cloudinary SDK's for Svelte and Django. I have a model with CloudinaryField: class Room(models.Model): ... avatar = CloudinaryField("image") class UserRoom(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) ... and a serializer for the UserRoom: class UserRoomSerializer(ModelSerializer): user = UserSerializer() last_message = SerializerMethodField() def get_last_message(self, obj): return MessageSerializer(obj.room.message_set.first()).data class Meta: model = UserRoom fields = "__all__" depth = 1 I want to use Cloudinary's svelte component <CldImage /> and I need to pass an image public id into it. But when I make a request, I get an image path, not id: { "id": 1, "user": { ... }, "last_message": { ... }, "unread_messages": 0, "room": { "id": "49c33134-cc9f-43e0-b524-b05e9387602d", "name": "test", "avatar": "image/upload/v1728304120/sz8h5f5oqbtc95cfxbvx.jpg" // THIS LINE IS A PATH, NOT AN ID } } How do I make DRF send an id, not a path? -
Injecting input fields into existing HTML Form
Im trying to make a form which will be adding a new inputs whenever the user fill another input. I set up an event listener that will do ajax request into my back-end and, if succeed, it will bring an element of input that will be injected into the form. it looked like this : $.ajax({ type: "GET", url: "{% url 'cart:get-delivery' %}", data :{ city : id }, success: function(res) { $("#delivery").replaceWith(res.component) $('.spinner-overlay').remove(); }, error: function(e) { console.log("Failed") $('.spinner-overlay').remove(); } }) the form works on the surface, but when I submit the form, it won't recognize my newly added input fields. so when I do request.POST.get('example') it won't appear. does anyone have solution on this? also here is the added element : {% load humanize %} {% if content %} <td id="delivery"> {% for ins in content %} {% for jenis in ins.costs %} <div class="form-check"> <input class="form-check-input" type="radio" name="radio-delivery" id="{{ins.code}}" value="{{jenis.cost.0.value}}|{{ins.code}}|{{jenis.service}}"> <label class="form-check-label" for="radio-delivery"> <strong>{{ins.code | upper}}</strong> - {{jenis.service}} : Rp {{jenis.cost.0.value | intcomma}} </label> </div> {% endfor %} {% endfor %} </td> {% endif %} -
Django Issue After Migration: Identical Code in Test and Main Branch, But Production Fails
Has anyone encountered a similar issue in Django? In my test branch, everything works fine, including the password reset functionality. However, in production, it throws an error stating that the page doesn’t exist (even though it’s definitely there). I’m also experiencing a similar issue with date formatting. In test branch, the date displays correctly as the current month and year, but in production, it shows a different value, like “September 2020.” Any ideas on what could be causing this? I've reviewed the code in both the main and test branches, and everything appears identical. The issue began after the most recent migration, even though the site isn't used very often. Also if you will be wondering for some reason DEBUG = True And it's output specifically for the passwords was that the template was not found as I told you earlier. Any help would be highly appreciated! -
my chat user are not connecting each other
i am building a a private chat and calls both voice and video that preach privacy, with full privacy end to end, no message stored or saved to the backend, and every message is encrypted, so no one could breach it, every user has been given the power to thier own chat, now no matter what i do the chat isnt working i feel like my my consumer.py is not well written, i want user to chat and video call each other, but they are not chatting for example a user is not connecting with each other, its like they are not in a room together class SecureChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope['user'] self.friend_username = self.scope['url_route']['kwargs']['username'] if not self.user.is_authenticated: await self.close() return try: # Create a shared room name between both users for proper communication self.room_name = f"chat_{'_'.join(sorted([self.user.username, self.friend_username]))}" await self.channel_layer.group_add(self.room_name, self.channel_name) await self.update_user_status(online=True) await self.accept() logger.info(f"WebSocket connection established for user {self.user.username} in room {self.room_name}") except Exception as e: logger.error(f"Error during WebSocket connection: {e}") await self.close() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_name, self.channel_name) await self.update_user_status(online=False) logger.info(f"WebSocket disconnected for user {self.user.username}") async def receive(self, text_data): """ Handle incoming WebSocket messages. Distinguish between message events and WebRTC events. """ try: data … -
Cant access image on aws-s3 saved via django
Url of image stored in db is: profile_pictures/f292ddfe-ee17-4ccc-be85-0398fb602753.jpeg but when i click on it, url becomes https://workandhomes.s3.amazonaws.com/media/profile_pictures/f292ddfe-ee17-4ccc-be85-0398fb602753.jpeg?AWSAccessKeyId={keyHere}&Signature={somevalue}&Expires=1728557943 these is my relevant code: models.py class UserProfile(models.Model): ... profile_picture = models.ImageField( upload_to="profile_pictures/", blank=True, null=True ) ... class Meta: db_table = "user_profile" settings.py .... # AWS S3 Configuration AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME") AWS_REGION = os.getenv( "AWS_REGION", "eu-north-1" ) # Replace 'your-default-region' with your region # Configure the default file storage to use S3 DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_REGION}.amazonaws.com/" ... I am able to perform the put operations and upload the file, but i cant read it. my IAM user on AWS as fullAccess to aws. and following is the bucket policy { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::workandhomes/*" } ] } Lastly when i remove the auth query strings, image opens. Any idea what is happening here ? -
my consumer.py is not working no matter what i do
i am building a a private chat and calls both voice and video that preach privacy, with full privacy end to end, no message stored or saved to the backend, and every message is encrypted, so no one could breach it, every user has been given the power to thier own chat, now no matter what i do the chat isnt working i feel like my my consumer.py is not well written. class SecureChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope['user'] self.friend_username = self.scope['url_route']['kwargs']['username'] if not self.user.is_authenticated: await self.close() return try: # Create a shared room name between both users for proper communication self.room_name = f"chat_{'_'.join(sorted([self.user.username, self.friend_username]))}" await self.channel_layer.group_add(self.room_name, self.channel_name) await self.update_user_status(online=True) await self.accept() logger.info(f"WebSocket connection established for user {self.user.username} in room {self.room_name}") except Exception as e: logger.error(f"Error during WebSocket connection: {e}") await self.close() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_name, self.channel_name) await self.update_user_status(online=False) logger.info(f"WebSocket disconnected for user {self.user.username}") async def receive(self, text_data): """ Handle incoming WebSocket messages. Distinguish between message events and WebRTC events. """ try: data = json.loads(text_data) message_type = data.get('type') logger.info(f"Received message of type '{message_type}' from {self.user.username}") except json.JSONDecodeError as e: logger.error(f"Error parsing message data: {e}") await self.send_error("Invalid JSON format.") return if message_type == 'message': await self.handle_message_event(data) elif message_type … -
How to add the multiple image uploading feature in Wagtail?
I am primarily working with Django, Wagtail, and API serializers, without using templates directly for HTML rendering. Instead of HTML templates, I use Django's and Wagtail's API features to render content. Currently, I'm looking to add a new feature: multiple image uploading on the backend. Right now, with Wagtail, I can only upload a single image at a time. However, we need to modify this feature so that multiple images can be uploaded at the same time.. Let me clear my point my uploading a image. where the wagtail/images/muliple/add where user can add multiple images , but in default case we can only add one image at a time .What I need is for the ability to upload multiple images to be implemented in the default structure. my code structure is like this: ====================================== blocks.py: from wagtail.images.blocks import ImageChooserBlock from wagtail.models import Site, Page from cms.core.models import get_rootless_url_path import re from wagtail.images.models import Image from wagtail.templatetags.wagtailcore_tags import richtext class ImageChooserRenditionsAPIBlock(ImageChooserBlock): def get_api_representation(self, value, context=None) -> dict: from .serializers import ImageSerializer return ImageSerializer(value).data class GreeterBlock(StructBlock): label = TextBlock() # description = TextBlock() description =CustomRichTextBlock(features=['h1', 'h2', 'h3', 'h4', 'h5', 'bold', 'italic', 'ol', 'ul', 'hr', 'link', 'image', 'code', 'blockquote'] ) image = ImageChooserRenditionsAPIBlock(required=False) … -
Cache parts of the django template
I have a page, I want to cache only part of the template, because if I cache the whole page, I have the site header cached as well, and I don't need that. I tried to use the tag - cache in the template, but unfortunately the requests still keep going to the database. However, the cache is being accessed. What could be the problem? lesson.html {% extends "base.html" %} {% load static %} {% block content %} <div class="lesson-flex"> <div class="lesson-flex-nav"> {% for theme in selected_course.themes.all %} <div class="lesson-flex-nav-item"> <h1 class="lesson-flex-nav-title">{{ theme.name }}</h1> <ul class="lesson-flex-nav-list"> {% for lesson in theme.lessons.all %} <li><a href="{% url 'lesson_detail' course_slug=selected_course.slug lesson_slug=lesson.slug %}" class="lesson-flex-nav-list-item">{{ lesson.name }}</a></li> <div class="sep"></div> {% endfor %} </ul> </div> {% endfor %} </div> <div class="lesson-flex-wrapper"> <div class="lesson-flex-item"> <h2 class="lesson-flex-item-title">{{ lesson.name }}</h2> <div class="sep"></div> <p class="lesson-flex-item-text">{{ lesson.body|safe }}</p> </div> {% if lesson.questions.all %} <div class="lesson-flex-wrapper-questions"> <h3 class="lesson-flex-wrapper-questions-title">Questions</h3> <div class="sep"></div> {% for question in lesson.questions.all %} <div class="lesson-flex-wrapper-questions-item"> <p class="lesson-flex-wrapper-questions-item-title">{{ question.name }}</p> <details> <summary class="lesson-flex-wrapper-questions-item-legend">Answee</summary> <p class="lesson-flex-wrapper-questions-item-answer">{{ question.answer }}</p> </details> </div> {% endfor %} </div> {% endif %} {% if lesson.materials.all %} <div class="lesson-flex-wrapper-questions"> <h3 class="lesson-flex-wrapper-questions-title">Materials</h3> <div class="sep"></div> {% for material in lesson.materials.all %} <div class="lesson-flex-wrapper-questions-file"> {% if material.get_extension_display == '.zip' %} … -
Can't save BlobFields when using both django_gcp and django-reverse-admin
I'm trying to use both django-gcp to store large images as BlobFields, and django-reverse-admin so I can edit all of my data inline. My models look like this: class SceneContent(models.Model): site_title = RichCharField( max_length=25, verbose_name="Site Title (25 char)", null=True ) site_description = RichTextField( max_length=300, verbose_name="Site Description (300 char)", null=True, validators=[MaxLengthValidator(300)], ) site_image = BlobField( # blank=True, verbose_name="Site Image (3840 x 2160 px)", get_destination_path=get_destination_path_image, store_key="media", null=True, validators=[BlobImageExtensionValidator()], overwrite_mode="update", ) object_title_1 = RichCharField( max_length=25, verbose_name="Object Title 1 (25 char)", null=True ) object_description_1 = RichTextField( max_length=300, verbose_name="Object Description 1 (300 char)", null=True, ) object_image_1 = BlobField( # blank=True, verbose_name="Object Image 1 (3840 x 2160 px)", get_destination_path=get_destination_path_image, store_key="media", null=True, validators=[BlobImageExtensionValidator()], overwrite_mode="update", ) object_title_2 = RichCharField( max_length=25, verbose_name="Object Title 2 (25 char)", null=True ) object_description_2 = RichTextField( max_length=300, verbose_name="Object Description 2 (300 char)", null=True, ) object_image_2 = BlobField( # blank=True, verbose_name="Object Image 2 (3840 x 2160 px)", get_destination_path=get_destination_path_image, store_key="media", null=True, validators=[BlobImageExtensionValidator()], overwrite_mode="update", ) def __str__(self): return self.site_title class Site(models.Model): scene_title = RichCharField( max_length=12, verbose_name="Title (12 char)", null=True ) pronunciation_guide = RichCharField( max_length=25, verbose_name="Site Pronunciation Guide (25 char)", null=True ) scene_subtitle = RichCharField( max_length=40, verbose_name="Subtitle (40 char)", null=True ) scene_selection_image = BlobField( # blank=True, verbose_name="Background Image (1280 x 2160 px)", get_destination_path=get_destination_path_image, store_key="media", null=True, validators=[BlobImageExtensionValidator()], overwrite_mode="update", ) … -
django-haystack elasticsearch spanish special chars (accents)
im using django-haystack 3.3.0 over django 4.x and use elasticsearch 7.17.24 as backend. I'm dealing with texts in spanish, so for example I'm index the text: El corazón del mar and when I'm try to search: corazon i got 0 results, but when I'm search corazón or Corazón I got n>0 results any idea? thanks in advance -
getting phone number of user in a django app from google with social_core
Hello I am working on a Django app that have Customuser model and i just save users phone number in the model for some reasons this is my model and manager : class CustomUserManager(BaseUserManager): def create_user(self, phone_number, password=None, **extra_fields): if not phone_number: raise ValueError('The Phone Number must be set') user = self.model(phone_number=phone_number, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(phone_number, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField(max_length=15, unique=True) email = models.EmailField(unique=True, null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) score = models.PositiveIntegerField(default=10, null=True, blank=True) objects = CustomUserManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] def save(self, *args, **kwargs): super().save(*args, **kwargs) Profile.objects.get_or_create(user=self) def add_score(self, score): self.score += score print(self.score) self.save() def decrease_score(self, score): self.score -= score self.save() def generate_referral_code(self): code_length = 19 characters = string.ascii_letters + string.digits unique_code = ''.join(random.choice(characters) for _ in range(code_length)) while ReferralCode.objects.filter(code=unique_code).exists(): unique_code = ''.join(random.choice(characters) for _ in range(code_length)) ReferralCode.objects.create(user=self, code=unique_code) def get_referral_code(self): try: return self.referralcode.code except ReferralCode.DoesNotExist: return None def __str__(self): return self.phone_number i edit my setting.py file for having a pipleline file like this : SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config("GOOGLE_CLIENT_ID") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config("GOOGLE_SECRET") SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/user.phonenumbers.read', ] SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', … -
AJAX Posts Reverse Order After Refresh the Page When Multiple Posts are Created in the Same Minute from Same User
I'm working on a social network project using Django for the backend and JavaScript for the frontend. Users can post new content, and the global feed is updated both dynamically via Ajax and by refreshing the page. Everything works fine, except when a user creates multiple posts within the same minute. Initially, the newest post is displayed at the top, but when I refresh the page, the order of posts gets reversed for that specific user, where older posts appear above newer ones. I'm using the created_at field (with DateTimeField) to order the posts. Here's a snippet of the key code that handles fetching the global stream and updating the DOM: function updateStream(posts) { const postContainer = document.querySelector('#post-list'); posts.forEach(post => { let postElement = document.getElementById(`id_post_div_${post.post_id}`); if (!postElement) { postElement = document.createElement('div'); postElement.id = `id_post_div_${post.post_id}`; postElement.className = 'post'; postElement.innerHTML = ` <p> <strong><a href="/profile/${post.author_username}" id="id_post_profile_${post.post_id}" class="post-profile"> ${post.author}</a></strong>: <span id="id_post_text_${post.post_id}" class="post-txt">${sanitize(post.content)}</span> <span id="id_post_date_time_${post.post_id}" class="post-date-time">${formatDate(post.created_at)}</span> </p> <div class="comments" id="comments_${post.post_id}"></div> <div id="id_comment_input_div_${post.post_id}" class="add-comment"> <input type="text" id="id_comment_input_text_${post.post_id}" placeholder="Add a comment" /> <button id="id_comment_button_${post.post_id}" onclick="addComment(${post.post_id})">Submit</button> </div> `; // Add new post to the correct position postContainer.appendChild(postElement); } }); } What I’ve Tried: Adding a fallback to sort by post_id when posts have the same created_at, but … -
How to block migrations that delete a view in django?
When we change the type of a column in Django and run a migration, it does not finish if any view is using the column. However, when we remove a column from the table and run a migration, Django does not interrupt the migration. How can I configure this? Can we create a custom migration or even a trigger in the database? -
Redirecting a user to a specific address after logging in to Django
The problem is as follows: after the user has entered his data into the form on the page /accounts/login, upon successful login, he should be directed to the page corresponding to his username ``/username`'. At the same time, this redirection is carried out to the admin panel and each admin will have their own models displayed. I don't understand how to steal the name of the current user, and then allow only this user to enter the admin panel corresponding to his name. For example, the user entered the name ntz and some password, after that he should get to the /ntz/ - admin page of this user. There is no way other users can get there. One user - one admin panel. Here's what's in the code: #urls.py from django.urls import path, include from .views import main, CustomLoginView from PKM.admin import pkm_admin_site from NTZ.admin import ntz_admin_site urlpatterns=[ path('', main, name='main'), path('ntz/',ntz_admin_site.urls), path('pkm/', pkm_admin_site.urls), path('accounts/', include('django.contrib.auth.urls')), path('accounts/login/', CustomLoginView.as_view(), name='login') ] #login.html {% load static %} <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}Log in to your personal account{% endblock %}</title> </head> <body> <div class="login-container"> <h2>Login to your personal account</h2> <form method="post"> {{ form.as_p … -
How to fix this state management and improve conditional rendering of react elements
I'm pretty dang new to react, and I'm trying to understand general best practices for state management, especially when state conditionally renders different react elements. I am looking for general best practices on how to properly structure the below code in order to manage state effectively and properly conditionally render my page's content. Below is a quick code snippet showing how I am getting information about an "upstream" element, and using that information to conditionally render different form options in a "downstream" element. The general idea is that based on the type of document the user uploads, that then determines the different settings options they have available to them. I can tell that I'm writing spaghetti code, but I'm not sure how to refactor it/reorganize the code to make it cleaner. Below is a code snippet showing how I conditionally render different elements based on the fileType stored in inputType. <div className="card-body" style={{ padding: "10px" }}> {(inputType === 'txt' || inputType === 'docx') && <TextExtractHandler id ={id} />} {inputType === 'image' && <div>Image Input Handler Placeholder</div>} {inputType === 'video' && <div>Video Input Handler Placeholder</div>} {(inputType === 'csv' || inputType === 'xlsx') && <div>Spreadsheet Input Handler Placeholder</div>} </div> Here is my … -
Django constraint on derived fields
I am trying to add a non-overlaping constraint on a Postgres specific field DateRange field: class MyModel(models.Model): timespan = DateRangeField(blank=False, null=False) status = models.CharField(max_length=8, choices=status_choices, blank=False, null=False) class Meta: constraints = [ ExclusionConstraint( name='exclude_overlapping_offer', expressions=[ ('timespan', RangeOperators.OVERLAPS), (models.Q(status='ACCEPTED'), RangeOperators.EQUAL), ], ) Basically I want to prevent having overlapping entries in the database that have status ACCEPTED. The migration runs fine, but then when I try to save the model, I get an error: AttributeError: 'Q' object has no attribute 'replace_expressions' There is a reply on a bug report that says that Q objects are not allowed in the expressions of the constraint: https://code.djangoproject.com/ticket/34805 Is there some other way to have the constraint on a derived field?