Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can not access the values of dictionary using jinja
Here is my views.py def following(request): currentUser = User.objects.get(pk=request.user.id) currentUser_followings = Following_System.objects.get(user=currentUser).following allPosts = Post.objects.all().order_by("-timestamp").reverse() followingPosts = [] for user in currentUser_followings.all(): for post in allPosts: if post.author == user: followingPosts.append(post) **post_likers_ids = {post.id: list(post.likers.values_list('id', flat=True)) for post in followingPosts}** # Show 10 posts per page. paginator = Paginator(followingPosts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/following.html",{ "page_obj": page_obj, "post_likers_ids" : post_likers_ids }) I debug, and the post_likers_ids return: ({4: [2], 2: [1,3,5]}) And now in my following html why the if condition is always false (Although it should be true for some, cause I know the expected input output): {% for post in page_obj %} <div class="list-group-item"> {% with post_id=post.id %} {% if user.id in post_likers_ids.post_id %} <p>The user liked this </p> {% else %} <p>The user have not liked this </p> {% endif %} {% endwith %} </div> {% endfor %} Here is my model if that helps: class Post(models.Model): content = models.TextField(blank=False) author = models.ForeignKey("User", on_delete=models.CASCADE, related_name="author") timestamp = models.DateTimeField(auto_now_add=True) likers = models.ManyToManyField("User", related_name="liked_posts", blank=True) def serialize(self): likes_count = self.likers.count() # likers = [user.id for user in self.likers.all()] return { "id": self.id, "content": self.content, "author": self.author.username, "author_id": self.author.id, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), "likes": … -
Django Fulltext search is very slow how to make it fast?
I possess an extensive database of products and aim to implement full-text search functionality to enable users to easily search for products. I've employed SearchVector with Postgres for this purpose; however, the performance is quite sluggish. Despite attempting to enhance speed through indexing, it hasn't yielded the desired results. Below is a snippet of the code I've been working with. models.py class Product(models.Model): brand = models.ForeignKey(BrandName,related_name="brand_products", on_delete=models.CASCADE,db_index = True) item_name_title = models.CharField(max_length=10000, db_index = True,) product_description = models.TextField(db_index = True,) class Meta: indexes = [ GinIndex(fields=['search_vector']), ] Views.py search = request.GET.get('search') search_vector = SearchVector( 'product__mob_sku', 'product__item_name_title', 'product__product_description', 'product__brand__brand_name', ) query = SearchQuery(search) vendor_products = VendorProducts.objects.annotate( rank = (SearchRank(search_vector , query)) ).filter(rank__gte=0.001).select_related( 'vendor', 'product').prefetch_related( 'product__product_images', 'product__brand').exclude( vendor__vendor_name = "ALL_123").order_by('-rank') -
Django: Handling Expired API Keys Without Signals
Title: Django: Handling Expired API Keys Without Signals Question: How can I implement a logic in Django to automatically delete expired API keys from the OutstandingKey model and update the corresponding BlacklistedKey entry when the expiry date has passed, without using signals? I have two Django models: OutstandingKey and BlacklistedKey. The OutstandingKey model represents API keys generated by users, including an expiry date field. The BlacklistedKey model stores blacklisted API keys, referencing the OutstandingKey through a one-to-one relationship. I want to create a system where expired API keys are automatically removed from the OutstandingKey model and added to the BlacklistedKey model when their expiry date has passed. However, I prefer not to use signals for this implementation due to this Django Anti-Pattern. Could someone provide a blueprint or example of how to achieve this logic within Django?. Below is my Models from django.db import models from django.conf import settings from django.utils import timezone class OutstandingKey(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, default=None, verbose_name="User", ) name = models.CharField(max_length=1000, default="", blank=True, null=True) api_key = models.CharField( max_length=1000, unique=True, verbose_name="API Key", default="", blank=True, null=True, editable=False, ) expiry_date = models.DateTimeField( default=None, verbose_name="Expiry Date", blank=True, null=True ) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class … -
How to make the price of the product to be dynamically changed in Django?
I'm using Django framework. I've addded product variants like size, color and glass. Now, I need the price to be dynamically changed with selecting product options. The price doesn't change when I'm choosing different options of the product, it remains the same. Here is my ajax part: $('#size, #color, #glass').on('change', function () { const productId = $('#product-id').val(); const sizeId = $('#size').val(); const colorId = $('#color').val(); const glassId = $('#glass').val(); console.log("Selected values:", productId, sizeId, colorId, glassId); // Log captured values if (productId && sizeId && colorId && glassId) { calculateUpdatedPrice(productId, sizeId, colorId, glassId); } }); function calculateUpdatedPrice(productId, sizeId, colorId, glassId) { const url = `/get_variant/?product_id=${productId}&size=${sizeId}&color=${colorId}&glass=${glassId}`; console.log("Fetching price from URL:", url); // Log request URL fetch(url) .then(response => response.json()) .then(data => { console.log("Response data:", data); // Log server response const priceElement = document.getElementById('price'); const sellPriceElement = document.getElementById('sell-price'); priceElement.textContent = data.price; sellPriceElement.textContent = data.price; }) .catch(error => console.error('Error:', error)); } And product detail : {% for variant in product.variants.all %} <p>Size: {{ variant.size.name }}</p> <p>Color: {{ variant.color.name }}</p> <p>Glass: {{ variant.glass.name }}</p> <p>Price: <span id="price">{{ variant.price }}</span></p> {% endfor %} <div class="mb-3"> <strong><label for="size" class="form-label">Ölçü:</label></strong> <div class="dropdown-wrapper" style="width: 120px;"> <select class="form-select" id="size"> {% for size in sizes %} <option value="{{ size.id }}">{{ size.name … -
Create another object when I create an object in django model
When i create an object like: bus_stop_1 = 4(Foreign Key) bus_stop_2 = 7 then it should automatically create other object with bus_stop_1 = 7 bus_stop_2 = 4 ** time and distance would be the same ** BusStop is an model My model class ConnectedRoute(models.Model): bus_stop_1 = models.ForeignKey( BusStop, on_delete=models.CASCADE, related_name='stop1') bus_stop_2 = models.ForeignKey( BusStop, on_delete=models.CASCADE, related_name='stop2') distance = models.FloatField(blank=True, null=True) time = models.TimeField(blank=True, null=True) I have tried this my using save method and saving the ConnectedRoute but it been called recursively again and again. def save(self, *args, **kwargs): # Check if the object is being created for the first time if not self.pk: # Create a new ConnectedRoute object with reversed bus stops reverse_connected_route = ConnectedRoute( bus_stop_1=self.bus_stop_2, bus_stop_2=self.bus_stop_1, distance=self.distance, time=self.time ) reverse_connected_route.save() # Save the reversed object super().save(*args, **kwargs) -
Django Channels - Sending message to multiple channels
I created a room dict which which stores channels of consumers which belong to a specific group, now when any consumers sends a message i want all the channels to get that message ... but I only know self.send function to send message how do i send message to all channels. Channels are stored in the following way : from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class MyWebsocketConsumer(WebsocketConsumer): room = {} def connect(self): print("Connected...",self.channel_name) self.group_name = self.scope['url_route']['kwargs']['group_name'] print('Group Name...',self.group_name) try: if self.room[self.group_name]: self.room[self.group_name].append(self.channel_name) except: self.room[self.group_name]= [self.channel_name] self.accept() print(self.room) def receive(self, text_data=None, bytes_data=None): # Help with logic here pass def disconnect(self, close_code): self.room[self.group_name].remove(self.channel_name) -
django using drf-spectacular, I cannot customize schema with @extend_schema decorator
I have the following view: class ReferralCodeList(generics.ListCreateAPIView): queryset = ReferralCode.objects.all() serializer_class = ReferralCodeSerializer def get_queryset(self): queryset = super().get_queryset() queryset = queryset.filter(user=self.request.user) return queryset @extend_schema( description='More descriptive text', ) def create(self, request, *args, **kwargs): request.data['user'] = request.user.id serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) if 'send_mail' in request.data.keys() and \ request.data['send_mail'] == True: send_mail( "Your referral code", serializer.data['code_str'], project_settings.EMAIL_HOST_USER, [request.user.email], fail_silently=False, ) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) I execute ./manage.py spectacular --color --file schema.yml But I don't see any changes to the view's description. When I change the serializer, I see the respective changes in swagger page. What am I doing wrong? Thanks -
Heroku logging for django management commands
I would like to log statements when running a Django management command on Heroku. So, for example, when I login to Heroku and run the command: heroku run bash python manage.py my_management_command I should see all of the logging.info statements included. But instead they don't appear in the Heroku logs. All logging.info statements from the normal django appear fine, just not when I run a management command. My logger setup in settings.py is as follows: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'mylogger': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, 'formatters': { 'verbose': { 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s' }, }, } Can anyone tell me how to get log statements from inside my django management command to appear in the heroku logs? -
django using APIView can't override default djangorestframework permission classes
I'm trying to add swagger to my app, like stated here: https://django-rest-swagger.readthedocs.io/en/latest/schema/#advanced-usage So I've added this: class SwaggerSchemaView(APIView): permission_classes = [AllowAny] renderer_classes = [ renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer ] def get(self, request): generator = SchemaGenerator() schema = generator.get_schema(request=request) return Response(schema) I have the following lines in my settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } When I go to swagger url, I get this: HTTP 401 Unauthorized Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Bearer realm="api" { "detail": "Authentication credentials were not provided." } But I am expecting permission_classes to override the default ones. What am I doing wrong? Thank you -
How can I resolve ModuleNotFound Error in Django?
I have been working on a Django project for some time now. However, I am unable to resolve this error when I start the development server: Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'scraper_app' Based off previous posts I've read, I suspected the issue could lie in my file structuring. But my structure (below) appears to be alright. djangoProject [**scraper**] ├── djangoProject │ ├── __init__.py │ ├── asgi.py │ ├── scraper_app │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── templates │ ├── results.html │ └── search.html └── … -
How to Embed google review in Django website?
I was going through the Google Cloud Platform Console to find out how I could embed a Google review on my Django website. I found the Google Places API to be the most relevant (not quite sure), but then I got lost with all the details, pricing, and different tiers. My case is actually quite simple. I just want to display the total number of stars a specific place has. Is there a free way to get that, which I didn't understand? -
Portable windows app built with electron-builder takes too long to start up
I have used electron-builder to package my React + Django application into a single executable file. When I build the app, the resulting dist folder contains: -- dist (folder generated after building the app with electron) | |- MyApp0.0.1.exe (portable exe file) | |- win-unpacked | | | |-MyApp.exe | |-multiple_folders (dependencies of the MyApp.exe) | |-multiple_files (dependencies of the MyApp.exe) The problem is the following: When runnning the MyApp.exe inside the win-unpacked folder, and as long as the dependency files/folders are at the same level, the app works perfectly fine and takes less than a second to startup and display. It even asks for admin password, as in the package.json config it is specified to build it with "requestedExecutionLevel": "highestAvailable". When running the MyApp0.0.1.exe which is supposed to be the portable, standalone .exe file for the application, although it does run perfectly fine, it takes up to 6 minutes to start-up and display the app. I have tried skimming down the project as much as possible in terms of the node_modules that I need, removing large data files not needed, ... I am clueless as to why this is happening. I am not a web-dev expert in any way … -
Custom Admin Site in Django
I have problem to change title_header, site_header, index_title in custom admin site. My admin.py: from reviews.models import Movie, MovieCasts, Review, Actor class CritiflixAdminSite(AdminSite): title_header = 'Aplikacja administracyjna Critiflix' site_header = 'Aplikacja administracyjna Critiflix' index_title = 'Administracja witryną Critiflix' movie_admin_site = CritiflixAdminSite(name='critiflix') movie_admin_site.register(Movie) movie_admin_site.register(MovieCasts) movie_admin_site.register(Review) movie_admin_site.register(Actor) My urls.py: from django.urls import include, path from . import views urlpatterns = [ path('admin/', movie_admin_site.urls), path('movies/', views.movie_list, name = 'movie_list'), path('movies/<int:pk>', views.movie_detail, name = 'movie_detail'), path('', views.base, name = 'base') ] When i run manage.py nothing is change and models aren't on panel. -
Sending and receiving custom signals in Django and ensuring it is atomic
I want to create a custom signal and send the signal after some database operations. The receiver also performs database operations. I want to make sure all the database operations before sending the signal and in the signal, receiver is atomic meaning either all fail, or all succeed. Consider the following code: def send_my_signal(): # Database operation 1 # Database Operation 2 my_signal.send(sender=MyModel) The receiver: @receiver(my_signal) def my_receiver(sender, **kwargs): # Database operation 3 # Database operation 4 I want either all database operations 1 to 4 succeed or fail together. By asking from generative AI models, one proposed solution is to wrap the body of the function that performs database operations and sends the signal inside the transaction.atomic() context manager. So, the code would look like this: def send_my_signal(): with transaction.atomic(): # Database operation 1 # Database Operation 2 my_signal.send(sender=MyModel) But I could not find any resource or anything in Django documentation confirming this. It's not like I am calling the receiver of the signal inside the transaction.atomic() context manager, I am just sending the signal there. -
Optimizing One-to-Many Joins in Django MySQL ORM for Better Data Presentation
In Django MySQL ORM, I wanted to join tables with one-to-many relations. Consider a scenario where one user can belong to more than one department. Users and Departments are different entities. Now, if I want to demonstrate the rows as, User columns and department names the user belongs to in a single column as a list. How do I do that most efficiently? Example: class User(models.Model): name = models.CharField(max_length=100) class Department(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) Output: [ {'id': 1, 'name': 'John', 'department_names': ['HR', 'IT']}, {'id': 2, 'name': 'Alice', 'department_names': ['Finance']} ] I tried this: queryset = User.objects.values( 'id', 'name', ).annotate( department_names=Concat( 'department__name', Value(', '), output_field=CharField(), ) ).filter( department__isnull=False ).distinct() But got this: <QuerySet [ {'id': 1, 'name': 'John', 'department_names': 'HR, '}, {'id': 1, 'name': 'John', 'department_names': 'IT, '}, {'id': 2, 'name': 'Alice', 'department_names': 'Finance,'} ]> Expecting something this: <QuerySet [ {'id': 1, 'name': 'John', 'department_names': 'HR, IT'}, {'id': 2, 'name': 'Alice', 'department_names': 'Finance'} ]> -
Validate Django `JSONField` values are dictionaries
Is there anyway to require that a Django JSONField stores dictionary values only? And throws an error on scalar values. For example, I want the following values to be valid: {} {"a": 1} {"a": 1, "b": 2} And I want the following values to be invalid: "hello world" True 1 JSONField currently accepts all of these values, which makes sense because they're all valid json. But I want to change that behavior. -
How do I reduce the number of connections requests created by a multithreaded Django request?
My project is roughly set up like this thread_pool = ThreadPoolExecutor() def my_background_thread(model: MyModel): # Other DB Reads here ... # Some long running action here, spawning several threads ... # Save result of action to DB model.field = val model.save() # Other DB writes ... def my_view(request): model = MyModel.objects.get(...) thread_pool.submit(my_background_thread, model) # Return before thread has completed return HttpResponse("success") Unfortunately, because of the way I've set it up, Django is creating far too many DB connections -- more than necessary and exceeding my DB limits. Some things that are not clear: When I pass model to the new thread, does it create a new connection at that point? Does it create a new connection only when I read / write to the model? Only when I write? How do I check the number of open connections, or show when a connection is created? In short, how can I prevent Django from creating too many connections in this scenario? -
Emulating an empty queryset with an abstract model
I have a use case in which I have a ListAPIView that connects to a 3rd party (Stripe) API, fetches data (invoices) and returns that data to the user. I have a serializer, but I don't have a model. The entire code looks something like this: class InvoicesList(generics.ListAPIView): serializer_class = InvoiceSerializer def get_queryset(self): if getattr(self, 'swagger_fake_view', False): return # <---- ¿?¿?¿?¿?¿?¿?¿?¿? return StripeWrapper().get_invoices() class InvoiceSerializer(serializers.Serializer): ...fields.. ...fields... ...fields class StripeWrapper(): def get_invoices(): return requests.get(......) Since I don't have a model, drf-spectacular refuses to generate the proper openapi specs. It expects to receive an EmptyQuerySet (SomeModel.objects.none()), but I can't provide it any since I don't have an Invoice model. I could create an abstract model like this: class Invoice(models.Model): class Meta: abstract = True but I still won't be able to provide drf-spectacular with an Invoice.objects.none() since there is no manager in that class (and there can't be since it's abstract). How can I "emulate" (¿?) or "generate" an EmptyQuerySet so I can workaround this issue? -
Django get all Models with an associated Model
Hi im currently trying to learn Django. How would I write a query to get all Person instances that have an associated existing Form instance. For example: These are my models: class Person(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) class Form(models.Model): filled_by = models.ForeignKey(Person, on_delete=models.CASCADE) I have the following Person objects PersonA: {id: 1, name: 'Will'} PersonB: {id: 2, name: 'Greg'} PersonC: {id: 3 name: 'Dan'} And the following Form objects Form1: {filled_by: PersonA} Form2: {filled_by: PersonC} Query should return PersonA and PersonC -
AssertionError: Model userauths.User can't have more than one auto-generated field
This is my user model from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.utils.translation import gettext_lazy as _ import uuid from django.utils import timezone class CustomUserManager(BaseUserManager): """Manager for users""" def email_validator(self, email): try: validate_email(email) return True except ValidationError: raise ValueError(_("You must provide your interac email address")) def create_user(self, first_name, last_name, email, password, **extra_fields): """Create, save and return a new user""" if not first_name: raise ValueError(_("Users must have a first name")) if not last_name: raise ValueError(_("Users must have a last name")) if email: email = self.normalize_email(email) self.email_validator(email) else: raise ValueError(_("Users must have an email address.")) user = self.model(email=email, first_name=first_name, last_name=last_name **extra_fields) user.set_password(password) extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, email, password, **extra_fields): """Create and return a new super user""" user = self.create_user(first_name, last_name, email, password) extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("Superuser must have is_staff=True")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("Superuser must have is_staff=True")) if extra_fields.get("is_active") is not True: raise ValueError(_("Superuser must have is_active=True")) if not password: raise ValueError(_("Superuser must have a password")) if email: email = self.normalize_email(email) self.email_validator(email) else: raise ValueError(_("Superuser must have an email address.")) … -
Internal Server Error 500 Django on Apahce
Created a getting started Django app (Rocket screen..). Implemented serving the Django app locally via Apache according to this guide. Followed all the previous threads here in stack. Result: localhost:8000 Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at admin@example.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. httpd -e debug [Thu Feb 08 19:44:25.462095 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module actions_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_actions.so [Thu Feb 08 19:44:25.463099 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module alias_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_alias.so [Thu Feb 08 19:44:25.465112 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module allowmethods_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_allowmethods.so [Thu Feb 08 19:44:25.466114 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module asis_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_asis.so [Thu Feb 08 19:44:25.467114 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module auth_basic_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_auth_basic.so [Thu Feb 08 19:44:25.468159 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module authn_core_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_authn_core.so [Thu Feb 08 19:44:25.470163 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module authn_file_module from … -
django authenticate error with DJANGO_SETTINGS_MODULE
im new to django . I was doing some things to figure out how the code works. I did some part of the tutorial. I have an app folder named polls and the standard mysite folder where there is the settings.py file . I created another python file in mysite folder , auth.py and I wrote this code : from django.contrib.auth import authenticate user_auth = authenticate(username = "test-username", password = "test-password") print(user_auth) What I want to do is just see what the authenticate function returns. I want to know certain things like , where are the credentials searched for the authentication. I don't know any of that and that's the reason I want to print some things in the code. First question is, can I do that ? I always have learned coding with actually doing the things from the very basics, looking for what is happening with the code . The second question is that im trying to run the code but it gives me an error : django.core.exceptions.ImproperlyConfigured: Requested setting AUTHENTICATION_BACKENDS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I searched in google and I found the … -
Django - how do I filter or exclude by two identical fields?
We are using Django for our website. I have a query for model User and I want to exclude users which have two identical fields - in this case id and username. So if the id==username, I want to exclude them. How do I do it? The query looks like: users = User.objects.filter(...) And I want to add .exclude(...) where the id and username fields are equal. -
Django | NOT NULL constraint failed | When trying to reverse migrations
I, on a whim, made a bad decision to comment out a models.OneToOneField in one of my models and then migrate to see if it fixed a problem I was having. I realized after that I can't just re-migrate a models.OneToOneField in the same way I had originally and it started to throw the error "django.db.utils.IntegrityError: UNIQUE constraint failed:" this being because I was trying to re-migrate a models.OneToOneField back into my model I didn't think this was a huge issue, I was just going to reverse migrate to "0008_alter_profile_profile_private" because "0009_remove_profile_user" was the migration that caused the issue to start with. But now it's throwing the error "django.db.utils.IntegrityError: NOT NULL constraint failed: new__profiles_profile.user_id" Here is all the code that I understand to be important: Excerpt of my: models.py in "profiles" app: class Profile(models.Model): # User Profile model user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) #creates a OneToOneField connected to the user, that when the user gets deleted, so does the profile riot_name = models.TextField(default="RiotUser#1234") # Riot Username avatar = models.ImageField(upload_to='avatars', default='avatar.png') # Profile Image Field banner = models.ImageField(upload_to='banners', default='banner.jpg') # Banner Image Field friends = models.ManyToManyField(User, related_name='friends', blank=True) # Friends list bio = models.TextField (default="I don't have a bio... :(") # … -
django_countries not being recognized for import in my Pycharm
I am building an ecommerce website with Django and I want to add a dropdown menu for the user to select their state of residence. Since manually inputting (hardcoding) the list of states in the country would be tedious and unnecessary, I tried using the django_countries package. I have successfully installed the package using pip install django-countries it comes up in my list of installed packages in my Django project. I added it to my list of installed apps in my settings.py - INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ecommerce', 'accounts', 'cart', 'social_django', 'social_core', 'anymail', 'django_countries' ] So everything seems right, and at the top of my views.py, after all other imports I have - from django_countries import countries this is my views funtion that needs the import - def address_book_create(request): user = request.user # Get the logged-in user personal_details = user.personal_details # Add 'COUNTRIES' to the context dictionary context = { 'user': user, 'personal_details': personal_details, 'COUNTRIES': countries, # Include the country data } return render(request, 'accounts/address_book_create.html', context) So the line from django_countries import countries is being underlined in my Pycharm with the words "Unresolved reference 'django_countries'" I don't know why.the error is being shown because i …