Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - When using Easy Thumbnails how to force a field to convert the thumbails to JPG even if PNG with alpha was provided
When using Easy Thumbnails you can globally configure that all images (even PNGs with alpha) are converted to JPG by adding this to your settings.py THUMBNAIL_TRANSPARENCY_EXTENSION = 'jpg' But the problem is that I don't want to force ALL of my images in my application to be converted to JPG because I have some models that require images with alpha (png). I have a model for a blog article where I need the image to ALWAYS be converted to JPG. No matter if people upload PNGs with alpha. class Article(BaseModel): title = models.CharField(max_length=255, unique=True) image = ThumbnailerImageField(upload_to='blog/articles/image') Right now many people are uploading PNG's with alpha enabled (although the image doesn't have any transparency) and this is preventing the Thumbnailer to compress them as JPG making many of the thumbnails 500kb(png) instead of like 70kb(jpg). How can I specify to always convert these article images to JPG? -
In Django, is using exclude() before values() actually better for performance or is it just a myth?
In Django QuerySet, while querying, is it really better to use exclude() before values() in a query? For example: query_obj = TestModel.objects.values().exclude(somefield='somevalue') Is this the right way or, query_obj = TestModel.objects.exclude(somefield='somevalue').values() this one? Or both work the same way? -
Deleting many to many objects in django
I have two models like this: class Toppings(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) class Pizza(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) toppings = models.ManyToManyField(Toppings) I create a pizza and add toppings like this crazy_pizza = Pizza(name = "crazy pizza") crazy pizza.save() toppings = ["pepperoni","chicken","bacon"] for i in toppings: topping = Toppings(name = i) toppings.save() crazy_pizza.add(topping) crazy_pizza.save() now i want to delete all the toppings associated with crazy pizza. I run crazy_pizza.toppings.clear() this removes the many to many reference, how can i also delete all the actual toppings objects themselves? -
strict mime type checking is enabled, refused to execute script from '<url>' its mime type ('application/octet-stream'') is not executable, and
i have a problem when to return a html file through a link which is request from an API using django, like this: enter image description here any sugestion for this problem? thank you if there's no problem it will show the data -
Django dont show pdf from database
Learning Django and want show pdf documents from database on html page. But I have error: Unable to connect to site, ERR_NAME_NOT_RESOLVED. models.py class Certificate(models.Model): title = models.CharField(max_length=30, null=True) pdf = models.FileField(upload_to='pdf') status = models.BooleanField(default=True) class Meta: verbose_name_plural='09. Certificates' views.py def certificates(request): certificates = Certificate.objects.filter(status=True).order_by('-id') return render(request, 'certificates.html', {'certificates': certificates}) certificates.html {% block content %} <main class="container my-4"> <h3 class="my-4 border-bottom pb-1">Сертификаты</h3> <div class="row"> {% for certificate in certificates %} <html> <div class="card shadow"> <h1>{{certificate.title}}</h1> <iframe src="//media/{{pdf.pdf}}" width="100%" height="100%"> </iframe> </div> </html> {% endfor %} </div> </main> {% endblock %} I took information in parts through Google, maybe I missed the important setting, but I can't find a solution? Site is running locally on my computer. -
Possible platform to see real-time database changes on a dashboard
I am doing a website using Django that uses AWS RDS Postgresql as the database. Currently, I want put up the database on a dashboard that I can see live changes of the database from the dashboard without having to run the SQL statement SELECT * FROM xxx within my postgresql script everytime I want to see my database updates. Is there anyway I can do this? Is AWS Kinesis suitable? Or are there any other platforms to recommend? -
How to skip the record that creates 500 error in django api?
I have a serialiser and everything is working fine, but when some record that is not json serialiserable is inserted, it gives 500 error. I want to just skip the record that gives the error and get all the data. Error is: File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Country is not JSON serializable [14/Mar/2023 10:15:49] "GET /api/countries/ HTTP/1.1" 500 142117 -
TemplateDoesNotExist at / base/home.html Error
after given the path error in finding template apps are defined and also all path are clear need no run server -
select_related between three or more models
When using select_related in Django, you can get from A to B to a foreign key, you would write the following A.objects.select_related('B')... What should I write if I am referencing a foreign key from B to C? -
how to manage with new programming or framework version releases
Maybe the question will look like it is related to Django but it is a general question. I learned Django 1 year ago and Django version which i learned was 3.2 and now django updated and the version is 4.2. Django course i bought is using same version that i learned 3.2. My question is should i start learning Django again from scratch bcoz they launched new version or i go through the release notes only ? If yes then one more question. Is in release notes they only tell what is updated and the things which are not updated are not mentioned in the release notes. I go through release notes but i am worried like if all core concepts are changed. So i am looking for a industry exprience developer who can answer my question. -
authenticate function returning none in login api view django
I am building registration,login,logout apis with django rest.Registration works properly.I created a login view to authenticate users based on given username and password but authenticate return none instead of the user object.I am using a non hashed password for simplicity and It doesn't work.I can create users via the register api and they are created in the database and although I give the same credentials to the login api it fails.I printed the username and password inside the function before authenticate to test if they hold their correct values and they do but yet fails to authenticate. views.py @api_view(['POST']) def register(request): userser = SignUpUserSerialzer(data=request.data) if userser.is_valid(): user = userser.save(is_active = False) activateEmail(request, user, userser.validated_data['email']) return Response(userser.data) else: return Response(status=status.HTTP_404_NOT_FOUND) @api_view(['POST']) def custom_login(request): # if request.user.is_authenticated: # return redirect(reverse('home')) username=request.data['username'] password=request.data['password'] print(username) print(password) print('login1') user = authenticate(username=username, password=password) print('login2') print(user) if user is not None: login(request, user) return Response({"user": user.id}) else: return Response("error") serializers.py from rest_framework import serializers from .models import CustomUser class SignUpUserSerialzer(serializers.ModelSerializer): class Meta: model = CustomUser fields = '__all__' models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): email = models.EmailField(unique=True) def __str__(self): return self.username settings.py AUTH_USER_MODEL = 'users.CustomUser' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) REST_FRAMEWORK = … -
SynchronousOnlyOperation with django-channels on query done on urls
On the very first request after the application run, I'm facing the following error. It only happens once and after the first request fails, everything continue to work as usual, so I have no idea what's going on. It happened after I adopted async on my Django application: SynchronousOnlyOperation You cannot call this from an async context - use a thread or sync_to_async. ... line 44, in names_regex for n in names: File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 394, in __iter__ self._fetch_all() File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1866, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 281, in __iter__ for row in compiler.results_iter( File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1346, in results_iter results = self.execute_sql( File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1393, in execute_sql cursor = self.connection.cursor() File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) On my urls.py, I have something like this: router = DefaultRouter() router.register(r'news/' + NewsType.objects.names_regex(), NewsModelViewSet, basename='news') NewsType.objects.name_regex() has the code below (where the error is being triggered): def names_regex(self): names = self.get_queryset().values_list('name', flat=True) regex = r'(?P<newstype>' try: for n in names: regex += r'|{}'.format(n) except ProgrammingError: regex += r'|{}'.format('') regex += r')' return regex I also have this on my routing.py: application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter(apps.simulation.routing.websocket_urlpatterns) ), } ) and this my … -
Django: Getting last sent or received message of each user regarding the current user
I'm using Django 4.0 with PostgreSQL v 14. I can't find a way to get the last sent or received message in my database. My code is: class Message(models.Model): """ A model to represent a message between two users. Fields: message (CharField): The text content of the message with a maximum length of 2000 characters. attachment (FileField): An optional file attachment with the message. The file will be uploaded to the 'attachments/' directory. timestamp (DateTimeField): The date and time the message was sent, automatically set to the current date and time when the message is created. sender (ForeignKey): The sender of the message, a foreign key to the User model with a related name of 'sender'. receiver (ForeignKey): The receiver of the message, a foreign key to the User model with a related name of 'receiver'. Methods: __str__: Returns the text content of the message as a string representation of the model. """ objects = MessageManager() message = models.CharField(max_length=2000) attachment = models.FileField(upload_to='attachments/', blank=True) timestamp = models.DateTimeField(auto_now_add=True) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') deleted = models.BooleanField(default=False) deletedBy = models.ForeignKey(User, on_delete=models.CASCADE, related_name='deletedBy', blank=True, null=True) deletedStamp = models.DateTimeField(null= True)``` I did make the function: def getLastUsers(self, user, nbUsers = … -
Model method isn't returning when called from one HTML template
class Food(models.Model): fdc_id = models.PositiveIntegerField(primary_key=True) def get_absolute_url(self): return reverse('food-detail', args=[str(self.fdc_id)]) models.py from django.urls import path from . import views, urls from django.urls import include urlpatterns = [ path('', views.index, name='index'), path('foods/', views.FoodListView.as_view(), name='foods'), path('foods/<int:pk>', views.FoodDetailView.as_view(), name='food-detail'), ] urlpatterns += [ path('myfoods/',views.FoodsEatenByUser.as_view(), name='my-eaten'), ] urls.py {% extends "base_generic.html" %} {% block content %} <h1>Food List</h1> {% if food_list %} <ul> {% for food in food_list %} <li> <a href="{{ food.get_absolute_url }}">{{ food.name }}</a> ({{food.fdc_id}}) </li> {% endfor %} <ul> {% else %} <p>There are no foods in the database</p> {% endif %} {% endblock %} food_list.html The food_list page appears how I expect it to but the url returned by get_absolute_url is /catalog/foods However, if I enter the url manually it will take me to the detail page for the object, where the method does return the correct url. {% extends 'base_generic.html' %} {% block content %} <h1>Food View</h1> <a href="{{ food.get_absolute_url }}">{{ food.name }}</a> ({{food.fdc_id}}) <p>{{ food.name}}</p> {% for f,v in food.get_fields %} <p> {{ f }}: {{ v }} </p> {% endfor %} {% endblock %} food_detail.html In food_detail, the url returned is /catalog/foods/<fdc_id> Also, the links on the list page did go to the correct detail page at … -
Why is the page I am testing returning a 301 response instead of a 200 response?
I am writing tests for class-based views in the django project I am writing as part of a course. Currently, I am stuck trying trying to test a view that directs to an edit page that requires a user to be logged in. The item being edited must also have been created by that user in the first place, of course. In the test itself, I instantiate a model and a user, and then log the user in, before trying to get the edit page. I expect the response to have a status code of 200, but it keeps coming back as a 301. Code below: urls.py - path for the edit page: path('edit/<slug:slug>/', views.EditBulletin.as_view(), name='edit'), models.py - the model being instantiated: class Bulletin(models.Model): title = models.CharField(max_length=40, unique=True) slug = models.SlugField(max_length=40, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bulletins') content = models.TextField() link = models.URLField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name='bulletin_likes') edited = models.BooleanField(default=False) updated_on = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() views.py - the get method in the view for the edit page: class EditBulletin(View): def get(self, request, slug, *args, **kwargs): queryset = Bulletin.objects.filter(status=1) bulletin = get_object_or_404(queryset, slug=slug, … -
Django field ends up blank after save() AND code that prevents it from reverting to a blank value
A POST request hits one of my django GenericViewSet endpoint that find a matching instance and sets a value on it: obj = models.CarObj.objects.get(id=self.request.data['id']) if self.request.data.get('field_value',False): obj.field = self.request.data['field_value'] obj.save() this works like 95% of the time but occasionally I will catch an obj that has a blank field value after I KNOW that end point was hit correctly. So I changed my code to this: obj = models.CarObj.objects.get(id=self.request.data['id']) if self.request.data.get('field_value',False): obj.field = self.request.data['field_value'] obj.save() obj2 = models.CarObj.objects.get(id=obj.id) print("Mem: {} | DB: {}".format(obj.field, obj2.field)) if obj2.field == '' or len(obj2.field) == 0: raise ValueError("Mem does not match DB") The print always shows the same CORRECT values between the memory instance and the newest fetch from the DB. The ValueError is never raised. Yet sometimes field is still blank. So I went through the ModelViewSet of CarObj and made sure all the POST/ PATCH/ PUT all have: self.request.data.pop('field_value') before their respective serializers are populated with the self.request.data. Yet sometimes field is still blank. I have added a pre_save signal: @receiver(pre_save, sender=models.CarObj) def carobj_pre_save(sender, **kwargs): instance = kwargs.get('instance') if 'field' in instance.get_dirty_fields(check_relationship=True): field_new_value = getattr(instance,'field','') if field_new_value == '' or len(field_new_value) == 0: try: old_instance = models.CarObj.objects.get(id=instance.id) setattr(instance, 'field', getattr(old_instance, 'field', '')) … -
Permission api viewset for pub sub messages in Django
I want to create an action for this viewset that only can be triggered by our Google Cloud Pub Sub. class ObjectViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet, ): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] We have a separate endpoint that authorizes a request for only pub sub bearer_token = request.headers.get('Authorization') token = bearer_token.split(' ')[1] claim = id_token.verify_oauth2_token(token, transport.requests.Request(), audience=CLOUDRUN_SERVICE_URL) How can I add this logic to a Permissions class for a PATCH request? -
Making a follower count system in Python
I successfully made a post counter on my bassicly knock off twitter website i am building but I cant get the follower count to work. def get_context_data(self, **kwargs): user = self.get_object() context = super().get_context_data(**kwargs) context['total_posts'] = Post.objects.filter(author=user).count() context['total_followers'] = Follower.objects.filter(followed_by=id).count() if self.request.user.is_authenticated: context['you_follow'] = Follower.objects.filter(following=user, followed_by=self.request.user).exists() return context -
White spaces being added to text
I'm currently using a django char field in a model to store a url and then in the templates I do this: {% block url %} {% if object.url== '' %} {{ object.old_url}} {% else %} {{ object.url.strip }} {% endif %} {% end block url %} When i check it using inspect in chrome dev tools there are trailing and leading whitespaces for some reason even thought the "url" we enter has no whitespaces starting out? is their anyway to fix this? -
only get newest item of a type from queryset
Two models: class University(models.Model): name = models.CharField("name", max_length = 48) city = models.ForeignKey(City, on_delete = models.CASCADE) class Course(models.Model): name = models.CharField("course name", max_length = 48) university = models.ForeignKey(University, on_delete = models.CASCADE) students = models.ManyToManyField(Student, related_name = "%(class)s_name", related_query_name = "student_course_qs", blank = True) online = models.BooleanField("online course", default = False) semester = models.PositiveIntegerField("choose 1-6", default = 1, choices = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]) time_update = models.DateTimeField("last info update", auto_now = True) Restriction: If a Course has students, it cannot be online and vice versa. How would I obtain a list of all Courses on all Universities of a given city where the latest entry on Course has students and the Course is held in the 3rd semester? I tried it with a loop over the different groups of University but this results in a massive amount of queries: universities = University.objects.filter(city = City.objects.first()) wanted = [] for univ in universities: c = Course.objects.filter(university = univ).order_by("time_update").last() if c.semester == 3 and not c.online: wanted.append(c.id) selected_courses = Courses.objects.filter(id__in = wanted) The problem I see here is, that I create too many queries and just after the filter for universities they would already be grouped … -
login system issue not redirecting from register page to login page
i am creating a login system when a person create an account i want to redirect them to the login page but the user is still on the register page after they create their account my views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import * from .forms import OrderForm, CreateUserForm from .filters import OrderFilter def registerPage(request): if request.user.is_authenticated: return redirect('home') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('login') context = {'form':form} return render(request, 'accounts/register.html', context) def loginPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'accounts/login.html', context) **my urls.py** path('register/', views.register, name='register'), path('login/', views.login, name='login'),` i tried the redirect but it didn't worked -
How to Reduce Queries while Querying/Filtering GenericRelated Field Object
I have a Like model whose code looks like this: class Like(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) liked_on = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Meta: unique_together = ('customer', 'content_type', 'object_id') indexes = [ models.Index(fields=["content_type", "object_id"]), ] def __str__(self): return f'{self.customer.user} likes {self.content_object}' This generic relation enables me to reuse the likes model for the CampusAD and PropertyAD models which both have a GenericRelation to the Likes model. In the PropertyADSerializer which feeds the endpoints, /api/properties and /api/properties/{property_id}, I have a SerializerMethodField which provides a boolean telling the front-end which properties have been liked by the current authenticated user (useful for showing a like icon on the page for users). The SerializerMethodField is defined as thus: def get_liked_by_authenticated_user(self, obj): request = self.context.get('request') if request and request.user.is_authenticated: customer = Customer.objects.get(user_id=request.user.id) content_type = ContentType.objects.get_for_model(PropertyAD) likes = Like.objects.filter( customer=customer, content_type=content_type, object_id=obj.id) return likes.exists() return False Now, the issue with this approach is that it makes calls to the Customer and ContentType tables to fetch the required Customer and PropertyAD objects before using them for filtering, and this happens for each PropertyAD on the page resulting in hundreds of calls to the database as shown in the debug toolbar … -
Order Lists in alphabetical order (OrderFilter) with condition that the entries with the values '' were at the end of the list DRF
Good afternoon Please tell me how to sort the data in alphabetical order in ascending order! But with the condition that the entries with the values "" were at the end of the list. Here is the part of the code that conveys the meaning - def order_by_custom_fields(self, ordering: list): result = [] request_status_empty_first = Case( When(request_status__exact='', then=0), default=1 ) for field in ('field'): if field in ordering: result.append(request_status_empty_first) return result def get_ordering(self, request, queryset, view): params = request.query_params.get(self.ordering_param) if params: fields = [param.strip() for param in params.split(',')] ordering = self.remove_invalid_fields(queryset, fields, view, request) else: ordering = [] ordering.extend(self.order_by_custom_fields(ordering)) return tuple( self.filters_custom_ordering(ordering) ) def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering: return queryset.order_by(*ordering) return queryset This option displays records with '' at the very end, but the order is not alphabetical But it's necessary -
"The request's session was deleted before the request completed" on heavier requests
In my Django project I am frequently coming across the error: The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. This happens across a number of views and because of a number of different processes within my website. I have noticed that this error occurs on heavier requests for my local server to process, such as loading more images or returning more data from the database when calling the view associated with the current page the user is requesting. This issue does get resolved when configuring the session engine in settings.py: SESSION_ENGINE = "django.contrib.sessions.backends.cache" but this causes the users session to be cleared on server refresh which is a pain during development, so another option would be needed. I primarily use pythons sqlite3 package to execute most queries which could be a possible factor contributing to this error. sqlite3 connection settings connection = sqlite3.connect(r"C:\Users\logan..\....\db.sqlite3", check_same_thread=False) django database settings in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } perhaps using a different session engine would resolve this issue, or some other configuration in settings.py -
Custom Django JSON field with additional API information
I want to implement a custom json field that would take in the id and put it in json together with other API information. Let's say you receive an id of 2, so you want to put it together in the database like this: { "id": 2, "API": "path-to-api", "additional-info": ... } The additional info, API and other keys added to the json are known at the field declaration time, and they are always the same for the given column. I used Django's get_prep_value to change the value inserted into the DB. I am also using django rest framework ModelSerializer and generics for the views. When I create a new entry, the POST response doesn't have the correct JSON, just the id I sent it. However, if I look into the database, I can see that the value is saved in the correct way and if I list the values using the default generics ListCreateAPIView, I receive the correct JSON. So the question is: Can I do this kind of functionality somehow on the field level?