Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin: How to hide nested inline until parent is saved?
I have a nested inline setup in Django Admin where I want to hide a child inline until its parent is saved. Here's a simplified version of my models: class Parent(models.Model): name = models.CharField(max_length=255) class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name = models.CharField(max_length=255) class GrandChild(models.Model): child = models.ForeignKey(Child, on_delete=models.CASCADE) name = models.CharField(max_length=255) And here's my admin setup: class GrandChildInline(NestedTabularInline): model = GrandChild extra = 0 def get_formset(self, request, obj=None, **kwargs): formset = super().get_formset(request, obj, **kwargs) return formset class ChildInline(NestedTabularInline): model = Child extra = 0 inlines = [GrandChildInline] class ParentAdmin(NestedModelAdmin): inlines = [ChildInline] admin.site.register(Parent, ParentAdmin) Current Behavior When editing a Parent, I can add Children The GrandChild inline is visible immediately when adding a new Child I want the GrandChild inline to only appear after the Child is saved Desired Behavior GrandChild inline should be hidden when adding a new Child GrandChild inline should only appear after the Child is saved GrandChild inline should be visible when editing an existing Child What I've Tried Using the template property to return an empty string Using has_add_permission and get_queryset Checking for parent instance existence None of these approaches fully work - either the inline is always visible or always hidden. Question How … -
Django fails to correctly link viewable documents stored in a Django model
So I currently have a Django model which correctly references everything passed to my template, except for the link to the document I have uploaded. The model has been correctly registered in admin.py. Here is is MRE: #investors/models.py from django.db import models class FinancialStatements(models.Model): financials_upload = models.FileField(upload_to='documents/financials/') class Meta: verbose_name_plural = "Financial Statements" #investors/views.py from .models import FinancialStatements def investor_relations(request): financials_queryset = FinancialStatements.objects.all() context = { 'financials_queryset' : financials_queryset, } return render(request, 'investors.html', context) #settings.py MEDIA_URL = '/assets/' MEDIA_ROOT = BASE_DIR / 'assets' #investors/templates/investors.html {% for financials in financials_queryset %} <a href="{{financials.financials_upload.url}}">Financial Statement</a> {% endfor %} Upon accessing the uploaded file from the model, the URL is http://127.0.0.1:8000/assets/documents/financials/<filename>.pdf which is the directory I want to specify, and so is correct. However, Django is continuing to fail to access the URL from {{financials.financials_upload.url}} when looping through the financials_queryset quertset My file directory is set up in the following fashion: <ROOT>/assets/documents/financials/** Whenever I hover over the <a> tag, the message in the bottom of the left corner of the browser fails to return the URL of the document to be viewed. It simply returns http://127.0.0.1:8000/investors Despite this, I do fail to see how cannot work this one out, despite correctly point it … -
Settings.py cannot find psycopg2... squlite3 and postgresql problem... no such table: auth_user
I'm trying to deploy a simple app (learning log from Python Crash Course) to heroku. The app runs but upon login, I get a 500 error, and in debug=true the error is: no such table: auth_user. I realise this has something to do with squlite3 and Postgresql, but when I try to build the code in settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': BASE_DIR / 'db.sqlite3', } } the error message is ImportError: DLL load failed while importing _psycopg: The specified module could not be found. I have attempted to install and import psycopg2, and it appears to be in requirements.txt. But I think the paths are not aligning, since psycopg2 is in a python pathway, and setting.py is looking in my project environment. I'm very confused! Please help! -
Why am I getting a 403 Forbidden error when making a POST request to the login API in Vue.js?
I'm working on a Vue.js application where users can log in through an API using the axios library. However, when I send a POST request to the API endpoint, I'm getting a 403 Forbidden response. Here's the Vue.js code for the login request: const response = await axios.post( 'https://apibackup.example.com/api/login/', { username: email.value, password: password.value }, { headers: { 'Content-Type': 'application/json' }, withCredentials: true, withXSRFToken: true } ) And here's the login view from the Django backend: def login_view(request): if request.method == 'POST': try: data = json.loads(request.body) form = LoginForm(data) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Logic for handling user types here... else: return JsonResponse({'status': 'error', 'message': 'Invalid username or password'}, status=401) else: return JsonResponse({'status': 'error', 'errors': form.errors}, status=400) except json.JSONDecodeError: return JsonResponse({'status': 'error', 'message': 'Invalid JSON data'}, status=400) Here are the relevant settings from the Django settings.py: CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'https://example.com', 'http://localhost:5173', # other domains... ] CSRF_TRUSTED_ORIGINS = [ 'https://example.com', 'http://localhost:5173', # other domains... ] CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True CSRF_COOKIE_DOMAIN = 'example.com' Issue: When I try to log in, I get the following error in the browser console: POST https://apibackup.example.com/api/login/ … -
AxiosError: Network Error on iOS (GET request ) with Expo, working fine on Android
it's first time i am asking question in stack overflow . I hope you this will help me to solve the issue. About project I am using expo and axios for api request use hooks for handling the request using Django as backend Problem Overview Api request (all type of request) working properly in Android and Web In IOS the POST request working properly But Get request not working Getting this error when request get request from IOS "AxiosError: Network Error" I tested the Get request in IOS with other API tester app in IOS then it worked fine Expo App some codes app.json { "expo": { "name": "MyWard", "platforms": [ "ios", "android" ], "scheme": "com.myward", "slug": "myward", "version": "1.0.0", "orientation": "portrait", "icon": "./assets/images/logo/thumbnail.png", "userInterfaceStyle": "automatic", "ios": { "bundleIdentifier": "com.myward", "supportsTablet": false, "jsEngine": "jsc", "infoPlist": { "LSApplicationQueriesSchemes": ["whatsapp"] }, "runtimeVersion": { "policy": "appVersion" } }, "splash": { "image": "./assets/images/logo/thumbnail.png", "backgroundColor": "#ffffff" }, "jsEngine": "hermes", "android": { "package": "com.myward", "googleServicesFile": "./android/app/google-services.json", "runtimeVersion": "1.0.0" }, "web": { "bundler": "metro", "output": "static", "favicon": "./assets/images/logo/thumbnail.png" }, "plugins": [ "expo-router", "expo-localization", [ "expo-build-properties", { "android": { "usesCleartextTraffic": true } } ] ], "experiments": { "typedRoutes": true }, "extra": { "router": { "origin": false }, "eas": … -
How to Add a Python Interpreter to a Web Application?
I am currently working on a Learning Management System (LMS) web app, and one of the features I need to implement is a web-based Integrated Development Environment (IDE) where users can write, execute, and test Python code directly in the browser. What I am looking for: Guidance on integrating a Python interpreter into the web app. Best practices for securely running user-submitted Python code to prevent malicious activities. Recommendations for tools, libraries, or APIs that can help execute Python code. How to handle input/output in the IDE and display results to the user in real-time. Key considerations: The web app is built using Django and react. Code execution should be sandboxed for security. The IDE should be able to handle basic Python scripts and display outputs/errors to users and suggestions too. -
Does anyone have any ideas on how to make django multilingual more elegant and easier to maintain? [closed]
I had to realize that implementing multilingualism in Django turns out to be an absolute pain. I have seen the following variants, which are absolutely subterranean: Language via Excel. As I said, the message files. This also includes Django-Rosetta, which is a kind of management interface for the message files. And last but not least json files. Unfortunately, that doesn't make it any better for me. Does anyone have any ideas on how to make this more elegant and easier to maintain? Is there an extension that compares the languages like ResXManager Extension in Visual Studio? Thanks in advance. -
How to change the appearance of the TextField in the Django admin?
I want to increase the size of the text area in django admin form. html_content = models.TextField() -
WebSocket (python server, javascript/rxjs client) missing messages
Introduction I'm trying to provide as much info up front, so if I've missed something, please let me know. Motivation: server does the work (asyncio with multi-processing), client just requests and presents data. WebSockets (herein WS) used primarily to minimize latency of requests and replies (connection protocols done up front, and TLS connection done once). WS uses TCP, which has produced sufficiently transparent transactions...no need for UDP or anything for greater speed. Setup WS server: Python/Daphne/Django Channels (updated) WS client: Javascript/Angular/Rxjs (updated) Both running on localhost (no physical throughput contention, ) Applications Client: Angular, primarily requesting and formatting data for presentation Server 1: Django channels async JSON consumer (asyncio framework...maybe important later). Server 2: Python using WebSockets pypi asyncio package (currently legacy...will address later...confirmed not the issue). Server 1 instance connects to server 2 TLS WS connection. Problem I implemented the servers a few years ago. Long story short: I was seeing some aspects of latency in places I didn't expect when using await with the Django ORM. Short answer? I just switched the DB connections from database_sync_to_async to wrapping the calls in asyncio.to_thread. The concurrency experienced has improved by a factor of 10 without a doubt, as I was … -
'django-admin startproject myproject' is not recognised
django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin startproject myproject + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException i tried running this django-admin startproject myproject -
How to get information out of 'OneToOneField' and use this information in admin.py list_display?
I making my first site, this is my first big project so I stuck at one issue and can't solve it.. Here part of my code with error: models.py ... class GField(models.Model): golf_club_name = models.CharField( primary_key=True, max_length=100, help_text='Enter a golf club (Gfield) name', ) golf_field_par = models.PositiveIntegerField() def __str__(self): return f'{self.golf_club_name}' class PlayerInstance(models.Model): ... golf_field_playing = models.OneToOneField(GField, default = 'for_nothoing',on_delete=models.RESTRICT, help_text='where is it taking part?') now_at_hole = models.IntegerField() today = models.IntegerField() R1 = models.IntegerField() R2 = models.IntegerField() R3 = models.IntegerField() R4 = models.IntegerField() R5 = models.IntegerField() all_rounds = [R1, R2, R3, R4, R5] counter = sum(1 for value in all_rounds if value != 0) par_value = gfield_playing.golf_field_par total = sum(all_rounds[:counter]) if par_value * counter <= total: to_par = f'+{total - par_value * counter}' if par_value*counter>total: to_par = f'-{par_value * counter - total}' ... When I saving this code it sending: par_value = gfield_playing.field_par ^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'OneToOneField' object has no attribute 'field_par' And about admin.py that sending error, when I tried some solves from internet, I actually made the 'to_par' well, and fixed Error: models.py ... R2 = models.IntegerField() R3 = models.IntegerField() R4 = models.IntegerField() R5 = models.IntegerField() def calculate_to_par(self): all_rounds = [self.R1, self.R2, self.R3, self.R4, self.R5] counter = sum(1 for … -
Deployed Django project on vercel can't see tables on the database
I have deployed a django project through vercel and my log in and sign up authentication can't seem to go through. The error shows that the table where I store my users, are not visible to the vercel deployed app. But when I try the project locally, the project works fine with no errors in the log in sign up. Here's the error deployed project error Message. Here's the Github Repository as well. I tried re-configuring my django project to make it vercel ready and also tried to change database host (I am using postgreSQL initially from Railway to Supabase) -
Django Admin Action Function Failing - emailing multiple selected users (if "apply" in request.POST)
My implementation uses a CustomUser model. I'm creating a Django admin action that allows me to compose and send emails to multiple users. Everything on the website behaves as though it's working. After I hit the Send Email button, I'm redirected back to the Admin but I see no console output indicating an email was sent and self.message_user is never called and sent to the Admin. Email Backend Password Reset works with reset link sent to the console, so email backend is working. EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" admin.py if "apply" in request.POST: <-- This line never fires! class CustomUserAdmin(ExportMixin, UserAdmin): @admin.action(description="Email selected users") def send_email_action(self, request, queryset): print(request.POST) print(request.POST.getlist("apply")) input("HALT") if "apply" in request.POST: print("apply") form = EmailForm(request.POST) if form.is_valid(): print("form valid") subject = form.cleaned_data["subject"] message = form.cleaned_data["message"] recipients = [user.email for user in queryset] send_mail(subject, message, "your_email@example.com", recipients) self.message_user(request, f"{len(recipients)} emails were sent.") return HttpResponseRedirect(request.get_full_path()) else: print("no apply") form = EmailForm() return render(request, "email/admin_send.html", {"form": form}) forms.py Works as expected. class EmailForm(forms.Form): subject = forms.CharField(max_length=256) message = forms.CharField(widget=forms.Textarea) admin_send.html Either: The send_email_action function is getting called after I hit the Send Email button but the form isn't sending back the "apply" data, so this is failing: if "apply in request.POST: … -
I have a product and a category model. Now I should filter the products according to the category. How can I do it?
where should i code? at views.py or at the html file? actually I have an idea to render every category and inside that i should filter the products according to it. like, VEGITABLES carrot tomato FRUITS apple mango SOMETHING ELSE something 1 something 2 -
The problem of importing a model into consumer django Websockets
I want to write a consumer for the application, however, after importing the Device model, the application does not even want to start, crashes with an error that it cannot find the application settings. # consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer # from devices.models import Device class DeviceConsumer(AsyncWebsocketConsumer): async def connect(self): self.device_id = self.scope['url_route']['kwargs']['device_id'] print(self.device_id) await self.accept() async def disconnect(self, close_code): await self.close() async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] print(message) await self.send(text_data=json.dumps({'message': message})) And here are the Device and User models: from django.db import models from users.models import User from core.base.utils import generate_uuid class Device(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) device_key = models.CharField(max_length=255, unique=True, default=generate_uuid) is_active = models.BooleanField(default=True) def __str__(self): return self.name from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ class User(AbstractUser): first_name = models.CharField(_("first_name "), max_length=60, blank=False) last_name = models.CharField(_("last_name "), max_length=60, blank=False) username = models.CharField(_("username"), max_length=60, unique=True) email = models.EmailField(_("email address"), max_length=255, blank=False, unique=True) is_staff = models.BooleanField( _("is staff"), default=False, help_text=_("Determines whether the user can log in to this administrative site."), ) is_active = models.BooleanField( _("is active"), default=True, help_text=_( "Indicates whether this user should be considered active." "Uncheck this box instead … -
Polars Read Excel file from Form (ie. request.FILES.get('file'))
All the Polars examples show reading an Excel file from a path string. df = pl.read_excel("docs/assets/data/path.xlsx") But I am passing in the Excel file from a Django Form Post. file_name = request.FILES.get('file') df = pl.read_excel(file_name) I am getting a "InvalidParametersError". How do input the file to Polars from a HTML form? or do I somehow have to get the path from the request.FILES and use that? I am new to the whole Polars thing but very excited to try it. thank you. -
How to hide webapi url and show a "pretty" url?
I need to generate a pretty URL for my own URL shortening service. My web server address looks something like https://my-backend-api-server.us-central1.run.app/redirectapp/redirect/wAzclnp3 and I wouldn't want to expose that, nor is it short. I want to "prettify" my URLs. How to do this in django assuming I have a domain www.mydomain123.com? -
Not able to deploy my Django application on Google Cloud Run
i need some help with my django docker deployment, so ill show you what I currently have and I need your help now configuring it to run with nginx and gunicorn so I can eventually use this to deploy my application with google cloud run. I'm using a mac btw okay so here is my directory: Dockerfile carz docker-compose.yml nginx static carszambia db.sqlite3 manage.py requirements.txt staticfiles docker-compose.yml: version: '3.8' services: web: build: context: . command: gunicorn carszambia.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/usr/src/app - static_volume:/usr/src/app/staticfiles expose: - "8000" env_file: - ./.env.dev depends_on: - db nginx: image: nginx:latest volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - static_volume:/usr/src/app/staticfiles ports: - "8001:80" depends_on: - web db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=xxx_hidden - POSTGRES_PASSWORD=xxx_hidden - POSTGRES_DB=xxx_hidden volumes: postgres_data: static_volume: Dockerfile: # pull official base image FROM python:3.11.4-slim-buster # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN apt-get update && apt-get install -y \ nginx \ && rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy project COPY . . # configure nginx COPY ./nginx/default.conf /etc/nginx/conf.d/ # Expose port for Nginx EXPOSE 80 # Start Gunicorn and … -
Event.preventDefault is not working in JS for form submission
// js document.addEventListener("DOMContentLoaded", function () { const individualOrderForm = document.getElementById('individual-order-form'); async function sendAjax(form) { try { const response = await fetch(form.action, { method: 'POST', body: new FormData(form) }); const data = await response.json(); if (data.status === "success") { showToast(data.detail, "success"); disableForm(form); } else { let errors = JSON.parse(data.errors); let errorsText = Object.entries(errors) .map(([field, errors]) => { return errors.map(error => `${error.message}`).join('\n'); }) .join('\n'); showToast(`${data.detail}\n${errorsText}`, "danger"); } } catch (error) { console.log(error); showToast(gettext("Произошла ошибка. Повторите попытку позже."), "danger"); } } individualOrderForm.addEventListener( 'submit', function (e) { e.preventDefault(); sendAjax(individualOrderForm); }, {passive: false} ); } ); <form id="individual-order-form" action="{% url 'mainpage:individual-order-negotiate' %}" method="POST" class="d-flex w-100 flex-column justify-content-start align-items-start text-start card-body"> <fieldset class="w-100"> <legend class="text-center"> <h2 class="fs-4 fw-normal" id="contact-us"> {% translate 'Свяжитесь с нами' %} </h2> </legend> <div class="form-text">{% translate 'Заполните форму, чтобы заказать букет из индивидуального состава.' %}</div> {% csrf_token %} <div class="mb-3 w-100"> <label for="customerNameInput" class="form-label">{% translate 'Имя' %}</label> <input class="form-control text-start" id="customerNameInput" aria-describedby="nameHelp" name="first_name" required> </div> <div class="mb-3"> <label for="contact-method-input" class="form-label"> {% translate 'Тел. номер в любой соц. сети или ссылка профиля' %} </label> <div class="d-flex"> {{ individual_order_form.contact_method }} </div> </div> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input checkbox-dark" id="recallCheckbox" name="recall_me"> <label class="form-check-label" for="recallCheckbox"> <small> {% translate 'Разрешаю мне перезвонить' %} </small> </label> </div> … -
How can I use multiple routers for a Django Rest Framework project?
I am facing a hard time on trying to use a router for an app and another for another app. # api/urls.py from django.urls import path, include from .views import UserViewSet, DepartmentViewSet, UserLoginView, UserTokenRefreshView router = DefaultRouter() router.get_api_root_view().cls.__name__ = "E.R.P. API" router.get_api_root_view().cls.__doc__ = "API do ERP" router.register('users', UserViewSet, basename='user') router.register('departments', DepartmentViewSet, basename='department') app_name = 'api' urlpatterns = [ path('login/', UserLoginView.as_view(), name='login'), path('token/refresh/', UserTokenRefreshView.as_view(), name='token_refresh'), path('', include(router.urls)), path('history/', HistoryView.as_view(), name='history'), ] # mobile_app/urls.py from django.urls import path, include from .views import CustomerLoginView mobile_app_router = DefaultRouter() mobile_app_router.get_api_root_view().cls.__name__ = "Mobile App API" mobile_app_router.get_api_root_view().cls.__doc__ = "API do Aplicativo Mobile" app_name = 'mobile_app' urlpatterns = [ path('login/', CustomerLoginView.as_view(), name='login'), path('', include(mobile_app_router.urls)) ] # erp/urls.py from django.contrib import admin from django.urls import path, re_path, include from . import settings from django.conf.urls.static import static from notifications import urls as notifications_urls urlpatterns = [ path('api/', include('api.urls'), name='api'), path('api/m/', include('mobile_app.urls'), name='api_mobile'), path('', admin.site.urls), re_path(r'^inbox/notifications/', include(notifications_urls, namespace='notifications')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The name and doc are being mixed, if I try to use a swagger or redoc (drf_yasg) the urls are mixed. It is like they are the same. How can I do it corectly? I tried to use multiple routers for a Django Rest Framework and … -
django-crispy-forms split form in two divs layout
I want to split a form into two divs with their own css_id so I can ajax update second div based on choices in the first. Problem is that my resulting form does not have divs with ids 'pbid' and 'pb-options' class PBForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.layout = Layout( Div('cc', 'pb_id', css_id="pbid"), Div('closed_r', 'closed_l', css_id="pb-options") ) pb_id = forms.ChoiceField(label='PB', widget=forms.RadioSelect) closed_l = forms.ChoiceField(label='Left Closed', widget=forms.RadioSelect, choices=BOOL_CHOICES) closed_r = forms.ChoiceField(label='Right Closed', widget=forms.RadioSelect, choices=BOOL_CHOICES) class Meta: model = pb fields = ['cc', 'pb_id', 'closed_r', 'closed_l'] -
Django Diagnosis Data Not Appearing in Admin After Endpoint Execution
I am working on a Django project where I process mock patient data and save it to a DiagnosisResult model in the database (SQLite). The goal is for this data to appear in the Django admin interface, but after calling the endpoint, the data doesn't appear in the database or admin. By "mock," I mean fictional data (not testing framework mocks), which I pre-generated to avoid using real patient data. Hers is my Minimal Reproducible Example (In order: models.py, views.py, urls.py, sample JSON data, Dockerfile, docker-compose.yml): models.py from django.db import models class Subtype(models.Model): CATEGORY_CHOICES = [('Acute', 'Acute'), ('Chronic', 'Chronic')] category = models.CharField(max_length=20, choices=CATEGORY_CHOICES) name = models.CharField(max_length=100) def __str__(self): return self.name class DiagnosisResult(models.Model): patient_name = models.CharField(max_length=100) age = models.IntegerField() symptoms = models.TextField() # Comma-separated list of symptoms test_results = models.TextField() likely_diagnoses = models.ManyToManyField(Subtype) def __str__(self): return f"{self.patient_name} (Age: {self.age})" views.py import json from pathlib import Path from django.http import JsonResponse from .models import Subtype, DiagnosisResult # File paths IS_DOCKER = Path("/app").exists() # Check if running inside Docker MOCK_DATA_FILE = ( Path("/app/apps/diagnosis/mock_data/mock_diagnosis_inputs.json") if IS_DOCKER else Path(__file__).resolve().parent / "mock_data" / "mock_diagnosis_inputs.json" ) def process_and_save_mock_diagnoses(request): with open(MOCK_DATA_FILE, "r") as file: mock_data = json.load(file) results = [] for patient in mock_data: likely_subtypes = Subtype.objects.filter(category="Acute") diagnosis_result … -
Django display edited time only for edited comments
This is my model for Comment class Comment(models.Model): content = models.TextField() dt_created = models.DateTimeField(auto_now_add=True) dt_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") def __str__(self): return f"Comment by {self.author.username} on {self.post.title}" and I am trying to display edited time if edited time != created time in the template <div class="comment"> <div class="comment-meta"> {{comment.author.nickname}} | Date: {{comment.dt_created|date:"M, d Y H:i"}} {% if comment.dt_created != comment.dt_updated %} | Last edited: {{ comment.dt_updated|date:"M d, Y H:i" }} {% endif %} </div> <div class="comment-content">{{comment.content}}</div> </div> ... But somehow it is displaying dt_updated for all comments even the ones that are not edited. I tried changing the code to check if it displays date when dt_created==dt_updated and it actually didn't display the edited time for all comments, including the comments that were edited. I also tried using comment.edited and it also didn't display edited time for all comments. What is wrong with my code? -
How to call and process Confirmation popup from a service function without interrupting the transaction
In my Django project, the business logic is placed in the service layer. Views only perform the function of working with templates. I have a basic template with a form and select type fields on it. When any field is changed, the script sends an AJAX request to views. views accepts this request and passes the data to a service function that uses it to write to the DB. template -> views -> service -> model Now I need to make a function to call the Confirmation popup from service to confirm the data change, receive a response from the window and process it. I already have a modal window and a script that calls it when response.confirmation_dialog. I need a mechanism for calling this window from the service without interrupting the transaction. One of the implementation options was to send a response to template with a confirmation modal call. Clicking the confirm-button on it would again send an AJAX request to views with confirmation information. Then this information would be sent back to the service, which checked whether the confirmation was passed or not. However, even with one confirmation, it looks bad, and the service may need several checks … -
Implementing Offline Updates for a Django REST Framework Project - Best Approach?
I'm building a Django REST Framework (DRF) application and am exploring ways to handle offline updates for my users. The goal is to allow users to access updated version of my project with a flash usb or something like that. as my clients does not have any special technical knowledge(like how to pull a repo or even how to deploy a project on their servers) i need to provide an easy way to let them update and use latest features. Now specifically, I'd like to know: Best practices for implementing offline updates in a DRF project Recommended libraries or frameworks to simplify this process Tips for managing data synchronization and version control for offline updates