Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I replicate **bold** in my django template?
I am trying to replicate how stack overflow allows the user to type text and produces it below at the same time. The code below in the Django Template works for this. {% block head %} <script> function LiveTextUpdate() { var x = document.getElementById("myInput").value; document.getElementById("test").innerHTML = x; } </script> {% endblock %} {% block body %} <div class = typing_container> <div class = note_text> {{ note_form.note }} </div> </div> <div class = output_container> <div class = output_note_text> <p id="test" ></p> </div> </div> The following is in the forms.py file: class NoteForm(ModelForm): class Meta: model = NoteModel fields = [ 'note' ] widgets = { 'note' : Textarea(attrs={'placeholder' : 'Start a new note', 'class' : 'updated_task_commentary', 'id' : 'myInput', 'oninput' : 'LiveTextUpdate()' }), } How can I replicate the ability to bold text when the text is surrounded by "**" please? -
Django Postgres table partitioning not working with 'pgpartition' command
I have a huge "Logs" postgres table being used extensively in my Django project. Logs table has more than 20 million records and its slowing down the queries and page load time is also increased. I am using below Django and Postgres versions:- Django: 4.0 Postgres: 13 I read about table partitioning and decided to use "django-postgres-extra" as I don't want to manage migration files. I followed all the steps mentioned in below link but I am not able to create partitioned tables using "pgpartition" command. https://django-postgres-extra.readthedocs.io/en/master/table_partitioning.html Am I missing something here? models.py changes:- from django.db import models from psqlextra.types import PostgresPartitioningMethod from psqlextra.models import PostgresPartitionedModel from psqlextra.manager import PostgresManager class Logs(PostgresPartitionedModel): class PartitioningMeta: method = PostgresPartitioningMethod.RANGE key = ["ctime"] objects = PostgresManager() ctime = models.DateTimeField(auto_now_add=True) logname = models.CharField(max_length=20) builds = models.ForeignKey(Build) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'psqlextra', 'logs', ] DATABASES = { 'default': { 'ENGINE': 'psqlextra.backend', 'NAME': 'logdb', 'USER': 'root', 'PASSWORD': 'crypt', 'HOST': 'localhost', 'PORT': 5432, } } PSQLEXTRA_PARTITIONING_MANAGER = 'logs.partition.manager' Created a file named 'partition' under logs app and defined a manager object as per doc link above. partition.py from dateutil.relativedelta import relativedelta from logs.models import Logs from psqlextra.partitioning import ( PostgresPartitioningManager, … -
How to add Gunicorn to Django app running in docker?
I have a django app running with a docker in a Digitalocean droplet. My question is, where do I add the gunicorn.socket and the gunicorn.service? In the Django Docker app or in the DigitalOcean running the docker? `gunicorn.socket is: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target and gunicorn.service is: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ -k uvicorn.workers.UvicornWorker \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.asgi:application [Install] WantedBy=multi-user.target -
'speedtest-cli module showing incorrect internet speed when i put it in a heroku app
in my website I used 'speedtest-cli' module.it worked with my localhost. when I deployed to 'heroku' >>it shows incorrect internet speed. -
How to parse XMLHttpRequest in Django
I wanted to pass a file along with other text data from react to django and so I used the FormData() class and axios to post the request to DRF. The React code : import React, { useEffect, useState } from "react"; import "../styling/AptitudeTest.css"; import Timer from "../components/Timer"; import { useNavigate, useLocation } from "react-router-dom"; import axios from "axios"; function AptitudeTest() { const navigate = useNavigate(); const [lkdn, setLkdn] = useState(""); const [selectedFile, setSelectedFile] = useState(); const location = useLocation(); const [qs, setQs] = useState([]); const onFileChange = (event) => { setSelectedFile(event.target.files[0]); }; useEffect(() => { const data = async () => await axios .get(`http://127.0.0.1:8000/comp/test/${location.state.id}`) .then((res) => { setQs(res.data.jsonData); }) .catch((e) => console.log(e)); data(); }, []); function submitHandler(e) { e.preventDefault(); let c = 0, total = 0; var checkboxes = document.querySelectorAll("input[type=radio]:checked"); for (var i = 0; i < checkboxes.length; i++) { c = c + parseInt(checkboxes[i].value); total = total + 2; } let formData1 = new FormData(); formData1.append("Content-Type","multipart/form-data") formData1.append( "cid", JSON.parse(localStorage.getItem("uData"))["cand_email"] ); formData1.append("testid", location.state.id); formData1.append("linkedin", "asasdads"); formData1.append("score", Math.ceil((c * 100) / total)); formData1.append("cv", selectedFile); formData1.append("compid", location.state.compid); axios .post("http://localhost:8000/cand/response/",formData1) .then((res) => { navigate("/records2"); }) .catch((err) => { console.log(err); }); } return ( <div className="container"> <h4 className="tit">J.P Stan and Co. - Data … -
The current path, register/, didn’t match any of these
Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/register/ Using the URLconf defined in floshop.urls, Django tried these URL patterns, in this order: admin/ [name='demo'] floreg/ ^static/(?P.)$ ^media/(?P.)$ The current path, register/, didn’t match any of these. while giving action path is not working. after after submitting registration form it shows error -
Update database when CSV file is updated
I have data on a CSV file that I have imported into the DB, and display the data into my index.html as a HTML table. The CSV is updated frequently Is there anyway to update the data in the DB from the CSV file every hour or day, or even every time rhe file is updated? -
How to convert GROUP BY sql to Django orm
for exmaple, the sql is SELECT *, COUNT(*) FROM message_like WHERE receiver_id = 1 GROUP BY bbs_article_id, bbs_comment_id ORDER BY - time; I hope that the result is queryset, not a dict. -
Convert function base view to class based view (DRF)
can someone help me convert this function component to class based view (rest framework concrete view)? I tried converting but landed with errors where serializer is false. Product image is required in the query. class Product(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) stock = models.IntegerField() is_available = models.BooleanField(default=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class ProductImage(models.Model): image = models.ImageField(upload_to=get_upload_path) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_images") def store(request, category_slug): cat = None products = None if category_slug != None: cat = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=cat) product_count = products.count() else: products = Product.objects.filter(is_available=True) products.count() context = { 'products': products, 'product_count': product_count } return render(request, 'store.html', context) what i tried with rest framework. Serializers: class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = ('image',) class ProductSerializer(serializers.ModelSerializer): product_images = ProductImageSerializer(many=True, read_only=True) class Meta: model = Product fields = "__all__" def create(self, validated_data): profile_data = validated_data.pop('product_images') product = Product.objects.create(**validated_data) return product View: I tried with concrete views, product is filtered by category. class Store(generics.ListCreateAPIView): queryset = Product.objects.filter(is_available=True) serializer_class = ProductSerializer lookup_field = 'category_slug' lookup_url_kwarg = 'category_slug' def list(self, request, *args, **kwargs): queryset = self.get_queryset() cat_slug = … -
got an unexpected keyword argument 'max_lenght' . I don't know whats wrong with my code. Please somebody help me
from os import name from sre_constants import CATEGORY from unicodedata import category from django.db import models # Create your models here. CATEGORY = ( ('Stationary', 'Stationary'), ('Electronics', 'Electronics'), ('Food', 'Food'), ) class Product(models.Model): name = models.CharField(max_lenght=100, null=True) category = models.CharField(max_lenght=20, choices=CATEGORY, null=True) quantity = models.PositiveIntegerField(null=True) got an unexpected keyword argument 'max_lenght', how to solve this problem? -
How to retrieve Django model object using ForeignKey?
I am new to Django and I am having dificulty of understanding how search Querys and work. I have these models: User = settings.AUTH_USER_MODEL class List(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200) class ListShared(models.Model): shared_list = models.ForeignKey(List, on_delete=models.CASCADE, related_name="shared_list") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sub_user") Idea is that single user can have any number of lists and share those lists to other users if they choose to do so. I am trying write three querys: Return all Lists created by user Return all Lists that are shared to user Return all above So far it seems that 1. can be achieved with : parent = User.objects.get(username=user_name) lists = parent.list_set.all() and 2. with: lists = ListShared.objects.filter(user__exact=user) But I can't seems to find a way to return every that user is connected to (3.). How can I achieve this? -
How can I configure launch.json so it could type automatic response?
I need python manage.py collectstatic run before python manage.py runserver when I run 'launch.json' in VSCode. Another problem, 'python manage.py collectstatic' almost always requires typing 'yes' or 'no'(python manage.py collectstatic), before continuing to execute. Can I make it send 'yes' automatically? { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: CollectStatic", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "collectstatic" ], "django": true, "justMyCode": false }, { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver" ], "django": true, "justMyCode": false }, ], "compounds": [ { "name": "collectstatic/runserver", "configurations": ["Python: CollectStatic", "Python: Django"], "stopAll": true } ] } -
"Uncaught (in promise) Error: Request failed with status code 403" instead of redirecting to login page
Instead of getting redirected to the login page i get a 403 error when my JWT Token expired. What i'm trying to accomplish is that when the token expires or there is any other issue that leads to the token not being valid it redirects to the login page. But when the token (line 22-25 inside App.js is where the code related to the redirect is). AuthContext.js import React, { useEffect, useState } from 'react' import { API } from "../api" import axios from "axios" import { isAfter, isEqual, parseISO, sub } from 'date-fns' export const AuthContext = React.createContext(null) export function AuthContextProvider({ children }) { const [accessTokenExpiration, setAccessTokenExpiraton] = useState(undefined); const getUser = () => { return JSON.parse(localStorage.getItem('user')) } const isLoggedIn = () => { return localStorage.getItem('user') !== null } const [user, setUser] = useState(() => { return isLoggedIn() ? getUser() : null; }) const [shouldGoToLogin, setShouldGoToLogin] = useState(() => { if (!user || !user.access_token || !user.refresh_token) { return true; } return false; }) const logout = async () => { if (!user) { return; } const { access_token } = user; localStorage.removeItem('user') setUser(null); return axios.post(API.auth.logout, { headers: { "Authorization": `Bearer ${access_token}`, "Content-Type": "application/json" }, withCredentials: true }); } const … -
django modelform not seeing model
Anyone can help me with this ModelForm has no model class specified.. Already go through the code many times. Is there anything wrong with my code? I have go through other people that have same problem with me and address it but still have the same problem. forms.py class ProfileUpdateForm(ModelForm): class meta: model = User fields = [ 'full_name', 'address', 'postcode', 'phone_number', 'birthdate', ] models.py class User(AbstractBaseUser, PermissionsMixin, models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) class StateChoices(models.TextChoices): AB = 'AB', _('AB') AC = 'AC', _('AC') email = models.EmailField( verbose_name='email address', unique=True, db_index=True, ) full_name = models.CharField( max_length=100, blank=True, ) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) address = models.CharField(max_length=150, blank=False) city = models.CharField(max_length=50, blank=False) state = models.CharField( max_length=15, choices=StateChoices.choices, default=StateChoices.SELANGOR, ) postcode = models.CharField(max_length=10, blank=False) phone_number = models.CharField(max_length=15, blank=False) update_profile = models.BooleanField(default=False) birthdate = models.DateField(auto_now=False, null=True, blank=True) is_lecturer = models.BooleanField(default=False) is_student = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) objects = UserManager() USERNAME_FIELD = "email" def get_full_name(self): return self.full_name def __str__(self): if self.full_name == "": return f"{self.email}" else: return f"{self.full_name}" views.py def profileupdate(request, pk=None): key = request.user.pk user_pk = get_object_or_404(User, pk=key) if request.method == "POST": form = form = ProfileUpdateForm(request.POST, instance=user_pk) if form.is_valid(): form.save() return redirect('index') else: form = ProfileUpdateForm(instance=user_pk) … -
Insert multiple records in one query in mongodb using drf
I need to insert multiple records in the mongodb atlas. I am using djongo as database engine in my DRF backend. To save a single record, I send the data from React frontend and in the views.py file, I use the following code serializer = MySerializer(data=req.data) serializer.is_valid(raise_exception=True) serializer.save() And it works fine. But if I need to save multiple records in the database, I am sending a list of records and do this, for data in req.data['data']: serializer = MySerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() So, if the list is big, it takes a lot of time to insert all the records and I guess it is because all records are inserted by a separate query to the database. How can I insert all the records in the database quickly? -
python script returns The view website.views.buttonclick2 didn't return an HttpResponse object. It returned None instead
I am using django. I have added the below function into my views.py file. When i first start vs code the holehe GUI executes and the window pops up for me to enter text. However when I start the server and click the button on the holehe HTML page I receive the error "The view website.views.buttonclick2 didn't return an HttpResponse object. It returned None instead." I have tried adding at the bottom return render(request, 'holehe.html') however this doesnt work. Please can someone advise where I am going wrong ? def buttonclick2(request): if request.method == "POST": return def compile_terminal_command(terminal_command, last_line_index) : # The last line index stores the line where the command thread has to output in the listbox # since the listbox may have also received more commands in that span and the thread may take # some time to give output command_summary = terminal_command.split(' ') # Split the command and args. os.environ["PYTHONUNBUFFERED"] = "1" # MAKE SURE THE PREVIOUS OUTPUT IS NOT RECIEVED # > We use the subprocess module's run method to run the command and redirect output and errors # to the pipe from where we can extract it later. # > I will suggest running this … -
Websocket 502 Bad Gateway
I've two container for wsgi and asgi. wsgi server is running on 127.0.0.8000: gunicorn app.wsgi:application --bind 127.0.0.1:8000 Also asgi server is running on 127.0.0.1:8001 using of daphne: daphne -b 127.0.0.1 -p 8001 app.asgi:application I have a websocket request like this: wss://app.example.com/ws/chat/f770eef/ But unfortunately these errors occur in the system: i) nginx log says: 2022/05/22 13:15:29 [error] 463129#463129: *9 upstream prematurely closed connection while reading response header from upstream, client: 11.198.111.11, server: app.example.com, request: "GET /ws/chat/f770eef/ ii) Requests do not reach daphne. asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') application = get_asgi_application() nginx cofing: server { listen 443; listen [::]:443; server_name app.example.com; root /var/www/html; ... location /ws/ { proxy_pass http://127.0.0.1:1335; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_read_timeout 300s; proxy_connect_timeout 75s; } ... } -
Make a get request with a multiple value param in django requests Module?
I have a webservice that give doc list. I call this webservice via get_doc_list. but when I pass 2 values to id__in, it return one mapping object. def get_doc_list(self, id__in): config = self.configurer.doc params = { "id__in": id__in, } response = self._make_request( token=self.access_token, method='get', proxies=self.proxies, url=config.service_url, params=params, module_name=self.module_name, finalize_response=False ) return response How can I fix it?! -
Automatic deployment of my django website after making changes
i have deployed my Django portfolio using nginx server.but now i want a feature in which i make changes to my Github repo and then it will get automatic deployed to my nginx server. how can i do this?. thankyou -
Add Serial Number on Django Form [closed]
I want to add serial no on the top of body with auto increment after submit form -
Django Return Queryset from Database table by filtering using Dictionary values
My goal is to return rows from the books table using values sent by a user through a search form. The search form contains multiple fields author, ISBN and title. NB: In the code, the author field is a char, but converted to ID based on authors name due to foreign key relation. In this code, there's a get request converted to Dictionary and transformed to allow it to query data from the books table. def search(request): form = BooksForm() if request.method == 'GET': # convert get request to dictionary book_search = dict(request.GET) print("data before cleaning", book_search) #get the name from the dictionary get request author_name =request.GET['author'] #get the author id from the author table author = Author.objects.filter(full_name__contains=author_name).values() #get author_id from author queryset author_id = author[0]['id'] #update the dict with the author id to allow search in books models (foreing key) book_search['author'] = author_id print("data after cleaning",book_search) result_set = Book.objects.filter(**book_search) print("book search queryset",result_set) Problem: When I query the books table using the dictionary it returns an empty query set and I want it to return books from in table. Does anyone have an idea of how I can make the code work? -
Build a custom authentication flow in a hosted django app for pydrive2
I am using Django as backend. I need to create a custom auth flow for pydrive2. I cannot use gauth.LocalWebserverAuth() as that is suitable only on local machines. I see this sample code at pydrive documentation for custom auth flow. from pydrive2.auth import GoogleAuth gauth = GoogleAuth() auth_url = gauth.GetAuthUrl() # Create authentication url user needs to visit code = AskUserToVisitLinkAndGiveCode(auth_url) # Your customized authentication flow gauth.Auth(code) # Authorize and build service from the code AskUserToVisitLinkAndGiveCode is the part that I am unable to understand. What should this function do? Should my backend redirect to the URI that I added as the redirect URI on google drive console? Or should I redirect the user to the auth_url link? -
Django server not reloading on file changes
I just cloned a Django project from my Github for maintenance on another machine, installed all the dependencies then ran the server. Everything seems to be working fine except the fact that the server does not reload when I make file changes (on all python files). Changes in static files are not reflected too. Things to note: Django 4.0.3 Python 3.9.0 Environment manager is Pipenv. Settings.py DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], I don't have a custom runserver command I have the suggestions on this question but they didn't work. Any help would be greatly appreciated. -
Django error when using if condition on integar
I want to write if condition on integer when write if condition on string its is working but when I want to write same condition its not working. {% if 209 in l.label %} Book Now ! {% else %} Booked! {% endif %} -
Не вызывается Modal window после нажатия кнопки
делаю свой первый сайт, использую django, python, bootstrap 5, хочу что бы после заполнения формы человек нажал кнопку "отправить" и после этого всплыло модальное окно в котором будет написано что "все ок, ваша заявка создана" <div class="row mt-5 mb-5 p-2"> <form action="{% url 'feedback_view' %}" method="POST"> {% csrf_token %} <div class="col-md-6 mb-2"> <label for="exampleInputName" class="form-label">Ваше Имя</label> <input name="name" class="form-control" id="exampleInputName" aria-describedby="NameHelp"> </div> <div class="col-md-6 mb-2"> <label for="exampleInputphone" class="form-label">Ваш Телефон</label> <input name="phone" class="form-control" id="exampleInputphone" aria-describedby="NameHelp" placeholder="+7 (918) 000-00-00"> </div> <button type="submit" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Отправить</button> </form> </div> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Отправить_btn</button> но почему-то кнопка 'отправить' не работает, но работает кнопка 'отправить_btn' которую я сделал для теста проблемы. все что я понял на данный момент что мне мешает type="submit" тк. во второй кнопке стоит type="button". как мне решить эту проблему, учитывая что это кнопка отправки формы? это код окна: {% if messages %} {% for message in messages %} <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p class="reviews">{{ message }}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% endfor %} {% endif …