Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Opening modalwith multiple select Options
Hi I'm trying to open a modal with different Data (loaded from Django) from an Option. <tbody> <tr> <td class="client">client001</td> <td class="User">user001</td> <td class="Vulnerabilites"> <select class="form-select" size="4" id="vulselect" > <option value="2705" >Security Vulnerability CVE-2018-1285 for log4net</option> <option value="73562" >Security Vulnerability CVE-2022-39427 in VirtualBox</option> </select> </td> </tr> <tr> <td class="client">client002</td> <td class="User">user002</td> <td class="Vulnerabilites"> <select class="form-select" size="4" id="vulselect" > <option value="68069" >Security Vulnerability CVE-2021-34803 for TeamViewer</option> <option value="74465" >Security Vulnerability CVE-2023-21899 in VirtualBox</option> </select> </td> </tr> </tbody> <script> $(function () { $(".form-select").each(function () { $(this).change(function () { var e = document.getElementById("vulselect"); var value = e.value; alert(value); $('#vulmodal').modal("show"); var elements = document.getElementById("vulselect").options; for(var i = 0; i < elements.length; i++){ elements[i].selected = false; } }); }); }); </script> For my first select in the first table row (user001) the alert shows the correct Values. But when I try it in my second row the JS don't load the option value in the var value. Sorry Im very new to frontend so any help would be greatly appriciated. -
Configuration of Django Channel with Redis secured with SSL
I am facing the difficulty of configuring my Django application in Azure. I have a basic scenario where I track the file upload progress using the WebSocket. For WebSocket, I use Django Channels with Redis Channels. In my architecture, the Redis component is also used for another execution, and it is secured with SSL/TLS; therefore listens on port 6380. In my application, I have the following configuration for Redis (Celery) and Django Channel (using Redis Channel) settings.py # PORT 6379 for NON-SSL Connection and 6380 for SSL Connection _broker_url = f'rediss://:{os.getenv("REDIS_PASS", "")}@{os.getenv("REDIS_HOST", "localhost")}:{os.getenv("REDIS_PORT", "6379")}' CELERY_BROKER_URL = _broker_url CELERY_RESULT_BACKEND = _broker_url CELERY_BROKER_USE_SSL = {'ssl_cert_reqs': ssl.CERT_REQUIRED} CELERY_REDIS_BACKEND_USE_SSL = {'ssl_cert_reqs': ssl.CERT_REQUIRED} CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [(os.getenv("REDIS_HOST", "127.0.0.1"), int(os.getenv("REDIS_PORT", 6379)))], }, }, } On my frontend I have the regular file upload form that opens the secured websocket: function createSocket(task_id) { const socket = new WebSocket( `wss://${config.backendUrl}/ws/tasks/${task_id}/` ); socket.onmessage = function (e) { const data = JSON.parse(e.data); let status = data["message"]["status"]; console.log(data); if (status === "SUCCESS") { api.get(targetUrl).then((value) => { handleUploadReload(value.data["files"]); }); this.close(); } else if (status === "FAILURE") { setError(data["message"]["error"]); this.close(); } }; socket.onclose = function (e) { console.log("Task socket closed"); }; socket.onerror = (err) => { … -
Django-leaflet trying to load a bunch of js files from a non-existent static/src directory
I'm using Django-leaflet in my project. When loading a page it's trying to load a bunch of js files from a static/src directory. static/src/core... static/src/geometry... static/src/control... static/src/layer... and others I don't know why it is trying to load these files. I don't see anything in the documentation about why I should have a static/src directory. I have a working page that loads a leaflet map, adds layer control, adds markers, and functions. However I am running into errors when adding new functionality. I'm not sure if these missing js files are causing it. To isolate what was trying to load these files I made a barebones page that all it does is loads leaflet_tags and leaflet_js which results in attempting to load all these js files. {% load leaflet_tags %} <head> {% leaflet_js %} </head> Any help would be appreciated. -
can I use django with flutter?
I'm a noob in software development. I need to develop a web application to create and add users for a system. and a mobile app for to users to login. users can't register with mobile. they have to first register with web application can i use a Django with rest APIs to backend as both mobile and web application (mobile app language is dart with flutter) I read in the documentation that we can use rest API for it. but no clear guide found. I also found we can import user details easily with firebase. -
i write code in view.py and i need to get id of element in for loop in template i need to get from template instead of?
` x=job.objects.filter(category=???).count() {% for catigory in cat %} <div class="col-lg-4 col-xl-3 col-md-6"> <div class="single_catagory"> <a href="{% url 'job:job_list' %}?category={{catigory.id}}"> <h4>{{catigory}}</h4> </a> <p> <span>{{x}} </span> Available position {{catigory.id}}</p> </div> </div> {% endfor %}` i write code in view.py and i need to get id of element in for loop in template i need to get catigory.id from template instead of ??? thanks alot -
Django HTMX NoReverseMatch Reverse for 'my_url' with arguments '('',)' not found using POST-request in view
I ran into the following issue on the Django framework using HTMX: django.urls.exceptions.NoReverseMatch: Reverse for 'create_cv_workexp' with arguments '('',)' not found. 1 pattern(s) tried: ['create\\-cv\\-workexp/(?P<pk>[0-9]+)/\\Z'] models.py: class Position(models.Model): position_name = models.CharField(max_length=255, blank=True, verbose_name='Position') created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user by', blank=True, null=True) date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) class Meta: ordering = ['date_create'] def __str__(self): return self.position_name class WorkExperience(models.Model): pos = models.ForeignKey('Position', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Position Relative') company = models.CharField(max_length=50, verbose_name='Company', blank=True) position_work = models.CharField(max_length=50, verbose_name='Position', blank=True) link_company = models.URLField(verbose_name="Company's link", blank=True) date_of_employment = models.DateField(blank=True, verbose_name='Date of employment') date_of_dismissal = models.DateField(blank=True, verbose_name='Date of dismissal') def __str__(self): return self.company class Meta: ordering = ["-date_of_employment"] Here are two models two models linked by a ForeignKey. forms.py: class CreateCVWorkExperienceForm(forms.ModelForm): ''' form for WorkExperience object ''' class Meta: model = resume.models.WorkExperience fields = ('company', 'position_work', 'link_company', 'date_of_employment', 'date_of_dismissal') views.py: @login_required(login_url='/users/login/') def create_cv_workexp(request, pk): ''' main views for displaying form for to add WorkExperience to CV and redirect to HTMX template ''' position = Position.objects.get(id=pk) workexps = WorkExperience.objects.filter(pos=position) form = CreateCVWorkExperienceForm(request.POST or None) if request.method == "POST": if form.is_valid(): workexp = form.save(commit=False) workexp.pos = position workexp.save() pk = workexp.pk return redirect("resume:detail-workexp", pk=pk) else: return render(request, "resume/partials/workexp_form.html", context={ "form": form }) context = { "form": form, "position": … -
Django ModelMultipleChoiceField problem to save data in DB
I used to have a Multi select box in my form filled with a JSON list forms.py FRUIT_CHOICES= [ ('Oranges', 'Oranges'), ('Cantaloupes', 'Cantaloupes'), ('Mangoes', 'Mangoes'), ('Honeydews', 'Honeydews') ] class AddRecordForm(forms.ModelForm): testrever = forms.MultipleChoiceField(choices=FRUIT_CHOICES) And so I used a JSON field in my models.py like this models.py class Record(models.Model): testrever = models.JSONField(max_length=500) It worked like a charm and I was able to save the selection and load it back when the form was recalled. But now in forms.py I need to modify the forms.MultipleChoiceField to forms.ModelMultipleChoiceField which is populated by a queryset like this class AddRecordForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.storage_pk = kwargs.pop('pk') super(AddRecordForm, self).__init__(*args, **kwargs) self.fields['testrever'].queryset = BDC.objects.filter(ref=self.storage_pk).values_list('model', flat=True) testrever = forms.ModelMultipleChoiceField(widget=forms.widgets.SelectMultiple, queryset=None) class Meta: model = Record exclude = ("user",) fields = ['id','first_name','last_name','email', 'phone' ,'address', 'city' ,'state' ,'zipcode' ,'regarde' ,'testrever'] So now my models.JSONField in models.py is no longer working since I'm not rendering a JSON list format anymore. What kind of field should I use in models.py to make it work again? -
embedded django webserver in python program
I want to create a systemctl service using Python that, among other things, has a web server that listens to HTTP requests for management. I already created the server in Django, but Django's runserver explicitly says to not use it in production. My program is not a web app for thousand or millions of requests, and this message would make sense if I wanted to run a web app. So, how can I have a lightweight webserver that I can just embed in my Python program and will use my Django views? -
JWT refresh token best practices
I'm wondering what is the best\ most secure and efficient way for me to handle token refresh round trips. My client is an iOS app, For my BE I'm using Django with graphql_jwt. When user signup\login\refresh token I send the auth token, refresh token and token expiration date, The swift response object looks like that: class AuthenticationTokens: Codable { let token: String let refreshToken: String let expiresIn: Date } Token expiration delta on BE is set to 5 minutes, refresh token expiration delta is 7 days. Basically before performing a new request on client I can check token expiration date and refresh the token. And I'm wondering if there is a secure way to make it more efficient, meaning on the same roundtrip instead of 2 separate network requests. So my thought is in case client detect an expired token before performing a request, it will just add the refresh token to the request header\body and on the server side I'll perform a token refresh and will overload GraphQL response with the new auth data. That way each request\response can handle authentication challenge or refresh. My only concern is if it is a bad practice to send the token and … -
I finished my Virtual environment setup in Python. I didn't have django in pip list, but i can still create django project using django-admin command
pip list: Package Version pip 23.1.2 setuptools 58.1.0 it doesn't have django in My Virtual environment but still django-admin commands worked for me! how is that possible. Thank you for clear answers in advance i Tried finding django package in lib folder but still doesn't contain any packages related to django -
Group multiple transactions in one voucher
I am making an accounting software that has 3 types of transactions (Issue, Receive, SalesReturn). I have created a form for each of these, for the sake of simplicity lets just take into account 'Issue'. Now in the issue form the user can make transaction for one product at a time. This works fine, but when I am printing a invoice for transactions each Issue is coming out in different invoices. What I want is that when making an issue the user can tell the software that this transactions should be combined with the previous transaction and output it in the same invoice. The reason for this is, a single customer can be issued multiple products in a single transaction and it would be absurd to print different invoices for different products fro the same customer. I thought of making multiple transactions in a single form but could'nt work my way around. Just to make it more clear, right now my code works as such - if you buy an apple, mango and banana it will make 3 invoices. I want it to include all 3 items in a single receipt if the customer is same. models.py from django.db import … -
Django 4 async StreamingHTTPResponse and sending a large generated zipfile
I'm trying to zip some large files in Django and stream them to the client as a zipfile. The problem is that it tends to want to create the zipfile into memory first and then send. This causes the memory to run out and Django crashes. Writing the zipfile to disk prior to sending is also not feasible, due to limited storage space. I was able to do this using the zipfly package and it worked fine when Django was running synchronously in WSGI. But then I needed to implement WebSockets and had to make Django run asynchronously in ASGI, and the streaming zipfly implementation broke. So I started to write my own implementation and almost got it working but there are issues. It is currently attempting to create the zip on the fly, but it is still using quite a bit of memory. Also my code is not sending an indication to the client that the datastream has ended, causing the browser to abort the transfer in the end. Can anyone assist me? Here is the code: async def create_zip_streaming_response(files_to_compress: list, filename: str): # Create a generator function to yield chunks of data async def generate(): # Create an … -
websocket connection to 'ws://127.0.0.1:8000/ws/room_page/5/' failed: Error during websocket handshake: Unexpected response code: 404
im trying to make real time chat system but it gives me error in console log: websocket connection to 'ws://127.0.0.1:8000/ws/room_page/5/' failed: Error during websocket handshake: Unexpected response code: 404, also in the vs code terminal it says [17/May/2023 20:05:38] "GET /room_page/5/ HTTP/1.1" 200 9806 Not Found: /ws/room_page/5/ [17/May/2023 20:05:38] "GET /ws/room_page/5/ HTTP/1.1" 404 4248 this is a settings.py INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'playground.apps.PlaygroundConfig', 'users.apps.UsersConfig', ] ASGI_APPLICATION = 'DjangoWebsite.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", }, } consumer.py file from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_id = self.scope['url_route']['kwargs']['room_id'] self.room_group_id = 'room_%s' % self.room_id await self.channel_layer.group_add( self.room_group_id, self.channel_name ) await self.accept() await self.channel_layer.group_send( self.room_group_id, { 'type': 'chat_message', 'message': 'Hello World!' } ) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_id, self.channel_name ) async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) routing.py file from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/room_page/(?P<room_id>\w+)/$', consumers.ChatRoomConsumer), ] javascript file const roomId = JSON.parse(document.getElementById("room-id").textContent); const url = "ws://" + window.location.host + "/ws/room_page/" + roomId + "/"; console.log(url); const chatSocket = new WebSocket(url); chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); console.log(data); document.querySelector(".user-hello").innerHTML = data.message; }; chatSocket.onerror = function … -
How to attach a non persisted information to an object in Django Rest Framework model serializer and ModelViewSet
My goal is to transfer a query property from the request to the response without persisting this property. I am building an API endpoint using Django Rest Framwork ModelSerializer and ModelViewSet. This endpoint let the user create multiple buildings at once. The response of this endpoint is a JSON array of created buildings. Each building contains a unique ID (called rnb_id) generated before saving the model to the db. I want my user to know the unique ID of each the building they sent. To do so I want to let them attach a custom_id for tracking purpose. Important: I do not want to persist this custom id. Here is and example of the request they send me: [ { "geometry": [GeoJSON geometry], "custom_id": "XYZ" }, { "geometry": [GeoJSON geometry], "custom_id": "FOO" }, { "geometry": [GeoJSON geometry], "custom_id": "BAR" }, ] The response I would like to send them back is: [ { "geometry": [GeoJSON geometry], "custom_id": "XYZ" "rnb_id": "randomID-zefjf" }, { "geometry": [GeoJSON geometry], "custom_id": "FOO", "rnb_id": "randomID-oyijkn" }, { "geometry": [GeoJSON geometry], "custom_id": "BAR", "rnb_id": "randomID-dwdsq" }, ] I feel the mechanism should be in the serializer. Here is a simplified version of my serializers: class BdgInAdsSerializer(serializers.ModelSerializer): geometry … -
Improving queries by select related with many related models
Im writing an app with most of the data started across different tables. I've recently installed Django debug toolbar and noticed that i have some duplicates and similar queries. Thanks to this Im somewhat skeptical about my queries and how I make them. They work but are they efficient? models class Location(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) city = models.CharField(max_length=40, blank=True) placeId = models.CharField(max_length=100) point = models.PointField(srid=4326, blank=True, null=True) class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=150, blank=True) current_location = models.ForeignKey(Location, on_delete=models.SET_NULL, related_name="location", null=True) search_range = models.PositiveSmallIntegerField(default=10, blank=True, null=True) objects = CustomAccountManager() class Profile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) user = models.OneToOneField(User, on_delete=models.CASCADE) dummy_section = models.TextField(max_length=155, null=True, blank=True) class Blocked(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_thats_blocking") blocked_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blocked_user") date_created = models.DateTimeField(auto_now_add=True) class Interactions(models.Model): IntChoices = ( ("yes", "yes"), ("no", "no"), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="current_user") interacted_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="interacted_user") interacted = models.CharField(max_length=20, default="yes", choices=(IntChoices), db_index=True) So what I'm querying is. Getting all the potential profiles within my search_range so in location model. Then I'm getting interactions with users from the interaction model. If I … -
Using the "through " table in a Django template
I'm really new to Django and I've already tried to find a solution without success. I have these three models: class Items(models.Model): ID = models.AutoField(primary_key=True) name = models.TextField() price = MoneyField(blank=True, null=True, decimal_places=2, max_digits=8, default_currency='EUR') def __str__(self): return self.name class Interventions(models.Model): ID = models.AutoField(primary_key=True) date = models.DateField() time = models.TimeField(blank=True, null=True) description = models.TextField() ID_items = models.ManyToManyField(Items, through="Details") class Details(models.Model): ID = models.AutoField(primary_key=True) ID_item = models.ForeignKey(Items, on_delete = models.CASCADE) ID_intervention = models.ForeignKey(Interventions, on_delete = models.CASCADE) quantity = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.ID_intervention) I would like to be able to use the "quantity" field of the Details table, directly in the "intervention.html" template. intervention.html {% extends 'base.html'%} {% load static %} {% block content %} <h1>INSERT an INTERVENTION</h1> <br> <form action="" method="post"> {% csrf_token %} <div class="grid-container"> <h3>Date</h3><div>{{ form.date }}</div> <h3>Time</h3><div>{{ form.time }}</div> <h3>Description</h3><div>{{ form.description }}</div> <h3>Item/Items</h3><div class="overflow_scroll">{{ form.ID_items}}</div> </div> <br> <input type="submit" value="Save"> </form>[![example][1]][1] </div> {% endblock %} Unfortunately, the "intervention.html" template is formed by the "InterventionForm" ModelForm contained in the "forms.py" file. And so I don't know how to proceed. The result I'd like to get would be something like in the image. Thank you all for every little help. -
DJANGO - create a form that has as many inputs as there is data in the database
I'm new to django and I'm building a webapp that manages a db (created by django) where I'm going to save the data of a company with its employees etc. Each entity has its own model in models.py. Creating the page to be able to modify the data that is already inserted in the db, I encountered a problem: taking into account that a person can have more than one telephone number, in the form to insert the modified data I should have more inputs, dynamically generated by the view. py of django, based on how many phone numbers have been saved in the db. I've been stuck on this problem for hours and I can't find a solution ;) I saw someone using this function in view.py but it doesn't seem to work for me. `form = formset_factory(modifyPeopleForm, extra=1) if request.method == 'POST': formSet = form(request.POST) if form.is_valid(): print(request.POST) else: numbers= phoneNumbers.objects.filter(people=people_istance.id) formset = form(initial=[{ 'name': personale_istance.nome, 'secondName': personale_istance.cognome, 'job': personale_istance.mansione, 'phoneNumber': number.number} for number in numbers] )` -
How can I get the GET, PUT, DELETE API view in django rest framework?
I'm learning django Rest Framework and I'm trying to get the GET, DELETE, PUT APi view but it does not work. I use functions. Here is my view_list where It looks like working: My code views.py:: @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated, IsOwnerOrReadOnly]) def city_list(request, format=None): """ List all cities, or create a new city. """ if request.method == 'GET': cities = City.objects.all() serializer = CitySerializer(cities, many=True) #return JsonResponse(serializer.data, safe=False) return Response(serializer.data) elif request.method == 'POST': #data = JSONParser().parse(request) serializer = CitySerializer(data=request.data) if serializer.is_valid(): serializer.save(owner=request.user) #return JsonResponse(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_201_CREATED) #return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is my view_detail function where I want to get GET, PUT, DELETE API VIEW but It does not work! Here is my code in views.py: @permission_classes([IsAuthenticated, IsOwnerOrReadOnly]) @api_view(['GET', 'PUT', 'DELETE']) def city_detail(request, pk, format=None): """ Retrieve, update or delete a code snippet. """ try: city = City.objects.get(pk=pk) except City.DoesNotExist: return HttpResponse(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = CitySerializer(city) return JsonResponse(serializer.data) elif request.method == 'PUT': #data = JSONParser().parse(request) serializer = CitySerializer(city, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': city.delete() return HttpResponse(status=status.HTTP_204_NO_CONTENT) Here is my permissions.py: from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an … -
Deploy Django App wih Dockerfile in Render
I'm trying to deploy Django application with Dockerfile in Render.com. I have added the below codes in Dockerfile - ARG PYTHON_VERSION=3.10-slim-buster ARG DEBIAN_FRONTEND=noninteractive FROM python:${PYTHON_VERSION} ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /code WORKDIR /code #install the linux packages, since these are the dependencies of some python packages RUN apt-get update && apt-get install -y \ libpq-dev \ gcc \ cron \ wkhtmltopdf \ && rm -rf /var/lib/apt/lists/* ! COPY requirements.txt /tmp/requirements.txt RUN set -ex && \ pip install --upgrade pip && \ pip install -r /tmp/requirements.txt && \ rm -rf /root/.cache/ COPY . /code And added the below codes in render.toml, [deploy] startCommand = "sh /code/release.sh" And, added the below in release.sh, #!/usr/bin/env sh python manage.py migrate python manage.py collectstatic --noinput python manage.py runserver 0.0.0.0:$PORT I have created all the above files in project's root directory. But, after building, it's not run/execute the release.sh. What's the proper way to implement this? -
500 Error when uploading images on Wagtail after deploying with Google Cloud Run
I have developed a blog website using Wagtail, and it works perfectly fine when I run it locally. However, after I deployed it with Google Cloud Run, I am facing the following two issues: I am unable to upload images to my website, and it always shows a 500 Error. I cannot access my website domain after mapping it. (Does it about ALLOWED_HOST or) I followed the steps to deploy my website from this link: https://codelabs.developers.google.com/codelabs/cloud-run-wagtail/. And some codes in settings.py that may help if (CLOUDRUN_SERVICE_URL): ALLOWED_HOSTS = [urlparse(CLOUDRUN_SERVICE_URL).netloc, '.thehomefixs.com'] CSRF_TRUSTED_ORIGINS = [CLOUDRUN_SERVICE_URL,'https://*.thehomefixs.com'] else: ALLOWED_HOSTS = ["*"] GS_BUCKET_NAME = env("GS_BUCKET_NAME") STATICFILES_DIRS = [] DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_DEFAULT_ACL = "publicRead" I have tried several troubleshooting steps, including checking the Cloud Run logs, but I have not been able to resolve the issues. Any help would be greatly appreciated. -
Javascript: Create Date object from a string with a time
Project setup Django and Django REST Framework on the backend React and AntD on the frontend Problem I have a DateField and TimeField fields in my backend that return a string with format "YYYY-MM-DD" and "HH:mm:ss" respectively. I'm trying to get AntD to accept these values as an initial value, but the problem is that it seems that AntD expects a Date object, because anytime I try to pass the strings themselves I get an date.format is not a function error. I guess that AntD is trying to format the dates, but they're actually strings. Code Next is a minimal example of the problem I'm presenting. If running this with the following dependencies, it produces the error date.clone is not a function. import { Form, DatePicker, TimePicker, Input } from "antd"; const initial_data = { title: "Title", date: "2023-12-05", time: "10:23:00" } export function Playground() { return ( <Form initialValues={initial_data} > <Form.Item name="title" > <Input placeholder="Title" /> </Form.Item> <Form.Item name="date" > <DatePicker format={"DD/MM/YYYY"} placeholder="Pick a date" /> </Form.Item> <Form.Item name="time" > <TimePicker format={"HH:mm"} placeholder="Pick a date" /> </Form.Item> </Form> ); } Dependencies: react: 18.2.0 react-dom: 18.2.0 antd: 4.24.8 Things I've tried For the DateField I have no problem, simply I … -
Querying Different Models with Ordering and Pagination
I have a project where I store transactional records across about three models. These models have relatively different columns. I need to retrieve these records across these models for a transactions endpoint. The transactions need to be ordered in descending order by date across the models and also paginated. The current implementation I have retrieves the records from the database using different querysets, then a sorted and chain method to order them by date before passing it to the paginator. This method happens to be expensive because the queryset has to be evaluated before pagination. model1_qs = Model1.objects.filter(...) model2_qs = Model2.objects.filter(...) model3_qs = Model3.objects.filter(...) chained_list = sorted(chain(model1_qs, model2_qs, model3_qs), key=lambda: x: x.created, reverse=True) # I pass this chained list to the paginator. One other implementation I've tried is to combine the queryset using union, but I got this error: django.db.utils.OperationalError: SELECTs to the left and right of UNION do not have the same number of result columns and when I tried to use annotate to make the columns equal on both sides, I got a couple of errors like this: AttributeError: 'float' object has no attribute 'replace' I have decided against going this route because it was beginning to look … -
Problem with fetching other user in Django
Good day everyone, currently I'm working on building a twitter clone and am almost done but I cant seem to get some functionality working. I created a profile page where users are able to see what they have tweeted and the people that follow them, so I created link to each persons profile so they can be linked there however, when I try clicking on the link I still end up on my page. My url changes so I know theres not problem with the markup, I will highly appreciate some assistance. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) bio = models.TextField(null=False, blank=False, max_length=500) profile_picture = models.ImageField(null=True, blank=True, upload_to="pictures/") followers = models.ManyToManyField("self", blank=True, symmetrical=False) def __str__(self): return self.user.username class Talks(models.Model): user = models.ForeignKey(User, related_name="talks", on_delete=models.DO_NOTHING) body = models.TextField(null=False, blank=False, max_length=500) image = models.ImageField(null=True, blank=True, upload_to="talk-pictures/") talked_at = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, blank=True, related_name="talk_likes") def total_likes(self): return self.likes.count() def __str__(self): return f"{self.user} " f"{self.talked_at:%Y-%m-%d %H:%M}: " f"{self.body}" @receiver(post_save, sender=User) def auto_create(sender, instance, created, **kwargs): if created: user_profile = Person(user=instance) user_profile.save() user_profile.followers.set([instance.person.user.id]) user_profile.save() post_save.connect(auto_create, sender=User) views.py from typing import Any, … -
Resize images in django-tinymce
I have a tinymce form in my Django app, this is the configuration: TINYMCE_DEFAULT_CONFIG = { 'branding': False, 'height': '300px', 'width': '100%', 'cleanup_on_startup': True, 'custom_undo_redo_levels': 10, 'selector': 'textarea', 'plugins': 'link image table', 'toolbar': 'undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image table', 'toolbar_mode': 'floating', 'relative_urls': False, 'remove_script_host': False, 'convert_urls': True, 'images_max_dimensions': (800, 800), } But 'images_max_dimensions': (800, 800), doesn't work and images go beyond the borders they're supposed to. I tried to resize the images by rendering the view with pillow but it's taking too much resources. -
Django using context processor in email template
I created a custom context processor to display the name of companies in templates. It works correctly in page templates but it is not working in an email template. Nothing is inserted in the template for {{ cname.company_name }}. The context processor code: def cname(request): ti = request.tenant.id company = Tenant.objects.get(id=ti) return ({'cname': company}) The relevant view code: def form_valid(self, form): password = CustomUser.objects.make_random_password() account = form.save(commit=False) account.password = make_password(password) account.reset_password = True account.save() account.reset_token = default_token_generator.make_token(account) account.save() base64_encoded_id = urlsafe_base64_encode(force_bytes(account.pk)) reset_url_args = {'uidb64': base64_encoded_id, 'token': account.reset_token} url = self.request.build_absolute_uri(reverse("password_reset_confirm", kwargs=reset_url_args)) account_creation_email(account.email, f"{account.full_name}", url=url) return super().form_valid(form) The utils.py code: def account_creation_email(to, full_name, url): template = get_template('mail/account-creation.html') context = {"full_name": full_name, "url": url} html = template.render(context) email = EmailMultiAlternatives( subject="Account Creation Email", body=html, to=[to] ) email.attach_alternative(html, "text/html") email.send() The email template: <div> <div>Hello, {{ full_name }}</div><br> <div>An admin at the company intranet for {{ cname.company_name }} just added an account for you to the site.</div><br> <div><a href="{{ url }}">Click Here</a> to set a password and login</div> </div> Any ideas for getting this to work?