Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove this box from the Django Signup form
In the tutorials I've followed, I didn't see this, so I assume it's because I recently updated django to 5.1. Now, there's this new box on the django signup view. It reads: Password-based authentication: Whether the user will be able to authenticate using a password or not. If disabled, they may still be able to authenticate using other backends, such as Single Sign-On or LDAP. Enabled Disabled I'd like to get rid of it as it makes the user creation process confusing for them. I'm not sure how to though. I'm currently just using css to hide it by selecting it - but I'm sure there's a better way. I'm already using a custom signup form which does NOT have this in it: class CustomSignupForm(UserCreationForm): email = forms.EmailField(max_length=254, required=True, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('email', 'password1', 'password2') -
Pattern for periodically fetching data from an external system
Assume I have a Django application with the following features: there's a Project model which has a created_at field the application supports a plugin system where a developer can create custom API endpoint and install them onto the application, exposing them publicly. The endpoints can run arbitrary code, but cannot schedule long running tasks (e.g. Celery tasks) My goal is to create a third party analytics service for this application. In order to do that, the analytics service needs to poll the application for new data periodically. Specifically, the analytics application needs to fetch any new projects. The first step is to create a plugin that will act as an "adapter", which exposes an API endpoint that presents the projects in a format that is useful to the analytics service. We have full control over this endpoint, which parameters it accepts, etc. Assume it answers using pagination. Now the question is: assuming the analytics service will perform one request per hour to get the new projects, what should be the pattern to only ask for new projects? There are two techniques which I've thought of, both with their advantages and disadvantages. Use a query parameter since specifying the timestamp of … -
How to use Async Redis Client + Django in python?
I'm trying to create a distributed semaphore using Redis to use in my Django application. This is to limit concurrent requests to an API. I'm using asyncio in redis-py. However, I want to create a connection pool to share across requests since I was getting a "Max clients reached" error. Thus, I created a shared connection pool in settings.py which I use in my semaphore class. However, I then get an error got Future <Future pending> attached to a different loop when I make concurrent requests. This is my code: import os import uuid import asyncio import time from typing import Any import random from django.conf import settings from redis import asyncio as aioredis STARTING_BACKOFF_S = 4 MAX_BACKOFF_S = 16 class SemaphoreTimeoutError(Exception): """Exception raised when a semaphore acquisition times out.""" def __init__(self, message: str) -> None: super().__init__(message) class RedisSemaphore: def __init__( self, key: str, max_locks: int, timeout: int = 30, wait_timeout: int = 30, ) -> None: """ Initialize the RedisSemaphore. :param redis_url: URL of the Redis server. :param key: Redis key for the semaphore. :param max_locks: Maximum number of concurrent locks. :param timeout: How long until the lock should automatically be timed out in seconds. :param wait_timeout: How long … -
How do I properly authenticate with OAuth using google-auth-oauthlib and Django?
I am building a Django project that works with video and needs to upload to Youtube. For this, I need oauth credentials. I am unable to authenticate with Oauth even though my redirect URI is correct and I am parsing the request for the code and passing it to the flow. I am using google-auth-oauthlib and oauth to authenticate. Here is what the error looks like: Traceback (most recent call last): File "/home/team/lotteh/venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/views.py", line 89, in sentry_wrapped_callback return callback(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/venv/lib/python3.12/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/users/views.py", line 47, in google_auth_callback email, token, refresh = parse_callback_url(request, code) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/users/oauth.py", line 66, in parse_callback_url flow.fetch_token(code=token_url) File "/home/team/lotteh/venv/lib/python3.12/site-packages/google_auth_oauthlib/flow.py", line 285, in fetch_token return self.oauth2session.fetch_token(self.client_config["token_uri"], **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/venv/lib/python3.12/site-packages/requests_oauthlib/oauth2_session.py", line 406, in fetch_token self._client.parse_request_body_response(r.text, scope=self.scope) File "/home/team/lotteh/venv/lib/python3.12/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 415, in parse_request_body_response self.token = parse_token_response(body, scope=scope) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/team/lotteh/venv/lib/python3.12/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 425, in parse_token_response validate_token_parameters(params) File "/home/team/lotteh/venv/lib/python3.12/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 432, in validate_token_parameters raise_from_error(params.get('error'), params) File "/home/team/lotteh/venv/lib/python3.12/site-packages/oauthlib/oauth2/rfc6749/errors.py", line 405, in raise_from_error raise cls(**kwargs)oauthlib.oauth2.rfc6749.errors.InvalidGrantError: (invalid_grant) Bad Request And the views: def google_auth(request): from django.shortcuts import redirect from … -
Cannot cast type bigint to UUID in Django migration when migrating from SQLite to PostgreSQL
I'm encountering an issue while migrating my Django project from SQLite to PostgreSQL. I had previously set the id field to UUID in SQLite, but now when applying the migration in PostgreSQL, I receive the following error: `django.db.utils.ProgrammingError: cannot cast type bigint to uuid LINE 1: ...ompany_company" ALTER COLUMN "id" TYPE uuid USING "id"::uuid ^ my models class Company(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) class Job(models.Model): BEGINNER = 'Beginner' MID = 'Mid' EXPERT = 'Expert' LEVEL_CHOICES = [ (BEGINNER, 'Beginner'), (MID, 'Mid'), (EXPERT, 'Expert'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) ` I initially developed my Django project using SQLite and set the id field of the Company model to UUID. Now that I am migrating the database to PostgreSQL, I need to update the id field to UUID in the PostgreSQL schema. Details: 1.Current Migration Code: # Generated by Django 4.2.7 on 2024-04-26 22:25 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('company', '0002_initial'), ] operations = [ migrations.AlterField( model_name='company', name='id', field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False), ), ] 2.Migration Error Message: psycopg2.errors.CannotCoerce: cannot cast type bigint to uuid LINE 1: ...ompany_company" ALTER COLUMN "id" TYPE uuid USING "id"::uuid ^ I … -
what is Password-based authentication in django
I made a form that inherits from the UserCreationForm and use class based view that inherits CreateView and when I use runserver and display the form, there is a section at the bottom Password-based authentication that I don't notice forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class RegisterForm(UserCreationForm): """Form to Create new User""" class Meta: model = get_user_model() fields = ["username", "password1", "password2"] views.py class SignUp(CreateView): form_class = RegisterForm template_name = "register.html" success_url = reverse_lazy("core:Login") def form_valid(self, form): user = form.save() if user: login(self.request, user) return super().form_valid(form) register.html <h1>signup</h1> {{form}} And when I ran the code I saw this output output image so i didn't expect password-based authentication. My question about What exactly this is ? Should it be displayed here ? How do I hide it ? -
How can custom django error views be tested?
In the Django documentation they provide the following example for testing custom error views. Given the following example how would you go about testing custom server_error and csrf_failure views? I've tried to trigger my error view using a few different django.core.exceptions however the custom error view is never run. Returning an HTTPResponse gives the error AssertionError: No templates used to render the response which makes sense. However when I try to raise an error that should trigger a server error like raise ImproperlyConfigured, the error is just raised in the test. Testing for CSRF failure is another story as I feel I'm not even close. # views.py from django.views import defaults from django.views.csrf import csrf_failure as csrf_failure_default def server_error(request): template_name = 'wholesale/500.html' return defaults.server_error( request, template_name=template_name, ) def csrf_failure(request, reason=''): template_name = 'wholesale/403_csrf.html' return csrf_failure_default( request, reason=reason, template_name=template_name, ) # tests.py from django.test import TestCase, override_settings from . import views def page_not_found_view(request): raise Http404 def server_error_view(request): # raise ImproperlyConfigured return HttpResponseServerError() def bad_request_view(request): raise BadRequest def permission_denied_view(request): raise PermissionDenied def csrf_failure_view(request): return HttpResponse(status=HTTPStatus.FORBIDDEN) urlpatterns = [ path('404/', page_not_found_view), path('500/', server_error_view), path('400/', bad_request_view), path('403/', permission_denied_view), path('403_csrf/', csrf_failure_view), ] handler404 = views.page_not_found handler500 = views.server_error handler400 = views.bad_request handler403 = views.permission_denied @override_settings(ROOT_URLCONF=__name__) … -
django-filters filter by Booleans or None with IN lookup expr
I'm trying to create a filter for DRF viewset that will filter my model field: is_claim_submitted = models.BooleanField( IS_CLAIM_SUBMITTED_NAME, blank=True, null=True ) I've written a filter according to django-filter docs class BoolInFilter(BaseInFilter, BooleanFilter): pass class DefectFilter(django_filters.FilterSet): is_claim_submitted__in = BoolInFilter( field_name="is_claim_submitted", lookup_expr="in", ) class Meta: model = Defect fields = { "id", "is_claim_submitted", } So I'm trying to filter a queryset by sending request http://localhost:8000/api/v1/defects/is_claim_submitted__in=true,false. Basicly, the values of URI param must be in a list of [True, False, None]. How ever it doesn't filter and it doesn't parse the values to python bools (true -> True). For some reason it doesn't get field_class = forms.NullBooleanField from BooleanFilter, but uses default Field parsing. I've already checked the MRO, though I still can't manage to figure out why my code doesn't work. The problem is precisely with BooleanFilter, as all the same but with NumberFilter and ids works fine. Is there a mistake in my code or is there a better way to implement such a filter? -
My django application is not rendering instead it is just showing the csrf middleware token id in the address bar
This is the views.py file section, class filterTask(View): def get(self, request): return render(request, 'filter-task.html'); def output(request): form = Taskform if request.method == 'GET': form = Taskform(request.GET.get('priorityChoice')) ans = Task.objects.filter(priority = form).values() return redirect(request, 'output.html',context={'ans':ans}) This is the filter-task.html file {% include 'base.html' %} `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <a href="{% url 'index' %}">Go To Homepage</a> <body> <h3>Filter Task by Priority</h3> <form method="get" autocomplete="off"> {% csrf_token %} <label id="priorityChoice">Enter the priority </label>: <select id="priorityChoice" name="priorityChoice" required> <option value="low">low</option> <option value="mid">mid</option> <option value="high">high</option><br> </select><br><br> <input type="submit" value="Submit"/> </form> </body> </html>` I am trying to filter a specific attribute of an object from the html file by getting the answer from a dropdown option, Kindly help me. I am trying to filter a specific attribute of an object from the html file by getting the answer from a dropdown option, Kindly help me. -
How to retrieve the URL of the uploaded image instead of the ID?
I have a Django RESTful application and a user can upload images from the Admin panel of Django. But the problem I am facing is that, in the corresponding API call, the IDs of the images are displayed instead of the URLs of the images. See the API call below (imag is the property): { "id": 30, "name": "Dier", "sort": "hghkjhkh", "uis": false, "cites": "B", "pet_list": "nvt", "description": "Wat een lekker dier", "feeding": "", "housing": "", "care": "", "literature": "", "images": "https://dier.blob.core.windows.net/media/media/photos/animals/amphibiance_X04Eh6N_1z0N4Gs_9EPmeMA_6j3axdY_da4cpTO_2VAY67x_hcUVB7f_bv9qvuY.jpg", "category": 11, "category_name": "mammal", "klasse_name": "mammal", "hdd_list_remark": "Wat een mooi dier", "bird_directive_list": "Bijlage|", "Habitat_directive_list": "Bijlage |V", "imag": [ 5, 6 ], }, So the corresponding code: model.py: import sys from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile from django.contrib.auth.models import Permission from PIL import Image from django.db import models from django.conf import settings class AnimalImage(models.Model): animal = models.ForeignKey( 'Animal', related_name='imag', on_delete=models.CASCADE) image = models.ImageField(upload_to='media/photos/animals') def __str__(self): return f"Image for {self.animal.name}" class Animal(models.Model): images = models.ImageField( upload_to="media/photos/animals", blank=False, null=False, verbose_name="Foto") animal_images = models.ManyToManyField( AnimalImage, related_name='related_animals', blank=True) def img_preview(self): # new return mark_safe(f'<img src = "{self.images.url}" width = "300"/>') img_preview.short_description = "Huidige Foto" def img_previews(self): images = self.images.all() return mark_safe(''.join([f'<img src="{img.image.url}" width="100"/>' for img in images])) img_previews.short_description = "Thumbnails" class … -
Problems with building dockerfile on GitHub Actions
I'm currently really freaking out about GitHub Actions. I have restructured my Django project on GitHub. Before my dockerfile worked like that: # Base image ARG arch=amd64 FROM --platform=linux/${arch} python:3 # Set work directory WORKDIR /appname # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . # Set default environment variables ENV DJANGO_SETTINGS_MODULE=appname.settings ENV DEBUG=False # Copy entrypoint script COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh # Command to run on container start ENTRYPOINT ["/entrypoint.sh"] where "appname" was the main repository of my django app where also the dockerfile layed in. I've restructured the app to make it way cleaner. Now my project looks like this (from root directory/github repo): .git/ .github/ apps/ appname/ config/ templates/ .gitignore manage.py requirements.txt README.md The dockerfile and entrypoint.sh are now in config/docker/.. So I've changed my dockerfile: # Base image ARG arch=amd64 FROM --platform=linux/${arch} python:3 WORKDIR /config # Set environment variables ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 ENV DJANGO_SETTINGS_MODULE=appname.settings ENV DEBUG=False # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt --no-cache-dir # Copy things COPY . . # Entrypoint script RUN chmod +x entrypoint.sh # Command to … -
AWS Application Load Balancer sticky session fails after targets change
I have a CloudFront distribution pointing to an Application Load Balancer, which is load balancing to ECS containers running a Django app. The ALB target group has stick sessions enabled using Application-based cookie, set to Django's sessionid cookie which is Django's main "logged-in" user indicator. All works well after the user logs in; Django sets the sessionid cookie and the ALB sets AWSALBAPP-0 cookie to a different value for each response, and the session stays sticky to a single ECS container. The problem is when I redeploy the app, and the containers stop. When the ALB directs traffic to new targets, I see the AWSALBAPP-0 cookie get set to _remove_. Always after this, the cookie value stays as _remove_ and the session is no longer sticky - it round-robin load balances. I have to log out and log back in to reestablish stickiness. Why is this happening? AWS documentation says: If a target fails or becomes unhealthy, the load balancer stops routing requests to that target, and chooses a new healthy target based on the chosen load balancing algorithm. The load balancer treats the session as now being "stuck" to the new healthy target, and continues routing requests to the … -
Blank pages after RollingUpdate for web deployment
We have a webserver based on Django+Gunicorn that is running in a kubernetes deployment. When we deploy a new version, we use RollingUpdate strategy. Any client that was connected to the webserver before the deployment gets a blank page. we suspect this could be due to an issue that is caused by browser cache, because it does seem to get resolved with a hard refresh. Is there a way to force refresh or store the cache in a different way so it won't impact the clients when we update the pods? any other suggestion will also be greatly appreciated -
Loading a pickle file into Django
I am working to develop on the website an application that built a picke file containing an object of a class defined on that project with specific data. I did not create that application and have no much knowledge of how pickle works. Now I want to move this app to a web version and I decided to go with django. To do not repeat the proces of creating those models I thought of directly load the pickle file in views.py and use the object already to make some operations. However, I am not sure how to make this load process as directly making the query: reg_model = pickle.load(open(r"C:\Users\...\pickle_file.pkl", 'rb')) throws error: An error occurred: No module named 'model' Error type: ModuleNotFoundError I started my django project from zero so I did not add any of the code from the app which creates the pickle. Should I? What am I missing? -
Django - website - ecommerce - ADD to cart ERROR
I am learning Python and Django and trying to create a Pilates Studio Website (as an e-commerce website, I'm following some tutorials) and I have a problem with ADD TO CART. I don't know why it doesn't work. When I click the button which supposes to add a product to a cart and I inspect the website I see that there is this error: POST http://127.0.0.1:8000/cart/add/ 500 (Internal Server Error) ` o = o("abort"); try { r.send(i.hasContent && i.data || null) } catch (e) { if (o) throw e }` Please, can you help me with it? I am totally stuck!!! I tried to add this product to a cart. I have tried to check if there are any problems with models etc. but everything looks good. I honestly have no idea what else can I do especially because I have just started learning Django and I don't know so much about it yet. views.py: `def cart_summary(request): return render(request, 'cart_summary.html', {}) def cart_add(request): # Get the cart cart = Cart(request) # test for POST if request.POST.get('action') == 'post': # Get stuff product_id = int(request.POST.get('product_id')) # product_qty = int(request.POST.get('product_qty')) # lookup product in DB product = get_object_or_404(Product, id=product_id) # Save to … -
Event type not found while using 2 consumers in a single django project
I have 2 consumers class KDPConsumer(JsonWebsocketConsumer): def connect(self): try: self.accept() self.user = self.scope["user"] print(f"User {self.user} connected.") if not self.user.is_authenticated: self.send_json({"error": "Incorrect authentication credentials."}) self.close() return # Join realm group self.realm = self.user.realm.name print(f"User {self.user.username} joined realm: {self.realm}.") async_to_sync(self.channel_layer.group_add)(self.realm, self.channel_name) except Exception as e: print(e) def disconnect(self, close_code): # Leave room group try: async_to_sync(self.channel_layer.group_discard)(self.realm, self.channel_name) print(f"User {self.user.username} disconnected from realm: {self.realm}.") except Exception as e: print(e) def receive_json(self, content, **kwargs): print(f"Received content: {content}") message = content.get("message") event_type = content.get("notification_type") if event_type == "send_notification_socket": self.handle_send_notification_socket(content) else: # Send message to room group self.send_message_to_channels_group(self.realm, message) def realm_message(self, event): try: print(f"Received realm message event: {event}") messages = event["message"] for message in messages: self.send_json( { "message": message, "user": self.user.username, } ) except Exception as e: print(e) @classmethod def send_message_to_channels_group(cls, realm, app_id): try: if app_id == AppTypes.umbrella: contracts = async_to_sync(cls.get_contracts)(realm) for contract in contracts: async_to_sync(channel_layer.group_send)(realm, {"type": "realm_message", "message": contract}) else: drafts = async_to_sync(cls.get_drafts)(realm) for draft in drafts: async_to_sync(channel_layer.group_send)(realm, {"type": "realm_message", "message": draft}) except Exception as e: print(e) @staticmethod @sync_to_async def get_contracts(realm): try: return Contract.objects.filter( created_by__realm__name=realm, module_type="Contract", kdp_status_done=False, created_on__gt=datetime.datetime.now() - datetime.timedelta(hours=1), ).all() except Exception as e: print(e) @staticmethod @sync_to_async def get_drafts(realm): try: return Draft.objects.filter( realm=realm, link__contains=settings.AWS_CLM_DOCUMENT_STYLUS_BUCKET_NAME, created_on__gt=datetime.datetime.now() - datetime.timedelta(hours=1), ).all() except Exception as e: print(e) def handle_send_notification_socket(self, … -
How to resolve uploading multiple images works, but the API call returns an empty array?
I have a Django REST API and I have a function for uploading multiple images in the admin of Django. And everything works fine: a user can upload multiple images and also the images are stored in the database table DierenWelzijnAdmin_animalimage But if I call: http://127.0.0.1:8000/api/animals/ I see an empty array returned: { "id": 30, "images": "https://dier.blob.core.windows.net/media/media/photos/animals/amphibiance_X04Eh6N_1z0N4Gs_9EPmeMA_6j3axdY_da4cpTO_2VAY67x_hcUVB7f.jpg", "animal_images": [] }, This is the model: import sys from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile from django.contrib.auth.models import Permission from PIL import Image from django.db import models from django.conf import settings class AnimalImage(models.Model): animal = models.ForeignKey( 'Animal', related_name='imag', on_delete=models.CASCADE) image = models.ImageField(upload_to='media/photos/animals') def __str__(self): return f"Image for {self.animal.name}" class Animal(models.Model): images = models.ImageField( upload_to="media/photos/animals", blank=False, null=False, verbose_name="Foto") animal_images = models.ManyToManyField( AnimalImage, related_name='related_animals', blank=True) def img_preview(self): # new return mark_safe(f'<img src = "{self.images.url}" width = "300"/>') img_preview.short_description = "Huidige Foto" def img_previews(self): images = self.images.all() return mark_safe(''.join([f'<img src="{img.image.url}" width="100"/>' for img in images])) img_previews.short_description = "Thumbnails" class Meta: verbose_name = "Dier" verbose_name_plural = "Dieren" # permissions = [("set_display_flag", "Check name is display or not",)] super(Animal, self).save() def __str__(self): return self.name admin.py file: from django.contrib import admin from django.db import models from django.forms import RadioSelect from django.http import HttpResponseRedirect from django.urls import reverse … -
Unable to Filter Decimal128 Field in MongoDB with Django, But Can Filter Integer and String Fields
I'm working on a Django project using MongoDB as my database. I have a Product model with a Decimal128 field for storing product prices. I'm trying to filter products based on price, but I'm encountering issues when attempting to filter using the Decimal128 field. Here's the relevant part of my code: class FilterProducts(View): def get(self, request): try: category = request.GET.get("category") min_prices = request.GET.get("min_price") max_price = request.GET.get("max_price") all_products = Product.objects.all() if category: all_products = all_products.filter(category=category) if min_prices: all_products = all_products.filter(price__gte=min_prices) print(min_prices) if max_price: all_products = all_products.filter(price__lte=max_price) response = [ { "title": product.name, "category": product.category, "price": product.price.to_decimal(), "description": product.description, } for product in all_products ] return JsonResponse(response, status=200, safe=False) except Exception as e: return HttpResponseBadRequest(str(e), status=400) Below is the Model created for Product: class Product(models.Model): product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) image = models.CharField(max_length=100) brand = models.CharField(max_length=100) shipping = models.CharField(max_length=100) description = models.TextField(max_length=500) price = models.DecimalField(decimal_places=2, max_digits=8) category = models.CharField(max_length=100) is_featured = models.BooleanField(default=False) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name The Issue: When I try to filter the Decimal128 price field, no results are returned, even when I know that matching data exists. Filtering based on integer or string fields works perfectly fine like Category. I've tried converting the … -
default=timezone.now in DateTimeField. What's timezone.now and what's the difference between it and auto_now_add?
class Post(models.Model): ... publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) GPT gave me this explanation: default=timezone.now: Sets the field to the current time by default but can be overridden when creating an object. auto_now_add=True: Automatically sets the field to the current time when the object is created and cannot be overridden. Is that it? I feel that this explanation isn't complete, that there's also something else. GPT says that timezone.now() in Django returns the current datetime in the current timezone as set in your Django project settings. Why to set datetimefield in the current timezone? I feel that there's some other difference besides just the ability to be overriden, or no? -
Video streaming with django from jellyfin
I made a streaming application with django from a jellyfin server, I use video js to play my video media. the problem is that when I try to play videos that are more than 1 hour long and longer it takes crazy time it seems that the video is first downloaded and then played and what's more I can't advance the media and put in the position I want, I first suspected a video js option called preload, so I tried the values 'none', 'metadata' and 'auto', but nothing there Actually, a colleague gave me a guess that maybe django doesn't support this kind of functionality! Can anyone confirm this? what could be the solution with django -
What is the better way to create multiple user types in Django? abstract classes or proxy models?
I want to create multiple user types in Django. The user types are 'Admin', 'Company' and 'Individual'. Should I use abstract models or proxy models for this requirement. I have already done this using proxy models. How would it be done using abstract models instead? Is any one of them better than the other? If so, how? Here is how I have implemented it using proxy models. models.py: class User(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True) email = models.EmailField(max_length=150, unique=True, null=False, blank=False) role = models.CharField(max_length=50, choices=Role.choices, null=False, blank=True) is_staff = models.BooleanField(null=False, default=False) is_active = models.BooleanField(null=False, default=True) is_superuser = models.BooleanField(null=False, default=False) objects = AccountManager() USERNAME_FIELD = "email" def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_staff def has_module_perms(self, app_label): return self.is_superuser class Admin(User): objects = AdminManager() class Meta: proxy = True def custom_method_for_admin_only(self): return something class AdminProfile(models.Model): admin = models.OneToOneField( Admin, on_delete=models.CASCADE, related_name="admin_profile" ) first_name = models.CharField(max_length=50, null=False, blank=False) middle_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=False, blank=False) def __str__(self): return f"{self.first_name} {self.last_name}" class Company(User): objects = CompanyManager() class Meta: proxy = True def custom_method_for_company_only(self): return something class CompanyProfile(models.Model): company = models.OneToOneField( Company, on_delete=models.CASCADE, related_name="company_profile" ) name = models.CharField(max_length=50, null=False, blank=False) is_verified = models.BooleanField(default=False, null=False, blank=True) logo = models.ImageField(upload_to="images/", null=True, blank=True) … -
creating a django project using 3.9.18 version in anconda prompt
i want to create a djongo project using python version = 3.9.18 . in my system i intalled python version is 3.12.4. how i can do this . my project related to the virsion is 3.8.18 i am expeting answer how i can (base) C:\Users\ACER\Desktop\newone>django-admin startproject new Traceback (most recent call last): File "C:\Users\ACER\anaconda3\lib\runpy.py", line 197, in run_module_as_main return run_code(code, main_globals, None, File "C:\Users\ACER\anaconda3\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\ACER\anaconda3\Scripts\django-admin.exe_main.py", line 4, in File "C:\Users\ACER\anaconda3\lib\site-packages\django\core\management_init.py", line 19, in from django.core.management.base import ( File "C:\Users\ACER\anaconda3\lib\site-packages\django\core\management\base.py", line 14, in from django.core import checks File "C:\Users\ACER\anaconda3\lib\site-packages\django\core\checks_init.py", line 26, in import django.core.checks.templates # NOQA isort:skip File "C:\Users\ACER\anaconda3\lib\site-packages\django\core\checks\templates.py", line 5, in from django.template.backends.django import get_template_tag_modules File "C:\Users\ACER\anaconda3\lib\site-packages\django\template_init_.py", line 44, in from .engine import Engine File "C:\Users\ACER\anaconda3\lib\site-packages\django\template\engine.py", line 7, in from .base import Template File "C:\Users\ACER\anaconda3\lib\site-packages\django\template\base.py", line 60, in from django.utils.html import conditional_escape, escape File "C:\Users\ACER\anaconda3\lib\site-packages\django\utils\html.py", line 11, in from django.utils.encoding import punycode File "C:\Users\ACER\anaconda3\lib\site-packages\django\utils\encoding.py", line 5, in from types import NoneType ImportError: cannot import name 'NoneType' from 'types' (C:\Users\ACER\anaconda3\lib\types.py)create a project and also how i can run the project. -
creation d'une authentification avec QR code en utilisant python Django
Comment crée une authentification avec QR code en utilisant python Django ? j'ai essayer le module django-qrauth, et ca pas marcher ainsi le module django_qr_code-4.1.0, et aussi ca pas marcher mais sans résultat ... quelqu'un peux m'aider a passer cette étape ? -
How to store user credentials temporarily for email verification in a django web app?
I want to create my own email verification flow, where the user enters his credentials and gets an OTP on the given email. When user enters the correct OTP within the time limit of 10 minutes, it will register the user and his credentials will be stored permanently in my database. How do I store the credentials temporarily for a time limit of 10 minutes ? I am thinking of storing the credentials after hashing using django_pbkdf2_sha256 library and storing it in my redis cache for a time of 10 minutes. If the user tries to enter it after this time, they will require a new OTP to register. Is this a good idea ? -
How to run periodic task in Django without using celery?
I need run a periodic task in Django to update some Prometheus metrics, then I realized that I cannot use celery, because celery runs in other workers while Prometheus metrics are in-memory objects. I am quite new to Django. If I do this in Go, I will start a thread (go-routine), but I am not sure if I should start a thread in Django as Django is like a block-box to me. If I should, then where to start to thread? In settings.py or elsewhere?