Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pull up Django model data based on ALREADY filled out form fields for other ForeignKeys
I have a form in which there are several fields with foreign keys. For example, the table "Entrance" (3 entries -> 1st entrance, 2nd entrance, 3rd entrance), "Apartment" (30 entries, 10 for each entrance (No.1-10, No. 11-20 and No. 21-30), "Owner" (also 30 entries of surnames). In turn, the "Owner" has an external key to the apartment, and the "Apartment" has an external key to the entrance. here's the question, if I selected entrance No. 2 in the form, then in the other two fields (Apartment and Owner) I need to display ONLY related records (that is, apartments from 11 to 20 rooms, and the owners who live in these apartments) how to implement it??? here is the code in forms.py(naturally, it gives out an error, I just pointed out where, logically, I wanted to get involved.) ` id_entr = ModelChoiceField(queryset=Bs_entrance.objects.all(), widget=Select( attrs={'class': 'form-select', 'placeholder': 'выберите подъезд'})) id_apart = ModelChoiceField(queryset=Bs_entrance.objects.filter(id_entrance=**id_entr**), widget=Select( attrs={'class': 'form-select', 'placeholder': 'выберите квартиру'})) id_owner = ModelChoiceField(queryset=Bs_apartment.objects.filter(id_apartment=**id_apart**), widget=Select( attrs={'class': 'form-select', 'placeholder': 'выберите собственника'})) ` enter image description here Here is an example of the form (the example is not on apartments)There are all kinds of fault groups, although there should have been only two, since the ballast was … -
Can't get Cursor to work with Django linting
I have Python code in a Django project that says: x = models.DecimalField(max_digits=18, decimal_places=2, default='0.00') In Cursor, I get a Linter error from pylance: "No overloads for "__new__" match the provided argumentsPylancereportCallIssue" I have "python.analysis.django": true, in my settings.json, but it is greyed out. The code runs fine interactively, and when I run pylance from the terminal it doesn't flag this error. I have the django-stubs package installed in my venv. It seems like pylance in Cursor doesn't know about Django, and I can't figure out why. Any suggestions most appreciated! -
How to Efficiently Manage JWT Authentication (Refresh & Access Tokens) in React Without Repeated Server Calls and Implement a Centralized Alert System
I'm working on a React application that requires JWT authentication with both access and refresh tokens. I want to manage the authentication process in a way that prevents multiple requests for the refresh token and handles token expiration smoothly. Additionally, I want to centralize the alert system for handling success, error, and informational messages across the entire application. ** What I want to achieve:** JWT Authentication: Proper handling of access and refresh tokens in the React app. When the access token expires, I want to refresh it using the refresh token, but without making repeated server requests or causing race conditions. Automatically retry the original request after refreshing the access token. Centralized Alert System: I need an alert system that can handle and display error messages from API responses (both nested and non-nested). The alert system should be available globally across all components. Alerts should be dynamically triggered based on different responses (error, success, etc.). Problem: I use the Djoser for backend handling and react for frontend handling I’m confused about how to manage the refresh token mechanism without making repeated calls to the server or causing race conditions. I’m also trying to implement a centralized alert system that works … -
Update a field of a Django Model class from another class linked through a OneToOne Relationship
I'm on Django 5.0.4. I'm building an API using DRF. I'm new to DRF. I have 2 django models which looks like this : class PostVideo(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='videos', null=True) width = models.PositiveIntegerField(editable=False, null=True) height = models.PositiveIntegerField(editable=False, null=True) duration = models.FloatField(editable=False, null=True) file = VideoField(width_field='width', height_field='height', duration_field='duration', storage=post_image_storage, upload_to=upload_to_post_video_directory, blank=False, null=True) video_type = (('regularvideo', 'regularvideo'),('gridvideo', 'gridvideo'),('livevideostream', 'livevideostream')) mediaviewtype = models.CharField(max_length=24, choices=video_type, default='') class LiveVideoStream(models.Model): parent = models.OneToOneField(Post, related_name='live_video_stream', blank=False, null=True,on_delete=models.CASCADE) stream_uuid = models.CharField(_('uuid'), null=False, editable=False, unique=False, max_length=settings.LIVE_VIDEO_STREAM_UUID_MAX_LENGTH) streamer = models.ForeignKey(User, related_name='live_video_streams', on_delete=models.CASCADE) started_at = models.DateTimeField( default=timezone.now, blank=False, editable=False,null=False) video = models.OneToOneField(PostVideo, related_name='live_video_stream', blank=False, null=True,on_delete=models.CASCADE) def create_live_video_stream_post(cls, parent, stream_uuid, streamer,started_at): return cls.objects.create(parent=parent,stream_uuid=stream_uuid,streamer=streamer, started_at=started_at) My objective is to update the mediaviewtype in the PostVideo class with the value ‘livevideostream’ when i create a PUT request to create a Live Video Stream Post using the create_live_stream_post method above. I’m not sure how to do it.I get the value of mediaviewtype which is 'livevideostream' from my frontend flutter app and I process it via a Serializer, but I get stuck when I think how to update the value of mediaviewtype in model PostVideo.* The view to create a live stream post : def put(self, request): query_params = request.data.dict() serializer = LiveVideoStreamRequestSerializer(data=query_params) serializer.is_valid(raise_exception=True) … -
Real time vechile tracking using django channels and react
I want to implement real time tracking for vehicles but I don't know most of my things are not working. I use the geolocation API to get current device location and send those locations(latitude, longitude) to backend every five seconds. Then using django channels and Daphne I implement routing APIs I will use in react with the websockets but things take a delay to respond. I was requesting for yhe way I can design the database efficiently and the way I can handle the websocket connections I tried to create the real time tracking using leaflet maps so that I can see the image move smoothly on the map but it just jumps or let me say it doesn't work as expected -
Facing configuration problem with the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?
connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Request Method: Django Version: 3.2.4 Exception Type: OperationalError Exception Value: connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Exception Location: /home/ebong/djangoproject/djangoprojectenv/lib/python3.10/site-packages/psycopg2/init.py, line 122, in connect Python Executable: /home/ebong/djangoproject/djangoprojectenv/bin/python Python Version: 3.10.12 Python Path: ['/home/ebong/djangoproject/smsdigo', '/home/ebong/djangoproject/djangoprojectenv/bin', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/ebong/djangoproject/djangoprojectenv/lib/python3.10/site-packages'] Server time: Wed, 25 Dec 2024 04:11:09 +0000 This happens when a user tries to login into the website. The website is hosted by digital ocean droplet on django, gunicorn, nginx and postgres. For some reasons, I had reported server, then this problem occured. I have tried the following below. Restarted my postgresql using sudo systemctl restart postgresql I have done changes in postgresql.conf and pg_hba.conf postgresql.conf file below listen_addresses = '*' data_directory = '/var/lib/postgresql/14/main' # use data in another directory # (change requires restart) hba_file = '/etc/postgresql/14/main/pg_hba.conf' # host-based authentication file # (change requires restart) ident_file = '/etc/postgresql/14/main/pg_ident.conf' # ident configuration file # (change requires restart) # If external_pid_file is not explicitly set, no extra PID file is written. external_pid_file = '/var/run/postgresql/14-main.pid' # write an extra … -
Microservice with django
i tried turning an old project to see if i make it work as microservices it is a chat application i separated them into two auth service(which handles registration, login, contacts and emails) chat service (which handles chatting with contacts) the auth service works perfectly but i am having issues in the chat service first let me send the models class Message(models.Model): sender_id = models.IntegerField() # Store user IDs instead of foreign keys receiver_id = models.IntegerField() message = models.TextField() timestamp = models.DateTimeField(default=timezone.now) is_read = models.BooleanField(default=False) def __str__(self): return f"Message from {self.sender_id} to {self.receiver_id} at {self.timestamp}" since i cannot reference foreign key i am using integerfield i also made a custom middleware that verifies the token entered when th chat endpoint is called class SimpleUser: def __init__(self, user_id, email, full_name, is_active): self.id = user_id self.email = email self.full_name = full_name self.is_active = is_active @property def is_authenticated(self): return True @property def is_anonymous(self): return False def __str__(self): return f"{self.full_name} ({self.email})" class AuthenticateJWTMiddleware: AUTH_SERVICE_URL = "http://127.0.0.1:8800/api/auth/verify_token/" def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path.startswith('/admin/'): return self.get_response(request) self.process_request(request) response = self.get_response(request) return response def process_request(self, request): print(f"Middleware Processing: Path={request.path}") token = self.get_token_from_headers(request) if not token: print("No Authorization token found.") request.user = AnonymousUser() … -
How Connect Tkinter With django using zerorpc?
i have tkinter app want connect and send data to django project using zerorpc on local host its work nice but after deploy django on ubuntu server with gunicorn & nginx and open port 4242 on ufw still dosen't work. when i check gunicorn status i get error on: Exception in thread Thread-l (verificate): Traceback (most recent call last): File'/usr/lib/python3.12/threading.py',line 1075, in _bootstrap_inner self.run() File'/usr/lib/python3.12/threading.py',line 1012, in run self._target(*self._agrs, **self._kwargs) File '_zmq',line 732, in zmq.backend.cython._zmq.Socket.set TypeError: set() takes exactly 2 positional arguments (3 given) i bind django gunicorn and nginx pass proxy on address: 0.0.0.0:8000 i try also bind django gunicorn and nginx pass proxy on address: 127.0.0.1:8000 i use zerorpc python module on python tkinter and django app tkinter client connect django using zerorpc on address: connect('tcp://serverip:4242') django has function to listen on port 4242 but i use thread module to run this function with django views in sametime. i open port 8000 and 4242 and 80 and 443 and tcp and nginx full -
ClientException: XMLHttpRequest error. Flutter WEB
I get this error in my app. and once i get this error, even though im catching it. it stops all my api requests to my back end django server from working steps to reproduce: i call an api to my django rest framework back end. works fine. i shut off my back end server ( to simulate an outage) api call from my flutter web app is then again made to a server that is not online a ClientException: XMLHttpRequest error. is thrown. which is caught. i turn my server back on. and then no further api calls are made to the back end. Is there any way around this in flutter web? (without disabling web security) -
DuckDB, Django and apache2 Permission Denied in production
I have a problem with my duckdb database, that I really don't seem to understand. After I created a .db database and put it in the apache2/Django webapp root and gave www-data access to it and its directory, I still get permission denied. Here's the weird part(s): I don't get the permission error when I establish the connection, I only get it in the fetchdf() part. con = duckdb(database='path/to/db.db',read_only=True) P = con.execute('SELECT * FROM products LIMIT 1;') p = p.fetchdf() # Here's where the error gets thrown ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ duckdb.duckdb.IOException: IO Error: Permission denied When I run the same python code with the www-data, everything works nice. Also in the runserver situation it works without a problem. It seems that the issue is related the production environment. I suspect that duckdb wants access to a certain directory or file that I have to make available in the apache2 config, but me and AI didn't know what or where. Any help? I tried changing the temp_directory, home_directory, extension_directory, and secret_directory to a directory within the webapp root directory. I tried moving the db file to a different dir and gave apache permission to it also in the .conf. -
Can't create second celery queue
I want to create two celery queues (for different types of tasks) My celery configuration. I expect that this config creates two queues 'celery' and 'celery:1' # celery.py import os from celery import Celery from core_app.settings import INSTALLED_APPS # this code copied from manage.py # set the default Django settings module for the 'celery' app. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings') app = Celery("my_app") # To start scheduling tasks based on priorities # you need to configure queue_order_strategy transport option. app.conf.broker_transport_options = { 'queue_order_strategy': 'priority', } # ['celery', 'celery:1',] - two queues, the highest priority queue will be named celery app.conf.broker_transport_options = { 'priority_steps': list(range(2)), 'sep': ':', 'queue_order_strategy': 'priority', } # read config from Django settings, the CELERY namespace would make celery # config keys has `CELERY` prefix app.config_from_object('django.conf:settings', namespace='CELERY') # load tasks.py in django apps app.autodiscover_tasks(lambda: INSTALLED_APPS) I am defining and running celery task like this: @shared_task(queue="celery", soft_time_limit=600, time_limit=650) def check_priority_urls(parsing_result_ids: List[int]): check_urls(parsing_result_ids) @shared_task(queue="celery:1", soft_time_limit=600, time_limit=650) def check_common_urls(parsing_result_ids: List[int]): check_urls(parsing_result_ids) # running task check_priority_urls.delay(parsing_results_ids) But I see only one queue celery -A core_app inspect active_queues -> celery@d1a287d1d3b1: OK * {'name': 'celery', 'exchange': {'name': 'celery', 'type': 'direct', 'arguments': None, 'durable': True, 'passive': False, 'auto_delete': False, 'delivery_mode': None, 'no_declare': False}, 'routing_key': 'celery', 'queue_arguments': None, 'binding_arguments': … -
Django model migration from standard model to multi-table inherited model with FK relations
I have a task to migrate some existing models to multi-table inherited models (make them subclass of existing parent). I'm testing my code on local machine and I've managed to enforce multi-table inheritance without faults. However some models are ForeignKeys linked to another models and I'm wondering how to manage such relations swap to avoid data lose. Example: class Member(models.Model): pass class Person_A(models.Model): member_ptr = OneToOneField(parent_link=True) class Person_B(models.Model): member_ptr = OneToOneField(parent_link=True) class Group(models.Model): person_a = models.ForeingKey(Person_A) person_b = models.ForeignKey(Person_B) So, Person_A and Person_B are on their way to be inherited from Member. All Member instances created and data prepopulated. Remains last step to remove _ptr field replacing models.Model with Member at the same time which causes drop of id field so ForeignKey link will be broken. Is there an easy way to manage this ForeignKey transfer without data lose? I have some weird ideas of field duplications etc. but hoping there is some more convinient way. -
how to know which field(category) most used
have query like this Product.objects.filter( title__icontains=self.query, # something to get most used category id ).values('id', 'is_featured').order_by('-is_featured', 'rank', '-created') what I want is. With one query can I get most used category id and above result. Note: order by should not be changed. is that possible?. this is my model looks like class Product(BaseModel): category = models.ForeignKey( 'tag_map.Category', on_delete=models.PROTECT, blank=False, null=False, verbose_name=_("Category of product"), ) class Category(BaseClassification): name_uz = models.CharField(max_length=200) name_ru = models.CharField(max_length=200) slug = models.SlugField(max_length=220, unique=True) rate = models.PositiveIntegerField() position = models.PositiveIntegerField() parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) -
how to create a form using multiple models in django?
So I am trying to make a student result management project.Where I can add students subhect grade and exam result.In the project i need to make a form where i can add marks of a subject to all the students of a grade(Class) at once.I want the look like the photo.Example Example . I tried to create individual form for every sector and try to combaine them.But it didn't work.Now I need to know how can I make a form using many models in django [Sorry for my Bad English ] -
Django Rest Framework - Nested Serializer Attribute error in response
wondering if someone could help me with the following problem. I have a serialises such as this: class LineupPlayerSerializer(serializers.ModelSerializer): id = serializers.UUIDField(write_only=True) name = serializers.CharField(read_only=True) positionType = serializers.CharField(read_only=True) alternativePositions = serializers.CharField(read_only=True, required=False, allow_blank=True) shirtNumber = serializers.IntegerField(read_only=True, required=False, allow_null=True) positionOnPitch = serializers.IntegerField(required=True) class Meta: model = LineupPlayer fields = ['id', 'positionType', 'alternativePositions', 'name', 'shirtNumber', 'positionOnPitch'] def create(self, validated_data): player_id = validated_data.pop('id') player = Player.objects.get(id=player_id) position_on_pitch = validated_data.pop('positionOnPitch') lineup = validated_data.pop('lineup') lineup_player = LineupPlayer.objects.create(lineup=lineup, player=player, positionOnPitch=position_on_pitch) return lineup_player class LineupSerializer(serializers.ModelSerializer): players = LineupPlayerSerializer(many=True) class Meta: model = Lineup fields = ['id', 'formation', 'players'] def create(self, validated_data): try: players_data = validated_data.pop('players') lineup = Lineup.objects.create(**validated_data) for player_data in players_data: player_data['lineup'] = lineup LineupPlayerSerializer().create(player_data) return lineup except Exception as e: print(f"Error: {e}") raise e However, when I send the request I get an Attribute error: Got AttributeError when attempting to get a value for field `positionOnPitch` on serializer `LineupPlayerReadSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Player` instance. Original exception text was: 'Player' object has no attribute 'positionOnPitch'. For some reason Django thinks that the positionOnPitch is in the Player model and I can't figure out how. When I use write_only=True for positionOnPitch it sends the … -
Efficient way to get relationship data
I have a Modal ABC and a field named GROUP which is a foreign key, and this model Abc is also used as a foreign key in another model XYZ. My requirement is that when I view the list of XYZ with filters such as (whse="01" and abc="02") I want to get the name of the group(from model abc) along with the list data of the XYZ model. class ABC(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) class XYZ(models.Model): abc = models.ForeignKey(ABC, on_delete=models.CASCADE) whse = models.ForeignKey(WHSE, on_delete=models.CASCADE) qty = models.CharField() What I do right now is - in serializer I define a SerializerMethodField() fields. here is the code - class XYZSerializer(serializers.ModelSerializer): groupName = serializers.SerializerMethodField() def get_groupName(self, instance): return instance.abc.group.name if instance.abc else '' class Meta: model = ZYX fields = '__all__' I get my desired result but you can see that my filter requirement is always (whse="01" and abc="02") on the XYZ model and so the value of get_groupName is always going to remain the same for each of my requests (my abc is always the same in the output list, so will be the group name). How can I format my data, serializer to reduce the database query, (to find groupName) for … -
Appending Wagtail StructBlock to Streamfield
is there a good way to append a StructBlock into an existing StreamField? I'm building a links page where non admin users can add their own links. I would like to be able to append a LinkBlock using form data. I'm attaching what I have right now and currently stepping through the Wagtail source code to better understand how blocks are created. class LinkBlock(blocks.StructBlock): title = blocks.CharBlock(required=True, help_text="Link title") url = blocks.URLBlock( required=True, help_text="Link URL", ) class LinksPage(Page): links = StreamField( [ ("link", LinkBlock()), ], blank=True, use_json_field=True, max_length=20 ) content_panels = Page.content_panels + [ FieldPanel("links"), ] # Adding dynamic links with form data links_page.links.append( ( "link", { "title": form.cleaned_data["title"], "url": form.cleaned_data["url"], "link_type": form.cleaned_data["link_type"], "color_scheme": form.cleaned_data["color_scheme"], }, ) ) try: # TODO: Investigate why this is necessary # links_page.links._raw_data = [lnk for lnk in links_page.links._raw_data if lnk is not None] # without the filter above, we get a TypeError when trying to save the page links_page.save() except TypeError as e: logger.error(f"Error saving link: {e}") raise e """ Example stack trace: File "../.venv/lib/python3.13/site-packages/wagtail/blocks/stream_block.py", line 680, in __getitem__ self._prefetch_blocks(raw_value["type"]) ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^ File "../.venv/lib/python3.13/site-packages/wagtail/blocks/stream_block.py", line 710, in _prefetch_blocks raw_values = OrderedDict( File "../.venv/lib/python3.13/site-packages/wagtail/blocks/stream_block.py", line 713, in <genexpr> if raw_item["type"] == type_name and self._bound_blocks[i] is None … -
UnicodeDecodeError with socket.getfqdn in Django runserver on Windows
I’m building a Django API. After transferring my project to a new server and attempting to run it with: python manage.py runserver I encountered the following exception: File "", line 795, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) ^^^^^^^^^^^^^^^^^^^ UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 19: invalid start byte I verified my hostname using the hostname command in the terminal. It returned: DESKTOP-KTU1TC2 (consists of only ASCII characters). I have also run this code, but everything works just fine. >>>import socket >>>socket.gethostbyname('127.0.0.1') 127.0.0.1 >>>socket.gethostbyname('DESKTOP-KTU1TC2') (some ip address) I have also tried to explicitly start the server with: python manage.py runserver 127.0.0.1:8000 The error persists. Environment Details: Python: 3.12 Django: 5.1.4 What should i try to resolve this issue? Thank you in advance -
MAUI / Django Serializer - Trailing slash added
I have a MAUI app that connects to an API to collect some data. I am handling the API width django. Whatever I try, it seems a trailing slash is added automatically at the end of the path which creates an error. logs: method=GET path="/api/some-model/?userprofile_id=105/" Received userprofile_id: 105/ Error during processing: Field 'id' expected a number but got '105/'. On the API side the trailing slash does not appear, which makes me think its on the server side. int userId = int.Parse((Shell.Current as AppShell).userID); string url = $"api-path/?userprofile_id={userId}"; # url = api-path/?userprofile_id=105 API<List<Model>>.Get( url, OnModelSuccess, OnModelError); On Django side, I have set APPEND_SLASH = True and listed below the path of my api: router.register(r'api-path', APIPATHViewSet, basename='apipath') Any idea how I could remove the trailing slash from the request? -
Django with uwsgi not service static files
I am running a django app using uwsgi and docker. When i open the admin panel, it's all messed up. I figured it's because the static files are giving 404. How do i fix this? uwsgi.ini: static-map = /static=/app/static static-expires = /* 7776000 offload-threads = %k settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') I have run collectstatic and verified static dir exists in docker container Dockerfile FROM python:3.10-slim # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set working directory WORKDIR /app # Install system dependencies RUN apt-get update \ && apt-get install -y software-properties-common python3-launchpadlib \ && add-apt-repository ppa:savoury1/ffmpeg4 \ && apt-get update \ && apt-get install -y --no-install-recommends gcc libpq-dev ffmpeg libc-dev \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY Pipfile Pipfile.lock /app/ RUN pip install pipenv && pipenv install --system --deploy # Copy project files COPY . /app/ # Expose the port the app runs on EXPOSE 8000 # Run the Django app CMD ["uwsgi", "--http", "0.0.0.0:8000", "--module", "yt_automation.wsgi:application", "--ini", "uwsgi.ini"] -
why I get error when I use href="{{ panel.get_absolute.url }}" in my templates?
I wrote a simple page to show a list of goods that when you click on each of them it forwards you to the purpose page to show the good's details, but I think this method doesn't work right now or I have a mistake ... this is my model: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class PanelManager(models.Manager): def ye(self,year): return self.filter(publish__year=year) def pu(self,publish): return self.filter(status=publish) class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset().filter(status='published') class Panel(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') author = models.ForeignKey(User, on_delete=models.CASCADE) objects = PanelManager() published = PublishedManager() # objects = models.Manager() def get_absolute_url(self): return reverse('users:details',args=[self.slug, self.id]) class Meta: ordering = ('-publish',) def __str__(self): return self.title my views: from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse from .models import Panel def test1(request): return HttpResponse("Hello this is test1") def panellist(request): panels=Panel.objects.filter(publish__year=2024) return render(request, 'users/panel/panel list.html',{'panels':panels}) def p_details(request,panel, pk): panel=get_object_or_404(Panel,slug=panel,id=pk) return render(request, 'users/panel/details.html', {'panel':panel}) my urls: from django.urls import path from .import views urlpatterns = [ path('panellist/', views.panellist, name='panellist'), path('details/<slug:panel>/<int:pk>/', views.p_details, name='details'), ] my … -
Prevent Django DetailView from adding template context with name of object
I have a DetailView for users, and it seems to be adding a user context variable. This is problematic because I have an application-wide context variable, user that contains the current user that is being overridden. How can I prevent the DetailView from adding this context variable? -
Error related to connecting Django from Docker to Nginx
I am currently working on Docker and have done the following: The Django test page was working fine on localhost. I connected it to Docker. I also connected Docker to Gunicorn. However, when I try to connect it through Nginx, only the default Nginx page is displayed, and it is not connecting to the application I created. nginx/Dockerfile FROM nginx:latest RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d # nginx/nginx.conf upstream daniel_blog { server web:8000; } server { listen 80; server_name localhost; # Default location location / { proxy_pass http://daniel_blog; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } # Static files location /static/ { alias /usr/src/app/_static/; } # Media files location /media/ { alias /usr/src/app/_media/; } } --- # .env.dev DEBUG="1" SECRET_KEY="django-insecure-88ndzs0z0uzko4x5f=*ngu=#h+a(k=!#ooyvt*0h+78r1n=^oy" DJANGO_ALLOWED_HOSTS = localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=daniel_blog_dev SQL_USER=daniel_blog_user SQL_PASSWORD=daniel_blog_db_password SQL_HOST=db SQL_PORT=5432 --- # .env.prod DEBUG=0 SECRET_KEY=w4+=--yyyigm1-=na@9et*1ldt-q-x4x=57m2xkiru6!oxeh5b DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=daniel_blog_prod SQL_USER=daniel_blog_user SQL_PASSWORD=daniel_blog_db_password SQL_HOST=db SQL_PORT=5432 --- # .env.prod.db POSTGRES_USER=daniel_blog_user POSTGRES_PASSWORD=daniel_blog_db_password POSTGRES_DB=daniel_blog_prod --- # docker-compose.yml services: nginx: build: ./nginx volumes: - static_volumes:/usr/src/app/_static - media_volumes:/usr/src/app/_media ports: - 80:80 depends_on: - web web: build: . command: gunicorn daniel_blog.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volumes:/usr/src/app/_static - media_volumes:/usr/src/app/_media - ./:/usr/src/app/_media expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:17.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ … -
Sorting a string before a number with Postgres and Django
I want to use fuzzy dates for sorting a Django query, so you can use a full date if you have it, but maybe you only know year and month. For example, Jan XX 2024 would come before Jan 1 2024 and Jan 2 2024. I was originally planning to store as a string 202401XX, 20240101, etc, but Postgres naturally sorts characters after numbers so this would put the date with no day AFTER the date with day specified. I was thinking of converting the 20240101 to letters before saving to the database (X=A, 0=F, 1=G, etc) since this is a computationally cheap thing and I could control where everything sorted. Is this a terrible idea? Is there a better way? I don't want to do a custom Postgres query because that would be complicated with Django's built-in pagination -
Is there way to display historical records for all model instances using django-simple-history?
I am using django-simple-history for saving history of the objects. And it works fine. But I want to create a view in django admin that displays history records for all instances in model in one page. For example I have a model class TestModel(models.Model): title = models.CharField('title', max_length=100) history = HistoricalRecords() and admin class TestModelAdmin(SimpleHistoryAdmin): list_display = ['title'] admin.site.register(TestModel, TestModelAdmin) And now I can see the history of each instance. Not sure how I can solve this problem. May be there is a way to create custom views in admin site (without model), or maybe I should create another model? What's the best way to display all history records (for all instances) in admin panel?