Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django makemessages, TypeError: expected str, bytes or os.PathLike object, not list
I'm trying to create a multi language Django project in pycharm. But have struggled for the whole day figuring out why the makemessages doesn't generate .po files. So I reach out for some help. settings.py from pathlib import Path import os from decouple import config from unipath import Path from django.utils.translation import gettext_lazy as _ import environ env = environ.Env() environ.Env.read_env() BASE_DIR = Path(__file__).resolve().parent.parent CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale/'), ) LANGUAGE_CODE = 'en-us' LANGUAGES = [ ('en', _('English')), ('fr', _('French')), ] TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True When I run python manage.py makemessages -l fr I get the following response: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_manage.py", line 52, in <module> run_command() File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_manage.py", line 46, in run_command run_module(manage_file, None, '__main__', True) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 225, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 87, in _run_code exec(code, run_globals) File "/Users/famronnebratt/PycharmProjects/CompValid3/manage.py", line 22, in <module> main() File "/Users/famronnebratt/PycharmProjects/CompValid3/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/famronnebratt/PycharmProjects/CompValid3/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/famronnebratt/PycharmProjects/CompValid3/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/famronnebratt/PycharmProjects/CompValid3/venv/lib/python3.9/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/Users/famronnebratt/PycharmProjects/CompValid3/venv/lib/python3.9/site-packages/django/core/management/base.py", line 458, in execute output = … -
Can't serve django App behind Apache + Nginx
I have a Django App that I'm trying to deploy on our dev server through a domain name. Our dev server uses apache, while I use nginx to serve my app and static/media files. If I deploy it locally on my computer (localhost:port) everything works perfectly. Once I try it on our dev server, I cannot connect to the websocket endpoint. First of all I deploy my app with a docker-compose.yml consisting of an nginx, django app, redis and postgres services. Below is my nginx conf file server { listen 80; listen 443 default_server ssl; server_name localhost; charset utf-8; location /static { alias /app/static/; } location /upload { alias /app/media/; } location / { proxy_pass http://web:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://web:8000; } } And here is my apache conf <IfModule mod_ssl.c> <VirtualHost *:443> ServerName our.dev.server <Location /> ProxyPass http://127.0.0.1:89/ ProxyPassReverse http://127.0.0.1:89/ # Proxy WebSocket connections to your application RewriteEngine On RewriteCond %{HTTP:Upgrade} websocket [NC] RewriteCond %{HTTP:Connection} upgrade [NC] RewriteRule ^/ws/(.*)$ ws://127.0.0.1:89/$1 [P,L] </Location> SSLCertificateFile /etc/letsencrypt/live/our.dev.server/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/our.dev.server/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf RequestHeader add X-Forwarded-Proto "https" </VirtualHost> </IfModule> When I try … -
Ajax request works succesfully in local but not working in web server. I use Django, Docker. I loads long time and after
Ajax request works successfully locally but not on the web server. I'm using Django and Docker. I've checked all my settings in my docker-compose.yml, Dockerfile, settings.py, urls.py, etc. After loading for a long time, the console shows a message saying "no response." Here's my Ajax view: function ShowOTP () { $.ajax({ url: '/createcustomer/', type: "POST", data: { 'first_name': $('#first_name').val(), 'last_name': $('#last_name').val(), 'number_prefix': $('#number_prefix').val(), 'phone_number': $('#phone_number').val(), 'otp_form': 'otp_form' }, success: (response) => { if (response["valid"] == 'True') { document.getElementById('otpshow').click(); countdownOTP("#countdown", 2, 0); } if (response["valid"] == 'False') { window.location = '' } }, error: (error) => { console.log('error'); console.log(error); } }); }; -
How does Django BooleanField work with RadioSelect?
I have a model with a boolean class MyModel(models.Model): ... current_measures = models.BooleanField( verbose_name=_("Is there any control and safety measures?"), choices=BOOLEAN_CHOICE, ) ... I have a form that should set a value on this field using either true or false values. class MyForm(forms.ModelForm): ... current_measures = forms.BooleanField( widget=WidgetRadioSelectCustomAttrs( RADIO_WIDGET_ATTRS, choices=Risk.BOOLEAN_CHOICE ), label=_("Is there any control and safety measures?"), label_suffix="", required=True, ) ... Everything works fine until I set required=True on my form field and send the value "False" to validation method. In this case it raises ValidationError('Current measures is required') As I found out while debuging, the issue is with validate method of forms.BooleanField. At first it runs the method to_python, witch converts my value 'False' (type string) to False (type bool). def to_python(self, value): """Return a Python boolean object.""" # Explicitly check for the string 'False', which is what a hidden field # will submit for False. Also check for '0', since this is what # RadioSelect will provide. Because bool("True") == bool('1') == True, # we don't need to handle that explicitly. if isinstance(value, str) and value.lower() in ("false", "0"): value = False else: value = bool(value) return super().to_python(value) Then the validate method of BooleanField class is being … -
how to verify Django hashed passwords in FastAPI app
So I have a Python project in Django and I'm trying to change it to FastAPI. The passwords in the database are already hashed (I'm using the same database from the Django project), the passwords in the database start with pbkdf2_sha256$260000$. I'm trying to do the login function, but I'm having trouble with the password, I get an error "raise exc.UnknownHashError("hash could not be identified") passlib.exc.UnknownHashError: hash could not be identified" when I insert the username and password in my fastapi login form. #Security config security = HTTPBasic() pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto") async def login(request: Request): form = await request.form() username = form.get("username") password = pwd._context(form.get("password")) db = database.SessionLocal() user = db.query(models.User).filter(models.User.username == username).first() if not user or not pwd_context.verify(password, user.password): raise HTTPException(status_code=401, detail="Invalid username or password") token = create_jwt_token(user.id) response = RedirectResponse(url="/index", status_code=301) response.set_cookie(key="token", value=token) return response I'm trying to hash the password the user inserts so it can be verified with the hashed password in the database. I've also tried password = form.get("password"), and the error still pops up. This is the error: File "C:\Users\user\Desktop\VSPRojects\LoginFastapi\db\views.py", line 53, in login if not user or not pwd_context.verify(password, user.password): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\Desktop\VSPRojects\LoginFastapi\venv\Lib\site-packages\passlib\context.py", line 2343, in verify record = self._get_or_identify_record(hash, scheme, category) … -
Django: object has no attribute after annotation; Got AttributeError when attempting to get a value for field <field_name> on serializer
I have a custom user model and subscription model, which contains ForeignKeys to subscriber and user to subscribe to. class Subscription(models.Model): user = models.ForeignKey( ApiUser, on_delete=models.CASCADE, related_name='subscriber' ) subscription = models.ForeignKey( ApiUser, on_delete=models.CASCADE, related_name='subscriptions' ) Also i have viewset for subscription and two serializers: for write and for read. class SubscribeViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = ApiUser.objects.all() serializer_class = SubscriptionSerializerForRead permission_classes = (permissions.AllowAny,) def get_queryset(self): queryset = ApiUser.objects.all().annotate( is_subscribed=Case( When( subscribtions__exact=self.request.user.id, then=Value(True) ), default=Value(False), output_field=BooleanField() ) ).order_by('id') return queryset def get_serializer_context(self): context = super().get_serializer_context() context.update({'subscription_id': self.kwargs['pk']}) return context def get_serializer_class(self): if self.request.method not in permissions.SAFE_METHODS: return SubscriptionSerializerForWrite return SubscriptionSerializerForRead @action( methods=['POST'], detail=True, url_path='subscribe' ) def subscribe(self, request, pk): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) class SubscriptionSerializerForRead(serializers.ModelSerializer): is_subscribed = serializers.BooleanField() class Meta: model = ApiUser fields = ( 'email', 'id', 'username', 'first_name', 'last_name', 'is_subscribed' ) class SubscriptionSerializerForWrite(serializers.ModelSerializer): user = serializers.StringRelatedField( required=False, read_only=True, default=serializers.CurrentUserDefault() ) subscription = serializers.PrimaryKeyRelatedField( read_only=True ) class Meta: model = Subscription fields = ('user', 'subscription') def validate(self, attrs): attrs['user'] = self.context['request'].user attrs['subscription_id'] = self.context['subscription_id'] if self.context['request'].user.id == self.context['subscription_id']: raise serializers.ValidationError( 'Cannot subscribe to yourself' ) return attrs def to_representation(self, instance): return SubscriptionSerializerForRead( instance=instance.subscription ).data After successful subscription i need to return response with subscribed user data … -
How to implement an API database-connection to replace Django's functions
I have a project running in Django that handles all of my database actions through urls and views. I want to change this to Postgres and use an API that instead handles all of my database actions. This would be my first API so i'm not sure what the optimal process of designing it would be. So far I have just initialised a new project, I want to use Typescript and express.js. -
Why can’t I deactivate the virtual environment?
here is my problem that didn't help either and it is now in double brackets, and not in single brackets as before -
Django coverage test doesn't seem to run all app tests
I am using coverage to check how much code I have covered with my test suite. It seems to not run some tests when I run the complete test suite but does if I only run an app. For example coverage run manage.py test followed by covereage html shows the api app has a 24% coverage. But when I run coverage run manage.py test api followed by coverage html I get 100% covered. Why would this happen? -
Upgrade graphene-django to v3: 'Int cannot represent non-integer value"
I'm trying to upgrade graphene-django from 2.15.0 to 3.2.0. After some fixes, I could get it to work, but while testing with the front-end, I start detecting errors of the type: "Variable '$height' got invalid value '5'; Int cannot represent non-integer value: '5'" Apparently graphene-django 2.15 can translate string arguments (in this case '5') into number values, but 3.2 it can't. Is there a way to adapt the back-end so I don't have to change the front-end to correct the strings and turn them into numbers? -
Django + react with apache can't find django rest api
I have a django + react app that i wish to deploy on my VPS. I've installed apache for that and tried to configure it to work with django and react. When i only put django in the apache conf it does work with a curl command to the django api and react always works fine. But when putting django and react together in the conf file in apache it seems like when making post or get requests to the api it doesn't find the django api. Here is my app.conf in apache : <VirtualHost *:80> ServerName vps-*******.vps.ovh.net WSGIDaemonProcess app python-path=/home/gabriel/scanner:/home/gabriel/venv/lib/python3.11/site-packages WSGIProcessGroup app WSGIScriptAlias /api /home/gabriel/scanner/App/wsgi.py <Directory /home/gabriel/scanner/App> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /home/gabriel/scanner/staticfiles <Directory /home/gabriel/scanner/staticfiles> Require all granted </Directory> Alias /static-react /home/gabriel/scanner/frontend/build/static <Directory /home/gabriel/scanner/frontend/build/static> Require all granted </Directory> <Directory /home/gabriel/scanner/frontend/build> Options FollowSymLinks Require all granted RewriteEngine on RewriteCond %{REQUEST_URI} !^/api RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> CORS is allowed for all origins in my settings.py in django for testing and the whole settings.py file seems nicely configured. wsgy.py is nicely configured too and here is my urls.py : from django.contrib import admin from django.urls … -
Nginx can't serve Django url over Gunicorn Docker container
I am trying to deploy my Django Docker application with Nginx and Gunicorn.I followed this tutorial.I also managed to run my Django app on :8000 and Nginx on :80, I can reach both :80 and :8000 but when I try to connect to for example :80/app I just get a 404, at the same time I can connect to :8000/app. My main Docker File looks like: FROM python:3.10.6-alpine RUN pip install --upgrade pip COPY ./requirments.txt . RUN pip3 install -r requirments.txt COPY ./proto /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT [ "sh", "/entrypoint.sh" ] this run my entrypoint.sh: python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn proto.wsgi:application --bind 0.0.0.0:8000` and my compose.yml looks like: version: '3.7' services: django_proto: volumes: - static:/static env_file: - .env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - django_proto volumes: static: and my default.conf: upstream django { server django_proto:8000; } server { listen 80; location /static/ { alias /app/static; } location / { proxy_set_header Host $http_host; proxy_pass http://django; proxy_redirect off; } } I tried different folder constructs because I thought I was just trying to connect to the wrong folder path, I also tried different ports … -
Code on Django does not reflect on the created website
I'm currently learning how to use django so I watch a youtube video and its Tech with Tim. His tutorials are good and I followed all his instructions but unfortunately, I did not get the expected result. I try asking chatgpt but somehow it cannot help me to fix this problem. Please help me on this problementer image description hereenter image description hereenter image description here the problemproblem error 404 -
Unable to create a django project showing attribute error in django5.0
I am new to django while using django version 1.11.29 it worked successful when upgraded to latest version 5.0.4 it not working and showing error as below try this on venv shown same result is problem with python ,my python version 3.13.0a5+ I was tried to get django versio by python3 -m django --version it has been shown no module named django found -
Speed up problem with response Django REST API
We are got a project on gunicorn,django and nginx. Got a table in postgres with 600000 records with a big char fields(about 7500). That problem solved by triggers and searchvector. Also there api(rest) and 1 endpoint. On this endpoint db request take about 0.3 s. Its normal for us. But getting response take about 2 minutes.While we are waiting for a response one of process(they are a 8 cores) take about 100%. CPU User CPU time 201678.567 ms System CPU time 224.307 ms Total CPU time 201902.874 ms TOTAL TIME 202161.019 ms SQL 385 ms What we can to do to speed up time of response? I tryed to change settings if gunicorn,but that doesnt help. Than I try to start project by ./manage.py runserver on unused port and send request to endpoint and got the same results of time. I think the problem with view of REST API django. Django work with asgi now ,gunicorn and nginx. -
how to apply vuexy theme in django application
how to apply vuexy theme in django application? I want to apply vuexy theme in my django project can you tell me any documentation or guidence how to apply vuexy theme in django application? I want to apply vuexy theme in my django project can you tell me any documentation or guidence properway -
Failed to load module script: help needed
index-d5Zm7UFq.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec I am doing react+vite as frontend and django and mysql as backend. It runs without problem in localhsot:5173, but when i run on localhost:8000 it is showing this error, what i did was after building dist, i copied dist folder and pasted it on backend. I aslo configured settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'dist')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') MEDIA_URL = '/media/' I aslo setup urls.py: from django.urls import path, include, re_path from django.views.generic import TemplateView urlpatterns = [ path('auth/', include('djoser.urls.jwt')), re_path(r'^.*$', TemplateView.as_view(template_name='index.html')), path('vite.svg', TemplateView.as_view(template_name='vite.svg')), ] And it is showing blank when i access localhost:8000,and there is this error in console: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. -
Problem when integrating django project with deep learning model using h5 file
after i make all things in django project and have the h5 file of deep learning model using CNN , and when running the development server , and uploading image , the view function code import os import numpy as np from django.shortcuts import render, redirect from .forms import ImageUploadForm from .models import UploadedImage from tensorflow.keras.models import load_model from PIL import Image def upload_image(request): if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): image_instance = form.save() image_path = os.path.join('media', str(image_instance.image)) prediction = predict_disease(image_path) return render(request, 'prediction_result.html', {'prediction': prediction}) else: form = ImageUploadForm() return render(request, 'upload_image.html', {'form': form}) def predict_disease(image_path): model = load_model(r'C:\Users\pc\PycharmProjects\testingModelH5\models\EfficientNetB1-Skin-disease-b1-87.h5') image = Image.open(image_path) image = image.resize((224, 224)) image_array = np.array(image) / 255.0 image_array = np.expand_dims(image_array, axis=0) prediction = model.predict(image_array) return prediction the error occurs below Error when deserializing class 'DepthwiseConv2D' using config={'name': 'block1a_dwconv', 'trainable': True, 'dtype': 'float32', 'kernel_size': [3, 3], 'strides': [1, 1], 'padding': 'same', 'data_format': 'channels_last', 'dilation_rate': [1, 1], 'groups': 1, 'activation': 'linear', 'use_bias': False, 'bias_initializer': {'module': 'keras.initializers', 'class_name': 'Zeros', 'config': {}, 'registered_name': None}, 'bias_regularizer': None, 'activity_regularizer': None, 'bias_constraint': None, 'depth_multiplier': 1, 'depthwise_initializer': {'module': 'keras.initializers', 'class_name': 'VarianceScaling', 'config': {'scale': 2.0, 'mode': 'fan_out', 'distribution': 'truncated_normal', 'seed': None}, 'registered_name': None}, 'depthwise_regularizer': None, 'depthwise_constraint': None}. Exception encountered: Unrecognized keyword … -
is it necessary to use https instead of http to connect RN app with Django using axios?
i have been trying to send the post request to django using axios but it keeps showing axios; network error this below is axios.js import axios from "axios" import { Platform } from 'react-native'; const BASE_URL = Platform.OS === 'android' ? "https://10.0.2.2:8000" : "https://localhost:8000"; export const axiosInstance = axios.create({ baseURL: `${BASE_URL}`, headers: { } }) and RN app import React, { useState, useEffect } from 'react'; import { View, Text, Image, Alert, StyleSheet, TouchableOpacity, Platform } from 'react-native'; import axios from 'axios'; import * as ImagePicker from 'expo-image-picker'; import { Icon, Button } from '@rneui/themed'; const FoodPredictionScreen = ({ navigation }) => { const [prediction, setPrediction] = useState(''); const [imageUri, setImageUri] = useState(null); useEffect(() => { (async () => { if (Platform.OS !== 'web') { const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (status !== 'granted') { alert('Sorry, we need camera roll permissions to make this work!'); } } })(); }, []); useEffect(() => { console.log('Image URI state updated:', imageUri); }, [imageUri]); const selectImage = async () => { try { let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [6, 5], quality: 1, }); if (!result.cancelled) { setImageUri(result.assets[0].uri); console.log('Selected Image URI:', result.assets[0].uri); // Corrected line } } catch … -
Django (beginner) How Serialize several models
REAL PROBLEM: On DJANGO, I Have Several models,with some fiels such as MODEL1: NAME = ADDRESS = MODEyour textL2: NAME = ADDRESS = PET_NAME = MODEL3: NAME = ADDRESS = PET_NAME = BEER = I intent to use it as a parameter on GeoJSONLayerView.as_viewd. MY SOLUTION(?) How to get a 'MODEL' type with fields NAME and ADDRESS from ALL models, serialized? (Must be a MODEL, if using GeoJSONLayerView) Like a Sql select NAME, ADDRESS from MODEL1, MODEL2, MODEL3 How to get a MODEL with fields from seleral MODELS. -
Django Channels Config - Django / Docker / Gunicorn / Daphne / Nginx
I have deployed an app, pypilot.app using django / nginx / docker / daphne / gunicorn on a digital ocean droplet. Daphne is for Django Channels which works no problem in development to display messages in a user's console via websocket. I'm also able to connect to the websocket successfully when navigating to my droplet's IP address over http. When I try to connect to websocket via https at pypilot.app, however, I run into issues. I suspect something is wrong with my ssl setup perhaps? Please let me know if you spot any obvious issues in my setup below. docker compose version: '3' services: web: build: . command: gunicorn unicorn_python.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/code - .:/usr/src/app - /var/run/docker.sock:/var/run/docker.sock ports: - "8000:8000" daphne: build: . volumes: - .:/usr/src/app - .:/code ports: - "8001:8001" command: daphne -b 0.0.0.0 -p 8001 unicorn_python.asgi:application nginx: image: nginx:latest ports: - "80:80" - "443:443" volumes: - ./config/nginx:/etc/nginx/conf.d - /etc/letsencrypt:/etc/letsencrypt:ro - ./static:/usr/src/app/static # Host path to static files mounted inside the container - ./media:/usr/src/app/media # Host path to static files mounted inside the container depends_on: - web - daphne # If Nginx is set to proxy to Daphne as well celery: build: . command: celery -A unicorn_python … -
Django request.user isn't using the custom backend at all
I'm coding with a custom user model and a custom backend in Django 5.0 to login with an email. Here is the backend : class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): print("authenticate called") try: user = User.objects.get(email=username) except User.DoesNotExist: return None else: if user.check_password(password): return user return None def get_user(self, user_id): try: print(user_id) print("get_user called") return User.objects.get(pk=user_id) except User.DoesNotExist: return None It's correctly registered in AUTHENTICATION_BACKENDS, and the user model just have an email field. The backend works perfectly in my register view using authenticate(request, username=email, password=password), and the login(request, user) works too. However, if in another view, after a login I try to use request.user, it will always return AnonymousUser. If I do request.session.values, the user ID is correct. I can't find anyone having the same issue online, so I hope someone can help me troubleshoot it. I tried to use request.user with the custom backend, but it's never called. I also tried to use request.session.values and this time the user ID was correct. The request.user was supposed to return the current user with my custom model, but it always return AnonymousUser -
Detect if a Django related object has been prefetched via select_related
Let's say I have the following models: class Product: name = models.CharField(max_length=128) class ProductVersion: name = models.CharField(max_length=128) product = models.ForeignKey(Product, on_delete=models.CASCADE) For a given ProductVersion object, is there anyway to detect if the Product object was prefetched via select_related? For example: # Yes, "product" was prefetched ProductVersion.objects.select_related("product").first() # No, "product" was NOT prefetched ProductVersion.objects.first() Looks like there's a way to do this was prefetch_related (see here) but I need it for selected_related. -
Django / Celery : How a task can constantly do something ? Is it possible to set an infinite loop for a task?
I'm currently learning Django and Celery. So I have to do a feature to a Django projet, and I use Celery for that : I need to constantly check a list in my Redis server. And for that, I use Celery but I don't know how I can implement correctly that and I opted for a while True:. After the launching of my task with celery -A <my_project> worker -l INFO, it's impossible to kill the task (the CTRL + C doesn't work), or I don't found how I can. I conclude it's not a good method for doing what I want. One more thing : I know the extension django-celery-beat exists but I think it's "weird" to open another terminal for launch this extension. Already I have to launch my django server, then my worker (with celery) on two different terminals, I have to open a third to launch my scheduled task, I don't know if this is really weird to do that, but... I don't know, I think it's weird to do that but I don't know if it really is. Here's my (unique) task in an app in my django project : from celery import shared_task import … -
Rewrite User logic in Django
I need to completely rewrite the user logic in Django. I would like to store only 2 parameters in the database: phone number and telegram_id. The user could login and register with both of these parameters from one page. So I need to rewrite the model and write custom views and urls. The main question is how do I write a user model from scratch, replacing the standard django one. However, I wouldn't want to completely remove the user block and write it from scratch. Just models and some views and urls Search the internet.