Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I make an upsert using the drf serializer?
I am trying to find a clean way using DRF serializers strictly in order to perform an upsert, aka inserting when the object with an indexed column does not exist or updating if it does exist (on duplicate equivalent of sql). I have found other ways using django objects but it seems there is no clear way to do that using a serializer. -
Delete Django queryset in a concurrency-safe way
I want to delete a row with a zero quantity in a way that is concurrency-safe. It is conceivable that the row could become non-zero just before it is deleted. The models looks something like this: class Stock(models.Model): product = models.ForeignKey(Product) location = models.ForeignKey(Location) quantity = models.IntegerField() To delete it, I am using: Stock.objects.filter(product=product, quantity=0).delete() I want the SQL to be: DELETE FROM app_stock WHERE product=product AND quantity=0 But it is being optimized to: DELETE FROM "app_stock" WHERE "app_stock"."id" IN (5) This optimization is quite reasonable in a sense as the ID of the object to be deleted is 5 and this is more efficient. Unfortunately it is not going to be safe as the stock could be increased by another process at anytime. I can fix this with raw SQL. I have also tried trying other queries but it is always optimized the same way. -
Simulating __subclasses__() behavior in one-to-many relationship in Django
I have situation similar to this, in which I have different levels in the hierarchy and every child in the hierarchy is in one-to-many relationship with its parent. # class from parent level. class Fookth: pass # classes from the child level. class Bar1: foo = models.ForeignKey(Fookth, on_delete=models.CASCADE) class Bar2: foo = models.ForeignKey(Fookth, on_delete=models.CASCADE) . . . class Barn: foo = models.ForeignKey(Fookth, on_delete=models.CASCADE) Now, my requirement is to find all the Bar-ith model which have Foo-kth as ForeignKey. Note, that if I have something like this, class Barith(Fookth) I could have used Fookth.__subclasses__() but that is not the case here. I wanted to ask is there a way to achieve this behavior? I have read through the docs but it only suggests to use related_name to use it in reverse query, but if I have lot of models it'll become tedious to keep track of each of them individually, I want something similar to __subclasses__(). -
Unable to access primary key of model object in template
I am trying to pass the primary key associated with a certain post back to my view to use for filtering the model objects. But I get that what is being passed to my view is 'None'. My template is as follows: {% for post in posts %} <div class="card mb-2"> <div class="card-body p-3"> <div class="row"> {% if post.non_bot == 'user' %} <div class="col-2"> WIP </div> <div class="col-2"> {{ post.created_by }} </div> {% else %} <div class="col-2"> <img src= {{ character.main_Img.url }} alt="Image Not Found" style="width:50px;height:60px;"> </div> <div class="col-2"> {{ post.character }} </div> {% endif %} <div class="col-2"> {{ post.message }} </div> {% if post.non_bot == 'bot' %} <div class="col-2"> <form method="post" novalidate> {% csrf_token %} {{ bot_rating_form.as_p }} {% include 'includes/form.html' %} <input type="hidden" name="form_type" value="bot_rating"> <input type="hidden" name="form_post" value="{{post.pk}}"> <button type="submit" class="btn btn-success">Rate</button> </form> </div> {% endif %} </div> </div> </div> {% endfor %} But the value that is apparently being passed back into the view from the hidden field "form_post" is None. Any ideas what I am doing wrong? -
Django orm - how to sort related fields when making Manager function
These are models for a restaurant booking service. Users can book a resaturant with their phone number, and can write down additional requests on request field. class Restaurant(models.Model): title = models.CharField(max_length=50) class Reservation(models.Model): restaurant_id = models.ForeignKey(Restaurant, on_delete_models.CASCADE) phone_number = models.CharField(max_length=50) request = models.TextField() created_at = models.DateTimeField(auto_now_add=True) So I want to make a RestaurantManager named 'has_request_for_latest_reservation()' that returns True if the most currently made reservation of given restaurant has value in request field, but I can't figure out where to begin. Restaurant.objects.get(id=1).has_request_for_lastest_reservation() I can do this on the side of Reservation like this, but how do I do the same thing on the side of Restaurant? reservation = Reservation.objects.filter(restaurant__id=1).order_by('-created_at').first() bool(reservation.request) -
Django full text search using SearchHeadline for multiple fields
While using django full text search can we use SearchHeadline for mutiple field as of now if only takes one field to annotate headline. search_vector = SearchVector('title', 'body') search_query = SearchQuery(search_post) search_headline = SearchHeadline('body', search_query) questions = posts.annotate(search=search_vector, rank=SearchRank(search_vector, search_query)).annotate(headline=search_headline).filter(rank__gt=0.0001).order_by('-rank') I use {{ post.headline|safe}}to view this in my django template. Is there any way i can use another SearchHeadline where i can headline 'title' field which is used in search vector. I tried annotate more than 2 times it over rides the previous headline. Is there any solution which can be implemented? -
Converting trilateration results to pixel values for displaying on a live map in a Django app
I have a django app that uses wifi trilateration to calculate a device's location in x,y. The calculated x,y values are expressed according to the real world locations of 3 wifi access points x1,y1, x2,y2, x3,y3. In the calculations x1, y1 is treated as the point of origin. After the trilateration is done, I want to show the location on a live map using ajax to send the device's live location. the map in my app is contained within a div with class .level.level--current which only covers part of the screen. how can i go from the x,y value given by the trilateration to pixel values that can be expressed within the map? The trilateration point of origin, x1,y1, may be different from the first pixel of the .level.level--current div. -
Django allauth: Multiple user registration with email-only authentication causing UNIQUE constraint error
I have an issue with a django allauth project I typed that in settings.py to disable username field and use email address SOCIALACCOUNT_QUERY_EMAIL = True ACCOUNT_LOGOUT_ON_GET= True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_LOGIN_ON_GET = True when I register for the first time it successfull, but when i tries to register another user raised me error : UNIQUE constraint failed: auth_user.username error with seccond register I expect that happend because unique not effected to field -
Does django-mptt support nested models?
I have a database of nested entities, that actually address parts: Street-House-Technical Room. In other words, I'd like to have a tree of nodes with different attributes on each level. What I'd like to implement is to use django-mptt features for this database, for example, I want to see the database as a tree in Django Admin. I tried the following in my models.py: from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Street(MPTTModel): name = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='streets') def __str__(self): return self.name class House(MPTTModel): name = models.CharField(max_length=100) parent = TreeForeignKey(Street, on_delete=models.CASCADE, null=True, blank=True, related_name='houses') def __str__(self): return self.name class TechRoom(MPTTModel): name = models.CharField(max_length=100) parent = TreeForeignKey(House, on_delete=models.CASCADE, null=True, blank=True, related_name='tech_rooms') def __str__(self): return self.name and my admin.py looks as: from django.contrib import admin from mptt.admin import MPTTModelAdmin from places.models import Street, House, TechRoom admin.site.register(Street, MPTTModelAdmin) admin.site.register(House, MPTTModelAdmin) admin.site.register(TechRoom, MPTTModelAdmin) The problem is it works as a regular Foreign key not as a tree. Is it possible to implement nested models using django-mptt? More specifically is it possible to use a model name (e.g. Street) instead of 'self' here: parent = TreeForeignKey(Street, on_delete=models.CASCADE, null=True, blank=True, related_name='houses') -
Django-Heroku: custom PIP module not found
I am trying to deploy my Django app with Heroku. I have successfully deployed this app before, but now with my recent changes the app crashes. I have created my own packages which I have installed in my virtual environment to be used throughout the app. The problem is when the app is deployed, an inspection of the Heroku logs shows that it can't find my custom modules. Running Heroku logs --tail 023-05-20T13:56:21.947973+00:00 app[web.1]: ModuleNotFoundError: No module named 'project_utils' How can I get Heroku to detect my custom packages? folder structure requirements.txt Django==4.1.7 django-heroku==0.3.1 ... scripts @ file:///C:/Users/logan/OneDrive/Documents/Programming/Python/apis/Legosite/legosite/local_packages/scripts project-utils @ file:///C:/Users/logan/OneDrive/Documents/Programming/Python/apis/Legosite/legosite/local_packages/project_utils config @ file:///C:/Users/logan/OneDrive/Documents/Programming/Python/apis/Legosite/legosite/local_packages/config -
Axios Bad Request 400 when saving event to my calendar
I am trying to implement addEvent function to vue calendar and I am strugging with Bad request 400 error. I am using Django and DRF for backend and fullcalendar-vue library to render my calendar. As you can see I put in my function few console logs and I can see that dish_name is visible and seems to be valid but for some reason Django returns NOT NULL constraint failed: dish_dishevent.dish_name_id. Question I also checked response.data.dish_name and it is undefined but the question is where am I making mistake? Where am I passing tis value incorrectly? Selected dish event: {id: 32, title: 'Spaghetti bolognese'} Selected dish event id: 32 Saving dish event: {dish_name: 32, start_time: '2023-05-04', end_time: '2023-05-05'} class DishEvent(models.Model): dish_name = models.ForeignKey(Dish, on_delete=models.CASCADE, related_name='dish_name') start_time = models.DateTimeField() end_time = models.DateTimeField() class DishEventAPIView(APIView): def get(self, request): events = DishEvent.objects.all() serializer = DishEventSerializer(events, many=True) return Response(serializer.data) def post(self, request): serializer = DishEventSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) handleDateSelect(selectInfo) { this.$axios.get('/dish-events/') .then(response => { const dishEvents = response.data.map(event => ({ id: event.id, title: event.dish_name, })); let selectedDishEvent = null; if (dishEvents.length > 0) { selectedDishEvent = dishEvents[0].id; } let dishEventDropdown = document.createElement('select'); dishEvents.forEach(event => { let option = document.createElement('option'); … -
Issue with updating categories and images in Django form
I'm working on a Django project where I have a form for updating a recipe. The form includes fields for the recipe name, description, preparation time, image, spiciness, steps, ingredients, and categories. I'm using Django's ModelForm and inlineformset_factory to handle the form and formset for the recipe ingredients. Yep this description was quickly made with chat-gtp. I'm encountering two issues: Categories not updating: When I try to update the recipe's categories, the changes are not saved. The checkboxes for the categories are not reflecting the current state of the recipe. Image not updating: When I upload a new image for the recipe and submit the form, the image gets updated but ifs a new image it doesn't get uploaded to the media (images) file. I have already checked my code, and I believe the issue lies in the update_recipe view function. I have made some changes to the code based on suggestions from OpenAI's ChatGPT, but the issues still persist. I have the following files: update_recipe.html: {% extends 'base.html' %} {% load widget_tweaks %} {% block extra_head %} <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" /> {{ block.super }} {% endblock %} {% block content %} <h1>Edit Recipe</h1> <form method="post" enctype="multipart/form-data" action="{% url 'update_recipe' … -
How to use two models in Django instead of using sessions, then store data to one and update these data to the second model after a successful action
I want to know how I can update a Django model with the data of another Django model, after an if status == 'successful': statement in a view function, this was working well with sessions, but when you try to save to the model after a callback the session gets lost. below are my models: class Hold_nominate(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) nomchildlast_nameho = models.CharField(max_length=100) nomchildfirst_nameho = models.CharField(max_length=100) nomchildageho = models.IntegerField() nomchilddobho = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return self.nomchildlast_nameho class Nominate(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) fk_holdnom = models.ForeignKey(Hold_nominate,on_delete=models.CASCADE) nomchildlast_name = models.CharField(max_length=100) nomchildfirst_name = models.CharField(max_length=100) nomchildage = models.IntegerField() nomchilddob = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return self.nomchildlast_name Bellow is my view code to save to the first Model: hold_nominate = Hold_nominate.objects.create( nomchildlast_nameho = nomchildlast_name, nomchildfirst_nameho = nomchildfirst_name, nomchildageho = b, nomchilddobho =nomchildage, nomchildamountho =nomchildamount, nomspemailho =nomspemail, user_id=user, nomchildgenderho = nomchildgender, nomchildclasscompho = nomchildclasscomp, nomchildshirtho = nomchildshirt, nomchildhealthissueho = nomchildhealthissue, nomchildhealthdetailho = nomchildhealthdetail, nomemerphoneho = nomemerphone, nomspnameho = nomspname, nomsprelchildho = nomsprelchild, nomspphoneho = nomspphone, ) hold_nominate.save() Below is where I am having issue to save to the second model after status == "successful": honomx = Hold_nominate.objects.get(id=child_id) nomchildlast_name = honomx.nomchildlast_nameho nomchildfirst_name = honomx.nomchildfirst_nameho nomchildage = honomx.nomchildageho nomchilddob = honomx.nomchilddobho nomchildamount = honomx.nomchildamountho nomspemail = … -
does anyone know how to change gg-mail icon position with html or css?
i tried moving a gmail icon i got from https://css.gg/mail, but everytime i try to move it i just ended up moving the lines on the icon instead of moving the whole icon as a whole. Here is the example of the CSS .gg-mail::after { display: block; box-sizing: border-box; height: 14px; border: 2px solid } .gg-mail { overflow: hidden; transform: scale(var(--ggs,1)); position: relative; width: 18px; border-radius: 2px } .gg-mail::after { content: ""; position: absolute; border-radius: 3px; width: 14px; transform: rotate(-45deg); bottom: 3px; left: 0 } -
Debugging production javascript errors
How can I make console.log visible to my django site deployed on heroku? I made a wordlegolf site, www.wordlegolfing.com, where my friends and I play wordle and it tracks our scores daily. I made it in Django and have it deployed on Heroku. I am getting errors randomly and having issues recreating them and fixing them. I added a logger to my Python code but it's not really telling me much as the javascript seems to be the issue. Can I add a logger to my javascript code that I can read from Papertrail or another log management tool? Also, the only thing I could think of my errors being is from poor internet connections, is that possible? I can not debug this from a local host using console.log because I can't recreate the errors. I tried django-js-logger (https://github.com/snok/django-js-logger) and I seem to get it somewhat working as it does a post request every time console.log is called but Im not sure how to show any data [20/May/2023 08:50:39] "POST /js-logs/ HTTP/1.1" 204 0 [20/May/2023 08:50:39] "POST /js-logs/ HTTP/1.1" 204 0 -
How do i send a timed notification to a user with django?
I am building a hotel management system with django. I want to implement a functionality that sends the user(guest in this case) a notification 6 hours before their reservation expires asking them if they want to renew. I have looked into some ways to do this like django-mails, channels and cron but they all do not seem to be able to do this or maybe I don't just know how to manipulate them well enough. Nevertheless, here is what I tried with cron: notification/cron.py class SendRenewalNotification(CronJobBase): RUN_EVERY_MINS = 60 # Run the cron job every hour schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'notification.send_renewal_notification' def do(self): now = datetime.now() six_hours_later = now + timedelta(hours=6) reservations = Reservation.objects.filter(end_date__gte=now, end_date__lte=six_hours_later) for reservation in reservations: user = reservation.guest reservation_id = reservation.pk url = reverse('update_reservation', args=[reservation_id]) view_reservations_url = reverse('view_reservations') subject = 'Renew Your Room Reservation' message = f'Dear {user.username}, your room reservation is ending soon. Would you like to renew it?' message += f' Click the link below to update your reservation:\n{url}' message += f'\n\nYou can also view all your reservations here: {view_reservations_url}' from_email = 'your_email@example.com' recipient_list = [user.email] send_mail(subject, message, from_email, recipient_list) -
Why does my site enter a blank page after the form submits a post request?
I am using Django to create a form that will update a list. I know it's quite simple, but I haven't used it in a while and got stuck. Here is my urls.py file inside my app: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:site>", views.info, name="info"), ] Here is the views.py file: from .models import website, members from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse def index(request): if request.method == "POST": named = request.POST["name"] desc = request.POST["description"] obj = website(name = named, description = desc) obj.save() return HttpResponseRedirect(reverse("index")) return render(request, 'management/index.html', { "website":website.objects.all() }) def info(request, site): return render(request, 'management/info.html', { site:"site" }) And here is the index.html page: <!DOCTYPE html> <html lang="en"> <head> <title> WebGo Management </title> </head> <body> <h1>Welcome to WebGo.</h1> <h3>Here, you can manage projects and deal with admins</h3> <form action="post"> {% csrf_token %} <input type="text" name="name" id="name"> <input type="text" name="description" id="description"> <input type="submit" name="submit" id="#"> </form> <ul> {% for i in website %} <li>{{i.name}}</li> {% endfor %} </ul> </body> </html> After it finishes submitting the form, it takes me to a blank page, with the following URL: http://127.0.0.1:8000/management/post?csrfmiddlewaretoken=HQO4pZAh79Q3ZUSxp90z6pRO6ieOeWI2hiBkVBu8TXaMJ63vZR2rDFskGw5oqdxr&name=Mukesh&description=cool&submit=Submit I am confused as to why … -
Django: how to display error only once when user enter invalid information on form submition?
may someone tell me how to avoid to have the error message shown 2 times? I'd like to keep the top error message, but on red. https://files.slack.com/files-pri/T07EFKXHR-F058SR427RA/image.png html: <form hx-post="{{ request.path }}" class="modal-content p-4" enctype="multipart/form-data"> <div class="modal-header"> <h5 class="modal-title">Ingresa tu usuario y clave</h5> </div> {% csrf_token %} {{ login_form.as_p }} {% if login_form.errors %} <ol class=""> {% for field_errors in login_form.errors.values %} {% for error in field_errors %} <li class="text-danger"><strong>{{ error|escape }}</strong></li> {% endfor %} {% endfor %} </ol> {% endif %} <div class="modal-footer"> <button type="submit" class="btn btn-primary">Ingresar</button> </div> </form> form.py: class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Nombre de usuario'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Contraseña'})) image: -
How can I display the names of employees under the same company on my Django index page?
Django display value in list of same row name models.py class Employee(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) comment = models.TextField() #companyname=models.OneToOneField(Insert, on_delete=models.CASCADE) def __str__(self): return f"{self.first_name} {self.last_name}" class Company(models.Model): name = models.CharField(max_length=100) employeename= models.ForeignKey(Employee, on_delete=models.CASCADE,blank=True,null=True) this is my index page enter image description here urls.py path('', views.companies_view), what i want is Apple [None, Jessica, Matthew, Anthony] instead of apple jessica apple matthew apple Anthony -
Change button on click after django view
I have this follow form using htmx, I tried writing hx-swap:innerhtml but it's just writing the response instead of the button: <form id="follow-form" hx-post="{% url 'main:follow_toggle' account.id %}"> {% csrf_token %} {% if request.user in account.followers.all %} <button type="submit" id="follow-button" class="btn btn-secondary rounded-pill">עוקב</button> {% else %} <button type="submit" id="follow-button" class="btn btn-success rounded-pill">עקוב</button> {% endif %} </form> and this view: class FollowToggleView(generic.View): def post(self, request, account_id): user_to_toggle = get_object_or_404(Account, id=account_id) if user_to_toggle in request.user.following.all(): request.user.unfollow(user_to_toggle) return HttpResponse('User unfollowed successfully') else: request.user.follow(user_to_toggle) return HttpResponse('User followed successfully') I tried this js but it doesnt work changing the buttons classes: <script> const followButton = document.getElementById('follow-button'); // Handle the AJAX response to update the button text and class document.addEventListener('htmx:afterSwap', (event) => { if (event.detail.target.id === 'follow-toggle') { const response = event.detail.xhr.response; if (response.is_following) { followButton.innerText = 'עוקב'; followButton.classList.remove('btn-success'); followButton.classList.add('btn-secondary'); } else { followButton.innerText = 'עקוב'; followButton.classList.remove('btn-secondary'); followButton.classList.add('btn-success'); } } }); </script> -
SameSite error in my Django + React authentication app
SameSite error in my Django + React authentication app I have a simple React + Django authentication app I deployed just for testing. I'm using Django Rest Framework. However, I'm facing this error when I click 'Login'. Basically, because of this error, the server isn't able to send/set cookies to the client. Here's the Django view: class Login(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise exceptions.AuthenticationFailed('Invalid credentials') if not user.check_password(password): raise exceptions.AuthenticationFailed('Invalid credentials') refresh_token = create_refresh_token(user.id) access_token = create_access_token(user.id) UserToken.objects.create( user_id=user.id, token=refresh_token, expired_at=datetime.datetime.utcnow() + datetime.timedelta(days=365) ) response = Response() response.set_cookie(key='refresh_token', value=refresh_token, httponly=True) response.set_cookie(key='access_token', value=access_token, httponly=True) response.data = UserSerializer(user).data return response In short, when I send '/login/' POST request to the server, it uses set_cookie() to set cookies on the client side. It works fine in the dev environment but gets messed up in the production environment. Client Github Code: https://github.com/MrGuardianGo/React-Django-Authentication-Client Server Github Code: https://github.com/MrGuardianGo/React-Django-Authentication-Server Help will be really appreciated. Thank you! -
How to accept websocket connections from a NextJS app deployed on vercel. In Django project that is deployed on Ubuntu VPS using nginx and gunicorn
The devlopment version of my django and nextjs is working fine but when I deployed the nextjs project on vercel and django project on ubuntu vps, It is not working! My django project uses django-channels to intract with the frontend and send messages thorough websocket. Here is my nginx file: server { listen 443 ssl; listen [::]:443 ssl; ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt; ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key; server_name _; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/projectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws { proxy_pass http://localhost; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } Here is my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/projectdir ExecStart=/home/ubuntu/env/bin/gunicorn --access-logfile - --workers 4 --bind unix:/run/gunicorn.sock --worker-class=geventwebsocket.gunicorn.workers.GeventWebSocketWorker chatterboxBackend.wsgi:application [Install] WantedBy=multi-user.target Here is my routing.py file: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"^ws/message/(?P<room_name>w+)/$", consumers.ChatConsumer.as_asgi()), ] Here is my project's .asgi file import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chatterboxBackend.settings") django_asgi_app = get_asgi_application() import message.routing application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(message.routing.websocket_urlpatterns)) ), } ) At first when I try to connect to backend websocket … -
django.template.response.ContentNotRenderedError: The response content must be rendered before it can be iterated over
I'm overriding the def get_queryset(self) to aggregate averages, sums, etc, of a model. My challenge is that I want to return these values but it is not a queryset so I get the following error: django.template.response.ContentNotRenderedError: The response content must be rendered before it can be iterated over.. My question is how can I return these values since they are not a queryset. Here is my code: class OrderMetrics(generics.ListCreateAPIView ): queryset = Order.objects.all() serializer_class = OrderSerializer def get_queryset(self): ... context = [ { 'data': round(current_total), 'percent': abs(total_delta_percentage), }, { 'data': current_count, 'percent': abs(avergae_delta_percentage), }, ] print(context) return Response(context, status=status.HTTP_200_OK) # print(context) returns the following: # [{'data': 138378, 'percent': 132}, {'data': 11, 'percent': 16}] I have seen several other similar questions but they don't address how to do this: ContentNotRenderedError: The response content must be rendered before it can be iterated over. Django REST and ContentNotRenderedError : The response content must be rendered before it can be iterated over -
What are some alternatives to 'python manage.py makemigrations --merge' for resolving duplicate Django migrations?
I need help with my Django project, with migrations. I have duplicated migrations which are not applied and it cose conflicts and so I can not deploy the website. Please if someone knows what to do let me know. I have tried python manage.py makemigrations --merge, it doesn't work. I do not want to delete the database, there must be some way what to do with this? I have tried so many different things, but it's still there.showmigrations I look forward to hear from someone. Thank you, Martina I have tried to run python manage.py makemigrations --merge, it did not work, also wanted to delete the migrations without the database, but it did not let me to do it because of the conflicts. Also I was trying to INSTALL DJANGO-MIGRATION-FIXER, but also it did not work :-( -
Django Static Files Not Loading through IIS
Currently I am stuck with deployment of Django on IIS as static files are not loading ...I tried to collect all staticfiles via command python manage.py collectstatic and then make virtual directory under my website Here is hirarchy of my project under IIS Under settings file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') Please tell me what I am doing wrong? I tried through configuring virtual directory under my project