Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I send a PDF from Python to PHP?
I try to create a PDF file in Python and send it to PHP. When I open the PDF it's corrupted. Python code: from reportlab.pdfgen import canvas from io import BytesIO from django.http import HttpResponse def generar_pdf(): buffer = BytesIO() c = canvas.Canvas(buffer) c.drawString(50, 50, "¡Hola, mundo!") c.save() pdf_bytes = buffer.getvalue() return HttpResponse(bytes(pdf_bytes), content_type='application/pdf') pdf_response = generar_pdf() print(pdf_response) PHP code: <?php $pdf_bytes = shell_exec("python prueba.py"); header('Content-Type: application/pdf'); header('Content-Disposition: inline; filename="archivo.pdf"'); echo $pdf_bytes; ?> I got: An error occurred while loading the PDF document. -
django-channels integration tests with pytest?
I am trying to create a simple live-server style test fixture for pytest for testing with django-channels. I came up with the simplest solution: import pytest @pytest.fixture(scope="function") def channels_live_server(request): from channels.testing import ChannelsLiveServerTestCase class MyChannelsLiveServerTestCase(ChannelsLiveServerTestCase): @property def url(self): return self.live_server_url server = MyChannelsLiveServerTestCase() server._pre_setup() yield server server._post_teardown() When used, the web server starts in the background and serves the web pages just fine... except it is using "production" settings, which means the database used is NOT the test database. Any ideas how to fix this? I do realize, that multiprocessing at some later stage is using Popen and starts the server using spawn context. I am on macOS, if that matters. -
Django proyect tring to integrate asgi
I have a django proyect that works with views and django-rest-framework and now i want to add channels to it. I have a django proyect that works with views and django-rest-framework and now i want to add channels to it so my Django project could support both HTTP and WebSocket connections. My question is there is a way of doing this? I have to rewrite my proyect to use asgi?. I found that channels_redis could do the thrick but I'm not sure -
Django REST ModelViewSet view returns 404 after PATCH
I have ModelViewSet view in django rest framework project. I am trying to filter documents that are not live, I mean are not on main view. To filter I am using params: http://localhost:8000/documents?is_live=false. I have list of records. After set true on one of objects I'm getting 404 error "GET /api/documents/?is_live=false HTTP/1.1" 200 test {'pk': '2', 'partial': True} Not Found: /api/documents/2/ Not Found: /api/documents/2/ "PATCH /api/documents/2/ HTTP/1.1" 404 "GET /api/documents/?is_live=false HTTP/1.1" 200 My view's code and custom filter (django_filters) are below: class DocumentFilter(dfilters.FilterSet): is_live = dfilters.BooleanFilter(field_name='is_live') class Meta: model = Document fields = ['is_live'] class DocumentViewSet(viewsets.ModelViewSet): serializer_class = DocumentSerializer queryset = Document.objects.all() filterset_class = DocumentFilter filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend] search_fields = ['title', 'category'] ordering_fields = [ 'title', 'category', ] def update(self, request, *args, **kwargs): print("test", args, kwargs) kwargs['partial'] = True return super().update(request, *args, **kwargs) @action(detail=True, methods=['patch']) def get_queryset(self): if self.request.query_params.get('is_live'): return self.queryset.filter(is_live=False) return self.queryset.filter(is_live=True) I would like to have possibility to partial update of object on filtered view. -
how should index.html be served with django gunicorn and nginx?
my webapplication entirely dockerized and is written with a django and gunicorn backend and an nginx frontend. nginx is needed as a proxy and to serve static files. nginx has access to the static files via mounted volume from django. I would like the entire frontend not as django templates. i'm not understanding if index.html can be directly managed by nginx like this first configuration. (first nginx.conf) or if the request should regardless firstly reach django and then, ascertained that the wanted file is a static file (index.html), be redirected with the url changed in /static/... so that can be caught by nginx. (second nginx.conf). Thanks for everyone that will eventually help me. Sorry if maybe my question is born out of ignorance and please feel free to teach me if needed. server { listen 443 ssl; bash Copy code # SSL/TLS configuration ssl_certificate /etc/ssl/certs/server.crt; ssl_certificate_key /etc/ssl/private/server.key; # Define the location of static files location / { root /var/www/html/static/; index index.html; } location /api/ { include proxy_params; proxy_pass http://backend:8000; } location /static/ { alias /var/www/html/static/; } } server { listen 443 ssl; bash Copy code # SSL/TLS configuration ssl_certificate /etc/ssl/certs/server.crt; ssl_certificate_key /etc/ssl/private/server.key; # Define the location of static files location … -
How to fix Gunicorn Timeout error in Django?
My Django app uses gunicorn as server. It allows users to upload files. Recently I've been getting the following error with some file uploads: 0%| | 0/1121 [00:00<?, ?frames/s][2024-06-19 18:59:53 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:7) 0%| | 0/1121 [00:06<?, ?frames/s] web-1 | [2024-06-19 13:59:53 -0500] [7] [INFO] Worker exiting (pid: 7) web-1 | [2024-06-19 18:59:53 +0000] [1] [ERROR] Worker (pid:7) exited with code 1 web-1 | [2024-06-19 18:59:53 +0000] [1] [ERROR] Worker (pid:7) exited with code 1. web-1 | [2024-06-19 18:59:53 +0000] [32] [INFO] Booting worker with pid: 32 Sometimes(even for the same file) I get the following error instead: [2024-06-18 08:56:09 -0500] [19] [INFO] Worker exiting (pid: 19) web-1 | [2024-06-18 13:56:10 +0000] [1] [ERROR] Worker (pid:19) was sent SIGKILL! Perhaps out of memory? web-1 | [2024-06-18 13:56:10 +0000] [34] [INFO] Booting worker with pid: 34 web-1 | /usr/local/lib/python3.11/site-packages/whisper/__init__.py:63: UserWarning: /root/.cache/whisper/tiny.pt exists, but the SHA256 checksum does not match; re-downloading the file web-1 | warnings.warn( 78%|█████████████████████████████ | 56.6M/72.1M [00:24<00:05, 2.74MiB/s][2024-06-18 13:57:18 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:34) 79%|█████████████████████████████ | 56.7M/72.1M [00:24<00:06, 2.42MiB/s] web-1 | [2024-06-18 08:57:18 -0500] [34] [INFO] Worker exiting (pid: 34) web-1 | [2024-06-18 13:57:19 +0000] [1] [ERROR] Worker (pid:34) exited with code 1 web-1 | … -
problem with leaving dynamic form in django
[enter image description here](https://i.sstatic.net/cwRzZ7Kg.png) I want the person to select the category in which they are going to post in order to render the form for that category, so far ok, but when they fill it out and press submit, nothing happens, why is this happening? I want the person to select the category in which they are going to post in order to render the form for that category, so far ok, but when they fill it out and press submit, nothing happens, why is this happening? -
how to display algorithm outputs from vs-code terminal into the pages of my webapp?
I have a python program in my Django app called grouping.py, I want to display the outputs of the program into my pages of my webapp.The program works as I want in the vs-code terminals but when I run the command python manage.py runserver in my CMD it displays the error File "C:\Users\aqa\Desktop\academic\academic_balancing\urls.py", line 9, in <module> path('',views.algorithm_output ,name='algorithm_output'), ^^^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'views' has no attribute 'algorithm_output' I tried the following : urls.py from django.urls import path import views urlpatterns = [ #algorithm template path('',views.algorithm_output ,name='algorithm_output'), ] views.py from django.shortcuts import render from grouping import form_groups # Create your views here def algorithm_output(request): #call algorithm frunction output = form_groups #pass output to the template return render(request,'academic_balancing/academic.html',{'output':output}) academic.html <!DOCTYPE html> <html> <body> <p>{{output}}</p> </body> </html> i need help to display the algorithm output to my django webapp pages -
When I try to install psycopg2-binary in my windows machine it throws error
I was trying to install the libraries from a requirements.txt file, and it throws below error. requirements.txt - psycopg2-binary==2.9.1 The Error Message looks like, Collecting psycopg2-binary==2.9.1 (from -r requirements.txt (line 6)) Using cached psycopg2-binary-2.9.1.tar.gz (380 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: psycopg2-binary Building wheel for psycopg2-binary (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for psycopg2-binary (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [20 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-312 creating build\lib.win-amd64-cpython-312\psycopg2 copying lib\errorcodes.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\errors.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\extensions.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\extras.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\pool.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\sql.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\tz.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\_ipaddress.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\_json.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\_range.py -> build\lib.win-amd64-cpython-312\psycopg2 copying lib\__init__.py -> build\lib.win-amd64-cpython-312\psycopg2 running build_ext building 'psycopg2._psycopg' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for psycopg2-binary Failed to build psycopg2-binary ERROR: Could not build wheels for psycopg2-binary, … -
Issues in Debugging a Dockerized Web App in VS Code
I am learning web development on my own through different youtube videos and books. I am using VS code and started building my own web app in Docker containers (read somewhere regarding benefits of using containers) . I have built a few apps within the project, however, as the apps are getting complex and complex it is difficult for me to debug the app for errors and see where am I going wrong. I am going to lay down the code I am using for docker files and task.json and launch.json. DOCKERFILE # For more information, please refer to https://aka.ms/vscode-docker-python FROM python:3-slim EXPOSE 8000 # Expose port for debugpy EXPOSE 5678 # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # Install debugpy for debugging RUN python -m pip install debugpy # Install pip requirements COPY requirements.txt . RUN python -m pip install -r requirements.txt WORKDIR /app COPY . /app # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser … -
How to disable verification peer in Django
In localhost my configuration works fine but in production i recieve a "Connection unexpectedly closed" error This is my configuration... EMAIL_HOST='xxxxxxx' EMAIL_PORT=25 EMAIL_HOST_USER='xxxxxxx' EMAIL_HOST_PASSWORD='xxxxxxx' DEFAULT_FROM_EMAIL=EMAIL_HOST_USER EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' -
Wrong path for my default image Django app
i'm making a music streaming website with Django and i want to display the playlists in the homepage. All is working exept for the palylists in which i didn't upload an image. I set a playlist default image but the browser doesn't find the default image because of the wrong path. How can i fix it? (Probably it's an easy thing but i'm new to Django...) html: {% for playlist in my_playlists %} <a href="{% url 'music:playlist' playlist.playlist_id %}"><img src="{{ playlist.image.url}}" alt="playlist image"></a> {% endfor %} models.py: class Playlist(models.Model): playlist_id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) playlist_name = models.CharField(max_length=50, default="name") image = models.ImageField(upload_to="playlist_images/", validators=[FileExtensionValidator(allowed_extensions=['jpeg', 'jpg', 'png'])], default="images/music-placeholder.png") plays = models.IntegerField(default=0) songs = models.ManyToManyField(Song, related_name='playlist') slug = models.SlugField() views.py: def homepage(request): songs = Song.objects.all() user = request.user if user.is_authenticated: my_playlists = Playlist.objects.filter(user=user) return render(request, 'homepage.html', {'songs': songs, 'my_playlists': my_playlists}) setting.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I got this error: Not Found: /media/media/images/music-placeholder.png but the path should be this /media/images/music-placeholder.png: -
How can I output a selection of Blog objects in a ListView in Django searched via ForeignKeys of two other different models?
I have three models like this: 1: class Blog(models.Model): title = models.CharField() published = models.DateField() ... 2: class AuthorList(models.Model): blog = models.ForeignKey(Blog) author = models.ForeignKey(User) lastTimeEdited = models.DateTimeField() ... 3: class CommentsList(models.Model): blog = models.ForeignKey(Blog) commentAuthor = models.ForeignKey(User) commentPosted = models.DateTimeField() ... My class based ListView looks like this: class DashboardView(LoginRequiredMixin, ListView): model = Blog template_name = 'app/dashboard.html' paginate_by = 5 def get_queryset(self) -> QuerySet[Blog]: user = self.request.user author = #HERE I want a queryset of all blogs, where the requested user is one of the authors. commentator = #HERE I want a queryset of all blogs, where the requested user is one of the commentators. blogs = author|commentator return blogs.order_by(#HERE I want to order them by the lastTimeEdited-Field or the commentPosted-Field) So I want to list all the blogs that the user has to do with in one way or another. I also want to order them by the lastTimeEdited value if the user is an author or by the commentPosted value if the user is a commenter. How can I do that? I've already looked for the solution in other posts, but couldn't find the right solution for my problem. -
Django timeslots not showing up in form
I am trying to build a Django booking system where I am trying to implement the logic that if a timeslot is booked for a certain day, that timeslot should not be clickable (disabled). And beside the timeslot it should read (booked). This is my implementation. But my logic is not working. No timeslots are showing up. Can anyone help me point out the problem here? Thanks! My models.py: class Timeslot(models.Model): start_time = models.TimeField() end_time = models.TimeField() slot_text = models.CharField(max_length=100) def __str__(self): return self.slot_text class Appointment(models.Model): name = models.CharField(max_length=100) phone = models.CharField(max_length=20) email = models.EmailField() date = models.DateField() timeslot = models.ForeignKey(Timeslot, on_delete=models.CASCADE) booked_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name} - {self.date} - {self.timeslot.slot_text}" My views.py: def check_availability(date): timeslots = Timeslot.objects.all() booked_timeslots = Appointment.objects.filter(date=date).values_list('timeslot', flat=True) available_timeslots = [(timeslot, timeslot.id not in booked_timeslots) for timeslot in timeslots] return available_timeslots def book_appointment(request): available_timeslots = [] form_data = {} if request.method == 'POST': name = request.POST.get('name') phone = request.POST.get('phone') email = request.POST.get('email') date = request.POST.get('date') timeslot_id = request.POST.get('timeslot') form_data = { 'name': name, 'phone': phone, 'email': email, 'date': date, 'timeslot': timeslot_id, } if 'check_timeslots' in request.POST: if date: available_timeslots = check_availability(date) else: messages.error(request, 'Please select a date to check available timeslots.') elif 'book_appointment' in … -
front end improvement suggestion [closed]
I was attempting to create an 'About Us' page, but as a backend Django engineer who has recently transitioned to frontend development, I'm not very experienced in making designs visually appealing and clean. Therefore, I'm seeking help to enhance its aesthetics. Initially, I tried using AI for assistance, but unfortunately, it didn't work as expected. I would greatly appreciate your support. [text]https://codepen.io/VIN0D-PANDEY/pen/xxNYamL none -
Django-crontab in a docker container: how to change cron working directory from "root" to "app"?
I am developping a django app relying on a mysql database. I am trying to schedule a django-crontab task to backup my database once a week (here every minute for testing). I need my app to work inside docker, I thus have one container running the app, and one container running the cronjob, both from the same image. When testing my django-crontab task in docker, by setting the command in my docker-compose to: command: python manage.py crontab run {taskhashid} the job successfully runs once and the container exists. So far so good. To run my job periodically in the forground of my container, I have changed the command to: command: cron -f. My task is here executed from "root" directory and always fails as the needed scripts are saved in "app" directory: # cat /var/log/cron.log The badge files are not found Current working directory: /root Contents of the current working directory: - .bashrc - .profile - .cache - .wget-hsts My dockerfile: # Use the official Python base image FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip # Install necessary dependencies RUN apt-get update && apt-get install -y \ default-mysql-client \ cron \ gcc \ python3-dev \ default-libmysqlclient-dev # … -
Why is the internal properties broken when loading the page
enter image description here It's not smooth when there is css vsf the attributes fall out 1 time to complete I want it to be the load area as above Please show me how to make it smooth when loading the page So that when loading the page, all interfaces are shown in the fastest way -
Django Admin Validate across normal fields and inlines
I have a model like with two ManyToMany relations and an corresponding admin class: The first relation included in "filter_horizontal" The second relation is an inline that is included in "inlines" Everything works fine as long as I don't need to add custom validation. When trying to implement a "check" method on the Model itself, the data for the inline model admin is not included. But I need access to the data from both relations at the same time. How can this be done? -
How to handle large task_kwargs in Celery to avoid ellipsis in TaskResult
I am using Celery for asynchronous task processing in my Django application. Some of my tasks involve handling large amounts of data passed as task_kwargs. However, I have noticed that when the task_kwargs are too large, the TaskResult shows the data with an ellipsis (...), indicating that the full data is not being stored or displayed. Here’s an example of what my task arguments look like: task_kwargs = { 'period': {'ydpedid': 50, 'period': 2, 'year': 2024}, 'sector': '1', 'routes': [ {'yddiaid': 1, 'code': '0102', 'descr': '0102'}, {'yddiaid': 5, 'code': '0104', 'descr': '0104'}, # Many more routes... ], 'user_id': 12345 } When I check the TaskResult, it shows the task_kwargs like this: "{'period': {'ydpedid': 50, 'period': 2, 'year': 2024}, 'sector': '1', 'routes': [{'yddiaid': 1, 'code': '0102', 'descr': '0102'} #more routes , ...}]}" the total length of task_kwargs is 1031 I am looking for a way to ensure that the entire task_kwargs is stored and visible in the TaskResult without truncation. Is there a specific configuration option I am missing or a recommended approach to handle large task_kwargs in Celery? -
Invoice updating with line items
I am building a clinic referral system that will be used to generate referrals which in turn is i used to generate an invoice. Am able to do CRUD operations for referrals now for invoices the Update is giving me issues. The following are my models: class Invoice(models.Model): TYPE_CHOICES = [ ('Medicine', 'Medicine'), ('Auxillary', 'Auxillary'), ('Mixed', 'Mixed'), ] patient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='inv', blank=True, null=True) reference = models.OneToOneField(Referral, on_delete=models.CASCADE, related_name='invoice', null=True) invoice_type = models.CharField(max_length=50, choices=TYPE_CHOICES, default='Medicine') amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) date = models.DateField(auto_now_add=True) due_date = models.DateField(null=True, blank=True) status = models.BooleanField(default=False) prepared_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='prepared_invoices', null=True, blank=True) def __str__(self): return str(self.patient.first_name) + " " + str(self.patient.last_name) def total_amount(self): tax_rate = 10 subtotal = sum(item.amount for item in self.lineitems.all()) tax_amount = (subtotal * tax_rate) / 100 # Calculate tax amount return subtotal + tax_amount def get_status(self): return self.status def save(self, *args, **kwargs): if not self.id and not self.due_date: self.due_date = datetime.now() + timedelta(days=15) super().save(*args, **kwargs) class LineItem(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name='lineitems', blank=True, null=True) service = models.TextField() description = models.TextField() quantity = models.IntegerField() rate = models.DecimalField(max_digits=9, decimal_places=2) amount = models.DecimalField(max_digits=9, decimal_places=2) def __str__(self): return str(self.invoice) my views: logger = logging.getLogger(__name__) class CreateInvoiceView(UserPassesTestMixin, FormView): template_name = 'referral/invoice_create.html' form_class = BillInvoiceForm … -
How to give different description to different url endpoints in drf-spectacular
I have the following views: @extend_schema(tags=["admin"]) class CompanyForAdminView(APIView): permission_classes = [IsAuthenticated, IsAdmin] filter_backends = [SearchFilter] search_fields = ["email", "company_profile__name"] def get(self, request, id=None): if id: company = get_object_or_404(Company, id=id) serializer = CompanyRetrieveSerializer(company) return Response(serializer.data) else: companies = Company.objects.all() for backend in list(self.filter_backends): companies = backend().filter_queryset(request, companies, self) paginator = LimitOffsetPagination() result = paginator.paginate_queryset(companies, request) serializer = CompanyListSerializer(result, many=True) return paginator.get_paginated_response(serializer.data) @extend_schema(tags=["admin"]) class EmployeeForAdminView(APIView): permission_classes = [IsAuthenticated, IsAdmin] filter_backends = [SearchFilter] search_fields = ["first_name", "middle_name", "last_name", "designation"] def get(self, request, company_id, id=None): if id: employee = get_object_or_404(Employee, id=id) serializer = EmployeeRetrieveSerializer(employee) return Response(serializer.data) else: company = get_object_or_404(Company, id=company_id) employees = company.employees.all() for backend in list(self.filter_backends): employees = backend().filter_queryset(request, employees, self) paginator = LimitOffsetPagination() result = paginator.paginate_queryset(employees, request) serializer = EmployeeListSerializer(result, many=True) return paginator.get_paginated_response(serializer.data) I have two different routes for each view in my urls.py. from django.urls import path, include from rest_framework.routers import DefaultRouter from drf_spectacular.utils import extend_schema_view, extend_schema from account.views import ( CompanyView, EmployeeView, AddEmployeesFromExcelView, PasswordChangeView, ForgotPasswordAPIView, ResetPasswordTokenCheckAPIView, CompanyForAdminView, EmployeeForAdminView, ) app_name = "account" ... urlpatterns = [ ..., path("admin/company/", CompanyForAdminView.as_view(), name="admin_companies"), path( "admin/company/<int:id>/", CompanyForAdminView.as_view(), name="admin_companies" ), path( "admin/<int:company_id>/employee/", extend_schema_view( get=extend_schema( summary="List Employees", description="List of employees for a given company.", tags=["admin"], ) )(EmployeeForAdminView.as_view()), name="admin_employees", ), path( "admin/<int:company_id>/employee/<int:id>/", extend_schema_view( get=extend_schema( summary="Retrieve Employee", … -
Invalid HTTP_HOST header for Django app that is running in Cloud Run
I have a Django app running in Cloud Run. Cloud Run is configured as a backend service for External Application Load Balancer. The service works with different custom domains. The list of domains is changing continuously, so the domain management was moved to the Cloud Armor security policy level to avoid re-deploying the service after updating the domain list. On the Django level, all hosts are allowed: ALLOWED_HOSTS = ["*"] example.net is allowed by Cloud Armor security policy and every request to that host is handling by Django app in the Cloud Run. I started receiving requests from some scanning bots and some of this requests cause an error on the Django app level: Invalid HTTP_HOST header: 'mydomain.com%7d'. The domain name provided is not valid according to RFC 1034/1035. Here are other values from the traceback for this error: Report at //example。com Invalid HTTP_HOST header: 'example.net%7d'. The domain name provided is not valid according to RFC 1034/1035. Request Method: GET Request URL: http://example.net%7d//example%E3%80%82com Django Version: 3.2.25 ... META: ... HTTP_ACCEPT = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' HTTP_ACCEPT_ENCODING = 'gzip' HTTP_ACCEPT_LANGUAGE = 'en-US,en;q=0.9,ca;q=0.8' HTTP_CACHE_CONTROL = 'no-cache' HTTP_FORWARDED = 'for="replaced.ip.address";proto=https' HTTP_HOST = 'example.net%7d' PATH_INFO = '//example。com' QUERY_STRING = '' RAW_URI = '//example%E3%80%82com' ... At the same … -
Why is time in Django in 01.01.1900?
I defined a model: class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.TimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model""" return self.text I retrieve them in a view: topics = Topic.objects.order_by("date-added") I've been working on this project for a while now and the topics were displayed in the right order, but at some point I noticed that they're placed not in chronological order. I tried to see the dates (in Django shell): for topic in Topic.objects.order_by("date_added"): print(topic, topic.date_added.strftime("%d.%m.%Y $H:%M:%S")) The result: Hip-hop 01.01.1900 10:39:27 Rap2 01.01.1900 10:40:17 Chess 01.01.1900 15:45:32 Rock Climbing 01.01.1900 15:45:43 Programming 01.01.1900 15:51:18 Boxing 01.01.1900 18:21:59 Rap 01.01.1900 20:50:58 It shows, they're all added in the 1st Jan of 1900. How to configure the date in Django so it displays it right? -
I cannot check radio but after choose the option
in django template after choice the radio option my rabio box dont get checked {% if mod %} {% for i in mod %} <div class="form-check"> <input class="form-check-input" type="radio" name="Catagory" id="{{i.id}}"/> <label class="form-check-label" for= "{{i.id}}" > <a href="{% url 'catagory_wise_post' i.slug %}"> {{i.name}}</a> </label> </div> {% endfor %} {% endif %} here is the checking problem -
How to mapping ForeignKey model value in Django Rest Framework
models.py class Item(models.Model): name = models.CharField(max_length=100) # other_no_need_translate = models.CharField(max_length=100) class Itemi18n(models.Model): origin = models.ForeignKey(Item, related_name='i18n') language = models.CharField(max_length=200, default="") name = models.CharField(max_length=100) view.py class ItemViewSet(viewsets.GenericViewSet): def get_queryset(self): return Item.objects.annotate(name=F('i18n__name')) # something like this serializers.py class I18nField(Field): def __init__(self, field_attr, **kwargs): self.field_attr = field_attr super().__init__(source='*', read_only=True, **kwargs) def to_representation(self, value) -> str: request = self.context['request'] if request.query_params.get('lang') == 'es': value = ... else: value = ... return value class ItemSerializer(serializers.ModelSerializer): name = I18nField(...) I want to write a serializer, when i18n is needed, return name from Itemi18n, otherwise return name from Item. I thought of 2 solutions,one is use annotate to override field, another is use Custom Field. I am not sure about best practices and performance issues.