Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to retrive data from database in Django
I'm new to django. I am trying to obtain data from a profile page that I've created which exists in a app called users and I am trying to use the data in a HTML file called home that exists in an app called blog within in a templates directory within a blog directory This is how my users\model.py file looks like class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default='default.jpg', upload_to="profile_pics") height = models.PositiveIntegerField( null=True, blank=True) weight = models.PositiveIntegerField( null=True, blank=True) age = models.PositiveIntegerField( null=True, blank=True) def __str__(self): return f'{self.user.username} Profile' def save(self,*args,**kwargs): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width >300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) This is how my users\views.py file looks like def profile(request): u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated successfully!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) profile_instance = request.user.profile context = { 'u_form': u_form, 'p_form': p_form, 'height': profile_instance.height, 'weight': profile_instance.weight, 'age': profile_instance.age, } return render(request,'users/profile.html',context) Just to be sure that my Profile Page works, I checked the admin page, and it shows the data in the profile section. This is how my blog\views.py … -
Media Exposure Vulnerability
Currently, we have a configuration in Django to serve media files (these are the files uploaded by users in the system). We have a URL for this where we capture all the files in the media directory and redirect them to the serve_media view. re_path(r"^media/(?P<path>.*)$", cms.views.serve_media), This is the serve_media view: def serve_media(request, path=""): if request.user.is_authenticated: user = request.user else: return redirect("/%s?next=%s" % (settings.LOGIN_URL, "/media/" + path)) usuario = Usuario.objects.get(usuario=user) # Search for the file by its path in the media folder and check if the user # has permission to access it allowed_to_serve = False try: arquivo = Arquivo.objects.get(arquivo__contains=path) # Public image of a project on the website for projeto in Projeto.objects.exclude(id_imagem_publica=None): if projeto.arquivo_in_id_imagem_publica(arquivo.id) is True: allowed_to_serve = True break if user == arquivo.criado_por or usuario.permissao == Usuario.SUPER: allowed_to_serve = True # Entidade file if arquivo.entidade is not None and allowed_to_serve is False: if ( usuario.permissao == Usuario.ENTIDADE and user == arquivo.entidade.usuario.usuario ): allowed_to_serve = True elif ( usuario.permissao == Usuario.AGENCIA and arquivo.entidade.projeto_set.all() .filter(cidade_atuacao=usuario.cidade_atuacao) .count() > 0 ): allowed_to_serve = True # Projeto file if arquivo.projeto is not None and allowed_to_serve is False: if ( usuario.permissao == Usuario.ENTIDADE and user == arquivo.projeto.entidade.usuario.usuario ): allowed_to_serve = True elif ( usuario.permissao … -
VS Code (Python) uses wrong version of Python interpreter even after activation virtual env (Poetry)
I have two Python interpreters on my machine (3.11.6 and 3.12). My project runs with Poetry venv (3.11.6). Whenever I open a project the status bar indicates correct venv like 3.11.6("project-fd1143fd-py3.11":Poetry). When I run a project (Django) I get an import error says there is no Django package installed. I suspect there is no actual activation of venv. When I enter command python --version I always get Python 3.12.0 (tags/v3.12.0:0fb18b0, Oct 2 2023, 13:03:39) There is no any indication of activated venv near the command line (do it has to be there as I remember). The Poetry venv itself works fine as I use it in PyCharm without any issues. -
Django Auth Query
I have a django backend project for e-commerce site where I have created authentication class which is used by all the view classes for incoming requests. In one of the classes I have get_queryset, put and post functions overridden. I want the authentication class to be applied for both put and post functions but not to get_queryset. following are the code snippets, Authentication Class class JWTAuthentication(BaseAuthentication): def authenticate(self, request): print('authenticating') auth = get_authorization_header(request).split() print(auth) if auth and len(auth) == 2: token = auth[1].decode('utf-8') print('Decoded Token') print(token) id = decode_access_token(token) print(id) print(id) customer = models.Customer.objects.get(id=id) return (customer, None) raise exceptions.AuthenticationFailed('unauthenticated2') Product View class class ProductList(generics.ListCreateAPIView): ... authentication_classes = [ JWTAuthentication ] ... def get_queryset(self): ... def post(self, request): ... def put... Is there a way just to apply the authentication on put and post function but not on get_queryset function? -
Authentication logout
error screenguys i have a big problem. Now im working for tweet website with python django. Authentication steps are good runnig but logout is dont working please help me guys.... my base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <title>Tweet App</title> <link rel="stylesheet" href="{% static 'tweetapp/customform.css' %}"> </head> <body> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'tweetapp:listtweet' %}">Tweet App</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav me-auto mb-2 mb-md-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'tweetapp:listtweet' %}">List</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'tweetapp:addtweet' %}">Add Tweet</a> </li> <!-- <li class="nav-item"> <a class="nav-link" href="{% url 'tweetapp:addtweetbyform' %}">Add Tweet By Form</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'tweetapp:addtweetbymodelform' %}">Add Tweet By Model Form</a> </li> --> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}?next=/">Logout</a> </li> </ul> </div> </div> </nav> {%block content%} {%endblock%} </body> </html> my urls.py """ URL configuration for djangotweet project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/5.0/topics/http/urls/ Examples: Function … -
"invalid_client" Error in Django OAuth Toolkit Despite Following Documentation
I'm encountering an "invalid_client" error when attempting to obtain an OAuth token using Django OAuth Toolkit. I've been meticulously following the official documentation (https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html#step-4-get-your-token-and-use-your-api) but am unable to resolve the issue. Error Details: Error Response: {"error": "invalid_client"} Server Log: Unauthorized: /o/token/ [11/Jan/2024 20:13:37] "POST /o/token/ HTTP/1.1" 401 27 Steps Taken: Repeated Documentation Steps: I've carefully followed the documentation's instructions from scratch multiple times. Verified Credentials: I've double-checked the client ID, client secret, username, and password for accuracy and typos. Inspected Request Details: I've examined the cURL command and request details to ensure they align with the server's expectations. Specific Context: OAuth Server/Library: Django OAuth Toolkit Relevant Code Snippet: Bash curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/ Request for Assistance: I'm kindly seeking guidance on potential causes and troubleshooting steps. Specific Questions: Common Pitfalls: Are there any common mistakes or configuration issues that might lead to this error in Django OAuth Toolkit? Troubleshooting Suggestions: What additional diagnostic steps can I take to pinpoint the root cause? Server-Side Considerations: Are there any server-side settings or logs I should examine? Any insights or assistance would be greatly appreciated. -
IntegrityError FOREIGN KEY constraint failed
I am trying to add a new "Eveniment" through the admin page in my app, but I get the error from the title and I don't know how to solve the issue. Only and "Utilizator" who has the "Organizator" role should be able to add one. class Utilizator(AbstractUser): ORGANIZATOR=1 CUMPARATOR=2 data_inregistrare = models.DateTimeField(auto_now_add=True) ROLE_CHOICES =( (ORGANIZATOR, 'Organizator'), (CUMPARATOR, 'Cumparator'), ) role=models.PositiveSmallIntegerField(choices=ROLE_CHOICES,blank=True,null=True) evenimente=models.ManyToManyField(to='Eveniment', blank=True) groups = models.ManyToManyField( 'auth.Group', related_name='utilizatori', verbose_name='groups', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_query_name='user', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='utilizatori', verbose_name='user permissions', blank=True, help_text='Specific permissions for this user.', related_query_name='user', ) def to_dict(self): return{ 'id': self.id, 'data_inregistrare': self.data_inregistrare, 'role': self.role, } class Eveniment(models.Model): nume = models.CharField(max_length=255) data = models.DateField() locatie = models.CharField(max_length=255) descriere = models.TextField() organizator = models.ForeignKey(Utilizator, on_delete=models.CASCADE, related_name='evenimente_organizate', null=True) def __str__(self): return self.nume def to_dict(self): organizator_id = self.organizator.id if self.organizator else None return{ 'id': self.id, 'nume': self.nume, 'data': self.data, 'locatie': self.locatie, 'descriere': self.descriere, 'organizator': self.organizator.id, } For now, I am just trying to add a new "Eveniment" through the admin page, but the error keeps showing up no matter the changes I've made. -
django sender to django receiver api data exchange
I have built two web applications, django_one and django_two. I would like django_one to send data (From a web form) to django_two via RESTful_framework api any other method. Please guide me on how to go about this. -
The database needs something to populate existing rows...but the table doesn't exist yet and there are no rows
I'm getting this running python3 manage.py makemigrations You are trying to add the field 'created_at' with 'auto_now_add=True' to sitemetadata without a default; the database needs something to populate existing rows. But the table doesn't exist yet, and there are no rows. How can I use makemigrations here properly? -
Hello, I wrote the program so that the user enters the form, then it is authenticated, then it is logged in, but it says failure. Can you guide me?
class Register(View): def get(self, request: HttpRequest): register_form = RegisterForm() context = {'register_forms': register_form} return render(request, "register.html", context) def post(self, request: HttpRequest): register_form = RegisterForm(request.POST) if register_form.is_valid(): email = register_form.cleaned_data['email'] username = register_form.cleaned_data['username'] if RegisterModel.objects.filter(email__iexact=email).first(): messages.error(request, "The email has already been found") elif RegisterModel.objects.filter(username__iexact=username).first(): messages.error(request, "The username has already been found") else: # new_user = register_form.save(commit=False) # new_user.is_active = get_random_string(72) register_form.save() print("", tag="success", tag_color="green", color="yellow") # Authentication the user username = register_form.cleaned_data['username'] password = register_form.cleaned_data['password'] user = authenticate(username=username, password=password) if user: login(request, user) time.sleep(2) messages.success(request, "Successfully registered and logged in!") print(register_form.cleaned_data, tag="success",tag_color="green", color="yellow") else: messages.error(request, "Invalid username or password. Please try again.") context = {'register_forms': register_form} return render(request, "register.html", context) Authenticate successfully -
Django not writing to database but print statements are working and updated
I am using Django as my Web framework. The relevant function is def addWeight(request): if request.method == "GET": form = weightForm() return render(request, "base/weight.html", {"form": form}) if request.method == "POST": try: form = weightForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest("Error with your form") data = form.cleaned_data day = macro_day.objects.get_or_create(owner=request.user, date=data["date"]) print(data["weight"]) day[0].weight = data["weight"] print(day[0]) print(day[0].weight) return HttpResponse(status=204)` <form action="weight" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="SUBMIT"> </form> The form object is: class weightForm(forms.Form): date = forms.DateField(label="Date") weight = forms.IntegerField(label="Weight", min_value=0, max_value=500) day[0].weight reflects the value sent into the function by the webform but when I actually go into my database or call the object it appears that the change hasn't been made. I have another function implemented like this and I don't seem to have the same issue with it. What am I doing wrong? -
Django: While Button Pressed
I am currently working on a control for a camera (visca-over-ip) having 4 buttons that control in which direction the camera should turn. Currently I am in the testing phase and now need these 4 Buttons to set a variable in django to TRUE if the Button is held. If it was let go something else should happen. It should be something Like: index.html: <button>Left</button> camera.py button_pressed = (Code that checks if button is held down) def button_hold(): while button_pressed == True: (do something) -
Deploying django project on a 2019 windows server virtual machine (offline)
I've been working on a Django project for a while, and after completing it, I want to deploy it so my colleagues can work with it. I have a virtual machine (Windows Server 2019) that doesn't have internet connection. I copied my Django project there, but the first problem I faced was with the Python packages. Since my project has its own virtual environment, I assumed that by copying the project, everything would work. However, I had to reinstall all the packages offline using the wheel files. This has made me question the purpose of the virtual environment. I also intend to deploy it using an Apache server. When deploying a Django project with Apache, I need the mod_wsgi package. However, when I tried installing it, I encountered this error, even though I have already installed Visual Studio C++ Build Tools 14 : building 'mod_wsgi.server.mod_wsgi' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mod_wsgi Running setup.py clean for mod_wsgi Failed to build mod_wsgi ERROR: Could not build … -
Django - Downloading a file to local downloads folder
In Django, I am trying to download an entire album into local "downloads" default folder on the client's PC. but how do I specify the target folder? currently, my code doesn't nothing. from views.py: def download_file(lfile): uploaded_file = lfile response = HttpResponse(uploaded_file.image, content_type='application/force-download') response['Content-Disposition'] = f'attachment; filename="{lfile.fname}"' return response def download_album(request, albumpk, albumowner): album = Category.objects.filter(id=albumpk) lfiles = Photo.objects.filter(category=albumpk) for lfile in lfiles: dfile = download_file(lfile) return redirect('albumlist', albumowner) -
Subtract two date fields using computed twig in Drupal 10
Would be grateful for some assistance on this. I am building a webform using the webforms module in Drupal 10 and I want to subtract two date fields and as a result display the difference between the dates. For example, {{ 2024-01-11 - 2024-01-10 }} = {TheDifferenceInDays}. Thanks I have tried using the following expression in my computed twig field however this is returning a value of 0 - is that because the date fields need to be in a specific format? {{ date1 - date2 }} -
Pagination does not work when i use generil.ListView class in Django
I want to create pagination in Django for order list. It seems everything is coded correctly but for some reason when i get to webpage, instead of links to other pages it shows 'Page of . ' Apologies for formatting of this post as it's my first time posting a question and note that there are 7 objects of order, therefore there should be a page. My code looks like this: models.py class Order(models.Model): date = models.DateField('Date', null=True, blank=True) car = models.ForeignKey(Car, on_delete=models.SET_NULL, null=True) ORDER_STATUS = ( ('p', 'Processing'), ('o', 'Ordered'), ('s', 'In service'), ('c', 'Completed'), ('t', 'Taken back by customer') ) status = models.CharField(max_length=1, choices=ORDER_STATUS, blank=True, default='p') @property def order_total_price(self): order_rows = self.order_row.all() total_price = sum(row.total_price for row in order_rows) return round(total_price) @property def order_rows(self): return ', '.join(str(el) for el in self.order_row.all()) def __str__(self): return f'{self.car}' views.py class OrderListView(generic.ListView): model = Order context_object_name = "orders" template_name = "orders.html" paginate_by = 5 urls.py from django.urls import path, include from . import views urlpatterns = [ path('index/', views.index, name="index"), path('cars/', views.cars, name='cars'), path('car/<int:pk>/', views.car_detail, name='car_detail'), path('orders/', views.OrderListView.as_view(), name='orders'), path('order/<int:order_id>/', views.order_detail, name='order_detail'), path('search/', views.search_results, name='search_results'), path('', views.index, name='index'), ] and orders.html {% extends 'base.html' %} {% block header %}Orders{% endblock %} {% … -
Random Not Found</h1><p>The requested resource was not found on this server.</p>
I'm experiencing an issue which seems to be related somehow to Gunicorn + Django and I can't find the cause of the problem. I start Gunicorn using this command: gunicorn config.wsgi --bind=0.0.0.0:5000 --timeout=300 --workers=2 --threads=4 --worker-class=gthread --name=api --log-level debug --error-logfile gunicorn_error.log --access-logfile - --capture-output and then while trying to curl for example CSS file : curl http://0.0.0.0:5000/STATIC_DIR/CSS/FILE.css?v23423424 sometimes I get the correct response and CSS file but sometimes: <h1>Not Found</h1><p>The requested resource was not found on this server.</p> interestingly, if, for example, I kill 2 of the 3 gunicorn processes, they will start again in a moment and then everything will work properly. I can't find anything in the logs which can indicate the reason. Has anyone encountered a similar problem? enable DEBUG log try different types of worker-class -
Rendering data on the same template from different models
I want to render data on the same template(shared template) from different models I have the following models in models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): """ Custom user model to support role-based authentication. """ USER_TYPE_CHOICES = [ ('client', 'Client'), ('staff', 'Staff'), ('admin', 'Admin'), ] user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES, default='client') phone = models.CharField(max_length=15, blank=True, null=True) email = models.EmailField(unique=True) address = models.CharField(max_length=255, blank=True, null=True) # Specify unique related_name for groups and user_permissions user_groups = models.ManyToManyField( 'auth.Group', related_name='custom_user_groups', blank=True, verbose_name='groups', help_text='The groups this user belongs to.', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='custom_user_permissions', blank=True, verbose_name='user permissions', help_text='Specific permissions for this user.', ) def get_user_type_display(self): """ Display the user type in a more readable format. """ return dict(CustomUser.USER_TYPE_CHOICES)[self.user_type] class Meta: swappable = 'AUTH_USER_MODEL' class GarbageCollectionRequest(models.Model): """ Represents a request for garbage collection made by a client. """ client = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='garbage_requests') request_date = models.DateTimeField(auto_now_add=True) request_details = models.TextField(max_length=255) address = models.CharField(max_length=255) phone = models.CharField(max_length=15, blank=True, null=True) email = models.EmailField() is_assigned = models.BooleanField(default=False) collection_date = models.DateTimeField(blank=True, null=True) def __str__(self): return f"Request #{self.pk} - {self.client.username} - {self.address}" And my class-based views.py from django.shortcuts import render, redirect from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.urls … -
CSRF verification failed. Request aborted. (CSRF token not set while clearly being present)
Yes I added the csrf token to my form, yes I added post method in the form, yes I checked if the server send cookie matches the client side cookie. Als other good context maybe is that I have loginrequiredMixin on my homepage view so it redirects you to the login page when trying to access it but don't think that is the problem. Django is saying the reason is that it can't find the csrf token but I checked what its called in the source code of Django and it matches the key and has a matching value from the one send from the server which is request_csrf_token = request.POST.get("csrfmiddlewaretoken", "") here are the forms I'm using which have inherited Django default sign up and login forms: class LoginForm(AuthenticationForm): def __init__(self, request=None, *args, **kwargs): super(LoginForm, self).__init__(request, *args, **kwargs) self.fields['username'].widget = forms.TextInput(attrs={'class': 'form-control', 'id': 'username'}) self.fields['password'].widget = forms.PasswordInput(attrs={'class': 'form-control'}) self.fields['remember_me'] = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'class': 'custom-control-input', 'id': 'remember-me'}) ) class SignUpForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) username = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': 'form-control'})) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class': 'form-control'})) im losing my shit here, what am I doing wrong? <form method="POST" id="formAuthentication" class="mb-3"> <div class="input-group mb-3"> {{ form.username|attr:"placeholder:Username"|add_class:'form-control' … -
how to rach model from the other model in django?
if i have model called Reaction and it has ForeignKey refers to the other model called User. now i know that i can reach the User model from the Reaction model but i have a list of more that 1000 users came from User model , and i want to reach the ractions of them from the Reaction model. how can i do that without taking each user from User model and get it through Reaction model. these are my models : class User(models.Model): name = models.TextField() class Reaction(models.Model): from_user = models.ForeignKey(User, on_delete=models.PROTECT, default=None, related_name="reaction_from_user") to_user = models.ForeignKey(User, on_delete=models.PROTECT, default=None, related_name="reaction_to_user") date = models.DateField(null=True) time = models.TimeField(null=True) type_of_reaction = models.TextField() have_been_seen = models.BooleanField(default=False , null=True) -
Django telling me an existing template does not exist. | {% include %}
I'm currently trying to point to a template in Django which is not in the directory with which is the calling template is sitting in. This is the relative path which has been copied and pasted here: static\libraries\templates\our-tech-stack.html Root | |---static | | | |--libaries | | | |--templates | | | |--<our-tech-stack.html> |---templates | |--<calling-template.html> This is the include in the <calling-template.html> {% include "../static/libraries/templates/our-tech-stack.html" %} This is the setup in my settings.py `'DIRS': [ . ... ... os.path.join(BASE_DIR, 'static/libraries/templates'), ... ... ... ],` As you can see this has been correctly set up, so why is Django telling me that the template does not exist when it very clearly does? Read office documentation - however, the official documentation is wrong. -
Django manage.py makemigrations: Show differences between model and database
I occasionally run into a problem where manage.py makemigrations will generate migrations that, as far as I can tell, concern models or model fields I didn't touch. Is there any way to find out what differences between the model and the database manage.py makemigrations found, that make it think a migration is needed? I searched the web and checked the django-admin and manage.py documentation but couldn't find a way to make makemigrations "explain itself" or to find differences between my models and database any other way. Any hints would be greatly appreciated :) -
Django posts page not displaying
System check identified no issues (0 silenced). January 11, 2024 - 16:23:58 Django version 5.0, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [11/Jan/2024 16:24:00] "GET /posts/?Category=All HTTP/1.1" 200 9404 [11/Jan/2024 16:24:00] "GET /static/images/MyPic.jpg HTTP/1.1" 304 0 [11/Jan/2024 16:24:00] "GET /static/images/IntroPicture2.png HTTP/1.1" 304 0 [11/Jan/2024 16:24:02] "GET /posts/?Category=All HTTP/1.1" 200 9404 -
"operator does not exist: bigint = bigint[]" Error when I want to use __in lookup agains ArrayAgg field Django
#views.py queryset = User.objects.all() queryset = queryset.annotate( request_ids=ArrayAgg("requests__id") ) unread_messages = Request.objects.filter( pk__in=OuterRef("request_ids") ) queryset = queryset.annotate( unread_messages=Coalesce(Subquery(unread_messages), 0) ) I want to achieve something like this in SQL: WITH user_requests AS ( SELECT uchat_user.username, Array_Agg(uchat_request.id) AS request_ids FROM uchat_user LEFT JOIN uchat_request ON uchat_request.refugee_id = uchat_user.id GROUP BY uchat_user.username ) SELECT *, ( SELECT COUNT(*) FROM uchat_request WHERE uchat_request.id IN (SELECT unnest(user_requests.request_ids)) ) AS total_requests FROM user_requests However I get this error (table might be different but the overall the exception is like this): operator does not exist: bigint = bigint[] LINE 1: ...efugee_id" FROM "uchat_request" U0 HAVING U0."id" IN (ARRAY_... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Could you please help with that? -
My Django App not displaying the right page
System check identified no issues (0 silenced). January 11, 2024 - 16:01:17 Django version 5.0, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [11/Jan/2024 16:01:27] "GET /index/ HTTP/1.1" 200 9404 [11/Jan/2024 16:01:42] "GET /search/ HTTP/1.1" 200 9404 [11/Jan/2024 16:01:50] "GET /posts/?Category=All HTTP/1.1" 200 9404 [11/Jan/2024 16:02:56] "GET /admin HTTP/1.1" 200 9404 [11/Jan/2024 16:03:02] "GET /admin/ HTTP/1.1" 200 9404 [11/Jan/2024 16:03:53] "GET /posts/?Category=All HTTP/1.1" 200 9404 [11/Jan/2024 16:03:59] "GET /posts/?Category=Mythology HTTP/1.1" 200 9404 I am not able to see the Posts Page