Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django error - InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency userauth.0001_initial
hello i get this error when i run the command below: python manage.py migrate what should I do? I comment the 'django.contrib.admin', but I get another error =) : RuntimeError: Model class django.contrib.admin.models.LogEntry doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. what should I do with this issue? -
Django REST API Error: FOREIGN KEY constraint failed
In my django api, am able to successfully create admin users as well as normal users. This is the code for my models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, phone, password=None, **extra_fields): if not phone: raise ValueError('The phone field must be set') user = self.model(phone=phone, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', 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_superuser=True.') return self.create_user(phone, password, **extra_fields) class Users(AbstractBaseUser, PermissionsMixin): unique_code = models.TextField() fname = models.TextField() lname = models.TextField() email = models.EmailField(unique=True) phone = models.TextField(unique=True) sex = models.TextField() country = models.TextField() date_of_birth = models.TextField() image = models.TextField(default=None, blank=True, null=True) district = models.TextField() subCounty = models.TextField() village = models.TextField() number_of_dependents = models.TextField() family_information = models.TextField() next_of_kin_name = models.TextField() next_of_kin_has_phone_number = models.IntegerField(default=None, blank=True, null=True) next_of_kin_phone_number = models.TextField(default=None, blank=True, null=True) pwd_type = models.TextField(default=None, blank=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) REQUIRED_FIELDS = ['unique_code', 'fname', 'lname', 'phone'] USERNAME_FIELD = 'email' objects = CustomUserManager() def __str__(self): return self.phone Am using token authentication and this is my code for auth from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.response import … -
Errno 13 Permission denied when uploading files into folder through a Django web app using bitnami and apache
Here's what my permissions look like for inside the apache folder: And for the folder I'm trying to upload the files to: Does my media/images folder need to have the same owner/group as the apache folder for this to work? I'm using the django admin platform to upload files to that folder. -
When I click the button in my form, I expect it to execute this post function in my view, but it doesn't
The form <form action="{% url 'add-coupon' %}" method="post"> {% csrf_token %} <div class="coupon"> <input id="coupon_code" class="input-text" name="coupon" value="" placeholder="ENTER COUPON CODE" type="text"> </div> <button class="tp-btn-h1" type="submit">Apply coupon</button> </form> My Url from django.urls import path from .views import AddToCart, CartItems, AddCoupon urlpatterns = [ path('add-coupon/', AddCoupon.as_view(), name='add-coupon'), ] The Views from django.shortcuts import get_object_or_404, redirect from django.views import generic from django.utils import timezone from datetime import datetime from django.contrib import messages from .carts import Cart from .models import Coupon from app.models import Product class AddCoupon(generic.View): print("I should see two statements below this") def post(self, *args, **kwargs): print("Button Works") print(messages.success(self.request, "Your coupon has been included successfully") When I click the button, I should get all the 3 statements but I only get ( I should see two statements below this ), So the function is not executing and I don't know why. Would appreciate any help. -
What are the primary advantages of using Django's built-in ORM
What are the primary advantages of using Django's built-in ORM (Object-Relational Mapping) compared to writing raw SQL queries in Django web development? Haven't tried anything yet, just asking question. Thanks in advance. -
Import Error: cannot import name 'encodings' from 'psycopg2._psycopg'
I ran into this problem and Google doesn't give an answer... I have: Linux 3.10.0-1160.95.1.el7.x86_64; Django 3.2.6; Python 3.9; psycopg2 2.9.9; nginx/1.14.0; Log: [Wed Nov 15 11:20:13.904181 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] mod_wsgi (pid=63994): Failed to exec Python script file '/home/users/###/###/domains/###/django.wsgi'. [Wed Nov 15 11:20:13.904240 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] mod_wsgi (pid=63994): Exception occurred processing WSGI script '/home/users/###/###/domains/###/django.wsgi'. [Wed Nov 15 11:20:13.906201 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] Traceback (most recent call last): [Wed Nov 15 11:20:13.906243 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] File "/home/users/###/###/###/env/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 25, in <module> [Wed Nov 15 11:20:13.906250 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] import psycopg2 as Database [Wed Nov 15 11:20:13.906261 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] File "/home/users/###/###/###/env/lib/python3.9/site-packages/psycopg2/__init__.py", line 67, in <module> [Wed Nov 15 11:20:13.906267 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] from psycopg2 import extensions as _ext [Wed Nov 15 11:20:13.906276 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] File "/home/users/###/###/###/env/lib/python3.9/site-packages/psycopg2/extensions.py", line 50, in <module> [Wed Nov 15 11:20:13.906281 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] from psycopg2._psycopg import ( # noqa [Wed Nov 15 11:20:13.906301 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] ImportError: cannot import name 'encodings' from 'psycopg2._psycopg' (/home/users/###/###/###/env/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-x86_64-linux-gnu.so) [Wed Nov 15 11:20:13.906315 2023] [wsgi:error] [pid 63994] [client 5.180.19.143:0] [Wed Nov 15 … -
If the function lacks a print statement, it fails to operate correctly
I am using django channels in which I am creating a function that can get data from the database but the problem is when I am using the function with the decorator (@database_sync_to_async) it does not work until I put a print statement with the output result of query in it. other wise it give the error (You cannot call this from an async context - use a thread or sync_to_async.). I am trying to send message to the user. The code is mentioned in which I have highlited the funstion which does not work without print statement. @database_sync_to_async def get_driver_data(self,data): driver = DriverAdditional.objects.get(user_id=data) return driver @database_sync_to_async def **get_driver_location**(self,data): location = CabLocation.objects.get(driver_id=data) **#print(location)** return location async def send_amount(self, text_data): print("send amount") user = self.scope['user'].id print("user",user) driver = await self.get_driver_data(user) message = json.loads(text_data) data = message.get('data') try: location = await self.get_driver_location(driver) print(location) except Exception as e: print(f'error is {e}') # print(data['rider']) await self.channel_layer.group_send( group=data['rider'], message = { 'type': 'echo.message', 'message_type': 'send_amount', 'data': f"{driver} {data['amount']}", } ) The error without print statement is: Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "D:\Najam\June\development\backend\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 218, in get rel_obj … -
UWSGI Why would there be unattended requests . According to the log
I've got the below in my uwsgi log running with Django and Nginx. The req: -/- field i believe is referring to the request count and the total number of requests respectively. They're both incrementing gradually but the gap is not being closed. I'm not sure what this means for my application as it looks like there're unattended requests that will never be attended. I've checked around but still didn't get the right answer to the situation. [pid: 305785|app: 0|req: 418/1873] 99.7.107.127 () {38 vars in 554 bytes} [Tue Nov 14 23:30:43 2023] GET /api/machines/endpoint/ => generated 385 bytes in 10 msecs (HTTP/1.1 200) 7 headers in 215 bytes (1 switches on core 0) [pid: 305785|app: 0|req: 419/1874] 99.7.107.127 () {38 vars in 562 bytes} [Tue Nov 14 23:30:43 2023] GET /api/machines/endpoint/ => generated 545 bytes in 40 msecs (HTTP/1.1 200) 7 headers in 215 bytes (1 switches on core 0) I'm expecting there'd be so little gap between the request count and the total number requests. I should also mention that this persists even after restarting the service itself. Perhaps some explanation on this behavior would clear my confusions . -
How to use the django-filer file selector in a rich text editor?
Django filer is a great remote image file resource manager. I want to modify all projects to django filer to manage server image resources, but I don't know how to choose to use the django filer file selector from a rich text editor? After consulting a lot of materials, I couldn't find a case where a rich text editor can perfectly integrate with django filer. Is it possible that the django filer file selector cannot be used in conjunction with a rich text editor? -
Bulk_create django
Is there a way to dynamically keep progress of the number of instances saved in the database when using bulk_create in django def bulk_create( self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None, ): -
Error loading ASGI app. Could not import module "ChatApp.asgi".(Render..com)
Source code link : https://github.com/ab-h-i-n/ChatApp_Django The app is working perfectly and loading websockets in localhost. But when i try to deploy it on render.com it showing this error in log. ` Nov 15 10:38:07 AM WARNING: You are using pip version 20.1.1; however, version 23.3.1 is available. Nov 15 10:43:46 AM WARNING: You are using pip version 20.1.1; however, version 23.3.1 is available. Nov 15 10:43:46 AM You should consider upgrading via the '/opt/render/project/src/.venv/bin/python -m pip install --upgrade pip' command. Nov 15 10:43:48 AM ==> Uploading build... Nov 15 10:43:57 AM ==> Build uploaded in 8s Nov 15 10:43:57 AM ==> Build successful 🎉 Nov 15 10:44:00 AM ==> Deploying... Nov 15 10:44:19 AM ==> Using Node version 14.17.0 (default) Nov 15 10:44:19 AM ==> Docs on specifying a Node version: https://render.com/docs/node-version Nov 15 10:44:24 AM ==> Running 'uvicorn ChatApp.asgi:application' Nov 15 10:44:26 AM ERROR: Error loading ASGI app. Could not import module "ChatApp.asgi". my settings.py is : https://github.com/ab-h-i-n/ChatApp_Django/blob/main/ChatApp/ChatApp/settings.py How do i deploy a Django chat app with websocket and channel. or how do i fix this error -
How to build a robust payment subscription pipeline? [closed]
I am building a subscription-based product in Django. The payment processor in this case is Razorpay. I have few doubts regarding the architecture that I have thought. Business Logic: The user subscribes to my platform and a subscription ID is created. I store it in my DB. Each month an automated job needs to adjust the subscription amount for all the subscribed users based on their usage because it's a usage- based model. Proposed Architecture: After researching a bit I wish to use Celery and RabbitMQ. I am already using RabbitMQ for a different service so planning to reuse it. So after the application is deployed, I start the celery worker. A couple of doubts that I have are, Can I add the command to start the Celery worker be a part of the deployment script? The deployment script spins up a bunch of docker containers for different services. Is this a good approach or is there a better way? My biggest concern is what if the job fails? Like what's the best error-handling strategy? I would appreciate any further suggestions on this architecture greatly. -
order queryset by total sum of prices in drf
I use OrderingFilter, i have pizza model connect to pizzaprice model by many to many field, when i ordering by desc or asc i get not the result expected, how can get queryset ordering by sum of prices or first number in prices models.py class Categorie(models.Model): name = models.CharField(max_length=60, default=[0]) def __str__(self) -> str: return self.name class PizzaPrice(models.Model): price = models.DecimalField(max_digits=8, decimal_places=2) def __str__(self) -> str: return str(self.price) class Meta: ordering = ['price'] class PizzaSize(models.Model): size = models.IntegerField() class Meta: ordering = ['size'] def __str__(self) -> str: return str(self.size) class Pizza(models.Model): name = models.CharField(max_length=60) imageUrl = models.CharField(max_length=150) category = models.ForeignKey(Categorie, default=1, on_delete=models.CASCADE) rating = models.IntegerField(choices=PIZZA_RATING, default=1) sizes = models.ManyToManyField(PizzaSize, blank=True, default=[0]) prices = models.ManyToManyField(PizzaPrice, blank=True, default=[0]) def __str__(self) -> str: return self.name serializer.py class PizzaSerializer(serializers.ModelSerializer): category = serializers.CharField(source='category.name') sizes = serializers.SlugRelatedField(many=True, read_only=True, slug_field='size') prices = serializers.SlugRelatedField(many=True, read_only=True, slug_field='price') class Meta: model = Pizza fields = '__all__' views.py class PizzasList(generics.ListAPIView): queryset = Pizza.objects.all() serializer_class = PizzaSerializer pagination_class = PageNumberPagination filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_fields = ['category'] ordering_fields = ['rating', 'name', 'prices'] example of result: ordering by prices I tried many options but nothing helped I started learning Django not very long ago and I don’t know much, I hope you can … -
Djang views and urls connect
-App folder views.py codes. from django.shortcuts import render from django.http import HttpResponse # Create your views here. def MyApp(request): return HttpResponse("HELLO APP") -App folder urls.py codes. from django.urls import path from . import views urlpatterns = [ path('MyApp/', views.MyApp, name='MyApp'), ] -Project folder urls.py codes. from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', include('MyApp.urls')), path("admin/", admin.site.urls), ] http://127.0.0.1:8000 Error. Using the URLconf defined in FirstProject.urls, Django tried these URL patterns, in this order: MyApp/ [name='MyApp'] admin/ The empty path didn’t match any of these. -
Connect Django to MSSQL 2022
i am trying to connect sql server with django using mssql This is the config in settings.py ` DATABASES = { 'default':{ 'ENGINE':'mssql', # Must be "mssql" 'NAME':'WEB', # DB name "test" 'HOST':'localhost\SQLEXPRESS', # <server>\<instance> 'PORT':'', # Keep it blank 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, } } ` and getting this error when makemigrations RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF]. (-1) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (-1)') hope you guy help me, thanks for reading -
Queries too slow on PostegreSQL
I'm currently working on a project, using Django for web development and PostgreSQL as a database. I have noticed that queries on my system are starting to slow down as the amount of data increases. My main table, say Products, has millions of records, and simple queries like product listing are taking longer than I would like. I've already added some indexes to the relevant columns, but I still feel there's room for improvement. Here is my models: class Produto(models.Model): nome = models.CharField(max_length=255) descricao = models.TextField() preco = models.DecimalField(max_digits=10, decimal_places=2) estoque = models.IntegerField() class Pedido(models.Model): produtos = models.ManyToManyField(Produto) data_pedido = models.DateTimeField(auto_now_add=True) And this is the query I'm doing: produtos = Produto.objects.filter(estoque__gt=0).order_by('-preco')[:10] What am I doing wrong? How can I optimize this query? -
images Not Loading in xhtml2pdf with medial_url, Any Solutions? django
I'm encountering a peculiar issue in my Django project involving xhtml2pdf. When I attempt to generate a PDF using xhtml2pdf, the images, which load correctly when viewing the Django page, fail to display in the generated PDF. in my setting: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' my models classReserva(models.model): ImagenCarnet = models.ImageField(upload_to='images/', default='App/carnets/example.jpg') my views.py def DescargarReserva(request, id): reservas =Reserva.objects.filter(idSolicitud=id) Orden=Reserva() data={'reservas':reservas, 'Orden':Orden} pdf_response=genpdf('templatesApp/pdf.html', data) if pdf_response: response = HttpResponse(pdf_response, content_type='application/pdf') #agrecar variable con id como nombre de archivo quizas se usa {} response['Content-Disposition'] = 'attachment; filename="reserva.pdf"' return response return HttpResponse("Error al generar el PDF", status=500) in my template <img src="{{reserva.ImagenCarnet.url}}" style="max-width: 300px; max-height: 200px;" /> I've tried using {{ MEDIA_URL }}{{ reserva.ImagenCarnet.url }}, but it doesn't seem to resolve the issue. The images load correctly when accessing the Django page, but in the PDF generated by xhtml2pdf, they are not displayed. Here are the images illustrating the problem: image in django In djago load correctly with xhtml2pdf does not load correctly src from file Directly from the file (for reference): I'm seeking guidance on how to resolve this discrepancy between image loading in Django and xhtml2pdf. Any insights or suggestions would be greatly appreciated. Feel free to add … -
Django queryset.filter issue with model type pgfields.ArrayField(models.DateField())
I'm trying to filter a queryset by a date range, on the model it is pgfields.ArrayField(models.DateField()) it is stored in the actual table as text[] (ide). This is the specific piece of code that is failing triage_dates = [r.strftime('%Y-%m-%d') for r in list(rrule.rrule( rrule.DAILY, dtstart=parser.parse(range_start), until=parser.parse(range_end) ))] queryset = queryset.filter(triage_dates__overlap=triage_dates) when I print the type of each item in the triage dates list, it is str, I'm getting this error on the query django.db.utils.ProgrammingError: operator does not exist: text[] && date[]. HINT: No operator matches the given name and argument types. You might need to add explicit type casts. I've even tried converting each item to a date as well. I've been all over different AI platforms looking for answers. I'm thinking I might have to convert this over to a plainsql setup but would prefer to use the ORM if possible. I'm wondering if this is some weird bug between a postgres version + django or something. Any insight is welcomed, thank you! -
How to make delay tasks using Zappa with Django?
I am new to Zappa and I have usually used Django with celery in a server. I know that with Zappa I can schedule tasks with a rate, but how can I just execute a task delayed by a desired amount of time that does not have to be periodic? For example, give the user a finite time to buy a product, or to write a review, or to choose spots in a theater... I am also using AWS What I have read is to create a periodic event that executes every minute to check if the desired time have passed and then do the task, but I think that would be overkilling and I would prefer an event driven solution. I simply dont know if that is possible Another option was to create an SQS queue as this: "events": [ { "function": "your_module.process_messages", "event_source": { "arn": "arn:aws:sqs:us-east-1:12341234:your-queue-name-arn", "batch_size": 10, // Max: 10. Use 1 to trigger immediate processing "enabled": true // Default is false } } ] But I dont know how to put arguments, and just call one task I need without having one queue per function. Thanks and sorry if this is a fool question!!! -
How can I avoid re-triggering a django signal?
I have this signal and I want it to not run once it has already checked each instance once, currently it falls into an infinite recursion loop since it triggers itself each time it runs. from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from app.models import ( QuestionForm, Question, ) @receiver(post_save, sender=form) def get_max_score( sender: form, instance: form, **kwargs: dict, ) -> None: forms = form.objects.all() for form in forms.iterator(): total = 0 questions = form.questions.all() for item in questions.iterator(): total += item.points form.set_score(total) form.save() Any help is appreciated, bonus points if the answer is less complex than n^2. Edit: this is the form model itself: class QuestionForm(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) questions = models.ManyToManyField( Question, related_name='questions' ) created_at = models.DateTimeField( auto_now_add=True, editable=False, ) updated_at = models.DateTimeField( auto_now=True, editable=False, ) max_score = models.IntegerField( default=0, ) def __str__(self): return self.name def get_score(self): return self.max_score def set_score(self, score): self.max_score = score -
Django base.html block overwriting
I want to define, and append to blocks defined in the base.html template. Say I have the following template <!DOCTYPE html> <html> <head> <title>My Project</title> {% block append_to_me %}{% endblock %} </head> <body> {% block content %}{% endblock content %} </body> </html> I would then use the following template for my views, my views render some wagtail components, and those components might want to use the append_to_me block. This goes not only for the wagtail blocks, but also for plain django template tags {% extends "base.html" %} {% block content %} <h2>Content for My App</h2> <p>Stuff etc etc.</p> {# I want it to not matter where I use this. #} {% my_custom_tag %} {% endblock content %} Where {% my_custom_tag %} would do something like this: @register.simple_tag(takes_context=True) def my_custom_tag(context): objects = Preload.objects.all() for object in objects: append_to_header_block(object.html) Wagtail block example: class MyBlock(blocks.StructBlock): title = blocks.CharBlock() content = blocks.RichTextBlock() class Meta: template = 'myapp/myblock.html' myapp/myblock.html {% add_to_header IMG "img/my-img.jpeg" %} ... I also want to be able to keep the content of previous calls to the add_to_header function, as to not overwrite the previous content. I just cannot figure out how I would implement this, because there are a few issues: … -
How can properly verify a user is 18 or older in django?
I want to validate whether a user's age (birth_date) is 18+, this is my current code though it isn't working: ... def min_date(): return (date.today() - timedelta(days=6570)) class User(BaseModel, RemovabledModel, AbstractUser): birth_date = models.DateField( verbose_name=_('birth date'), help_text=_('Birth date'), null=True, blank=True, validators=[ MinValueValidator( limit_value=min_date(), message=("User must be 18 or older") ), ] ) This runs and is functional, but I can still set a user's age to today's date without the application throwing any error message like it would with other validators. Edit: In case it is relevant, this is related validator: def min_date(): return (date.today() - timedelta(days=6570)) class SignUpSerializer(serializers.Serializer): birth_date = serializers.DateField( write_only=True, required=True, validators=[ MinValueValidator( limit_value=min_date(), message=("User must be 18 or older") ), ] ) -
I am trying to install python-saml. It is throwing build dependencies error. It does not give specific reason why it is failing
Traceback (most recent call last): File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\cli\base_command.py", line 180, in exc_logging_wrapper status = run_func(*args) ^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\cli\req_command.py", line 245, in wrapper return func(self, options, args) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\commands\install.py", line 377, in run requirement_set = resolver.resolve( ^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 95, in resolve result = self._result = resolver.resolve( ^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 546, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 397, in resolve self._add_to_criteria(self.state.criteria, r, parent=None) File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 173, in _add_to_criteria if not criterion.candidates: ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_vendor\resolvelib\structs.py", line 156, in __bool__ return bool(self._sequence) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 155, in __bool__ return any(self) ^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 143, in <genexpr> return (c for c in iterator if id(c) not in self._incompatible_ids) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 44, in _iter_built for version, func in infos: File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 284, in iter_index_candidate_infos result = self._finder.find_best_candidate( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\package_finder.py", line 890, in find_best_candidate candidates = self.find_all_candidates(project_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\package_finder.py", line 831, in find_all_candidates page_candidates = list(page_candidates_it) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\sources.py", line 134, in page_candidates yield from self._candidates_from_page(self._link) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\package_finder.py", line 791, in process_project_url index_response = self._link_collector.fetch_response(project_url) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\collector.py", line 461, in fetch_response return _get_index_content(location, session=self.session) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\collector.py", line 364, in _get_index_content resp = _get_simple_response(url, session=session) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\collector.py", line 135, … -
Django Tables2 with TemplateColumn the View is not printing the request
I'm trying to print the request in my view but nothing happens when I click on the 'Editar' button (TemplateColumn), this is what I have in my code: tables.py import django_tables2 as tables from django_tables2 import TemplateColumn from .models import Vencimientos, LogAsistencia class VencimientosTable(tables.Table): asistencia = TemplateColumn( '<a class="btn btn btn-info btn-sm" href="{% url "checkin" record.id %}">Editar</a>') class Meta: model = Vencimientos template_name = "django_tables2/bootstrap5.html" fields = ("cliente","vencimiento","activo" ) attrs = {"class": "table table-hover table-sm"} urls.py urlpatterns = [ .... path('asistencia/<int:pk>/', CheckIn.as_view(), name='checkin') ] views.py class CheckIn(View): def get(self, request): print(request) return redirect ('asistencia') when I click on the "Editar" button in the table the idea is to get the record.id so I can add some extra code, but the button doesn´t do anything UPDATE I inspect the button and I see the link correct: The button doesn´t do anything still -
Django ORM ForeignKey queryset output using annotations
I have the following 3 django models (using some abstractions): class Person(models.Model): full_name = models.CharField(max_length=120, validators=[MinLengthValidator(2)]) birth_date = models.DateField(default='1900-01-01') nationality = models.CharField(max_length=50, default='Unknown') class Meta: abstract = True class Director(Person): years_of_experience = models.SmallIntegerField(validators=[MinValueValidator(0)], default=0) objects = DirectorManager() class Actor(Person): is_awarded = models.BooleanField(default=False) last_updated = models.DateTimeField(auto_now=True) class Movie(models.Model): MOVIE_GENRES = ( ('Action', 'Action'), ('Comedy', 'Comedy'), ('Drama', 'Drama'), ('Other', 'Other') ) title = models.CharField(max_length=150, validators=[MinLengthValidator(5)]) genre = models.CharField(max_length=6, choices=MOVIE_GENRES, default='Other') rating = models.DecimalField(max_digits=3, decimal_places=1, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], default=0) director = models.ForeignKey(Director, on_delete=models.CASCADE) starring_actor = models.ForeignKey(Actor, on_delete=models.SET_NULL, blank=True, null=True) actors = models.ManyToManyField(Actor, related_name="actors") As you can see in the code above, I have also 1 manager. Here it is: class DirectorManager(models.Manager): def get_directors_by_movies_count(self): return self.all().values("full_name").annotate(movies_num=Count("movie__director")).order_by("-movies_num", "full_name") And here is my problem. I need and output like this: <QuerySet [<Director: Francis Ford Coppola>, <Director: Akira Kurosawa>...> instead, I am receiving this: <QuerySet [{'full_name': 'Francis Ford Coppola', 'movies_num': 2}, {'full_name': 'Akira Kurosawa', 'movies_num': 1}...]> So, I need just one record: Director, not these 2 full_name and movies_num, but i want to preserve the same group and order logic. How to do this?