Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I return several aggregates based on a condition within a queryset?
So I have the following model which contains different booleans and one amount field. I now want to render the overall sum amount for each boolean when true (only one boolean will be true at once always). class UserTransaction(models.Model): """ A table to store transactions between a user and Farena """ user = models.ForeignKey(User, on_delete=models.CASCADE) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) amount = models.FloatField() is_deposit = models.BooleanField(default=False) is_withdrawal = models.BooleanField(default=False) is_interest = models.BooleanField(default=False) is_investment = models.BooleanField(default=False) is_return = models.BooleanField(default=False) def __str__(self): return f'{self.user.first_name} {self.user.last_name} transacted {self.amount}' I tried to build it with annotate but that would add fields for each instance which wouldn't solve my issue as far as I understand it. Additionally using aggregate I couldn't implement a condition and also wouldn't know how to access the aggregated value in the template? -
Unable to select value in action intermediate page
I have two models User and Group. I'm implementing an action "Change Groups" in UsersAdmin that redirects to an intermediate page with 2 MultipleChoiceFields for Groups, that I want to be used to either remove users from certain groups, add users to other groups, or do both in one go (i.e. move them). The docs are very short about this subject, so in order to do this, I'm following this article. Here's my form: class ChangeUsersGroupsForm(forms.Form): _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) from_groups = forms.ModelMultipleChoiceField(Group.objects, required=False) to_groups = forms.ModelMultipleChoiceField(Group.objects, required=False) My admin action: def change_groups_action(self, request, queryset): if 'apply' in request.POST: from_groups = request.POST["from_groups"] to_groups = request.POST["to_groups"] from_groups_qs = Group.objects.filter(pk__in=from_groups).all() to_groups_qs = Group.objects.filter(pk__in=to_groups).all() user_ids = [u.user_id for u in queryset] # task that will do the job of actually moving the users change_users_groups.delay(from_groups_qs, to_groups_qs) self.message_user(request, "Changed groups of %s users" % len(user_ids)) return HttpResponseRedirect(request.get_full_path()) form = ChangeUsersGroupsForm(initial={'_selected_action': queryset.values_list('id', flat=True)}) return render(request, "admin/change_users_groups.html", {'queryset': queryset, 'form': form}) change_groups_action.short_description = "Change Groups" Here's my template: <!-- users/templates/admin/change_users_groups.html --> {% extends "admin/base_site.html" %} {% block content %} <form action="" method="post"> {% csrf_token %} {{ form }} <br /> <br /> <p>The Group changes will be applied to the following users:</p> <ul> {{ queryset|unordered_list }} </ul> <input … -
How to pass 2 parameters from django template to url path
path('/cart/<int:id>,<str:seller>/', auth_middleware(Cart.as_view()) , name='cart'), <form action="/cart/id={{product.id}}&seller={{price.seller}}" class="col-2 " method="post"> {% csrf_token %} <input hidden type="text" name='product' value='{{product.id}}'> <input type="submit" value=" Add to Cart " class="btn btn-success"/> </form> Wont get it working -
How to use drf implement nested url route?
with ModelViewSet, we can easily have these routes /article #get article list /article/1/ #get article whose id is 1 However, I want to accomplish following routes /article/1/comment #get comment list of article(id=1) /article/1/comment/5/ #get comment(id=5) (suppose that this comment belongs to article(id=1)) /article/1/comment/5/childern #get childern comment list of comment(id=5) .... What should I do? -
django.db.utils.OperationalError: sequence must have same owner as table it is linked to
This error is of Django - Postgres Schema of tables are public, type = table and owner are same what is this issue can you help me solving this -
Django HEIC to PNG conversion
I'm trying to convert heic to png, which I successfully achieved in Python with the help of Wand library. I also saved the file locally to see, if the convertion worked, and it did. The problem is that Django's serializer cant take in Wand image, and I have to convert it to InMemoryUploadedFile. Whatever I do, I still can't make the serializator to take in the converted image. views.py update_post() @api_view(['PUT']) @permission_classes([IsAuthenticated]) def update_post(request, id): image = request.FILES['image'] print(image.size, image.name, image.file, image.content_type, image.field_name) if image.content_type == 'image/heif': img = Image(file=image) img.format = 'png' img_io = io.BytesIO() img.save(file=img_io) filename = image.name.replace('.heic', '.png') img.save(filename=filename) img_file = InMemoryUploadedFile( img_io, 'image', filename, 'image/png', sys.getsizeof(img_io), None) print(img_file.size, img_file.name, img_file.file, img_file.content_type, img_file.field_name) image = img_file #request.data['image'] = img_file #request.FILES['image'] = img_file # data = request.data # print(img_file, image) loggedin_user = request.user.username post = Post.objects.get(id=id) post_user = post.user if (str(post_user) == str(loggedin_user)): serializer = PostSerializer( instance=post, data={'caption': request.data['caption'], 'image': image}) if serializer.is_valid(): print(serializer.validated_data) serializer.save() else: print('achjo') print(serializer.data) return Response(status=status.HTTP_200_OK) -
Django Invalid HTTP_HOST header: '<ip>'. You may need to add '<ip>' to ALLOWED_HOSTS
<ip> is showing an actual ip address, I just didn't include it in the title. I believe this ip address is the internal ip of my EC2 instance. I'm using AWS Elastic beanstalk to host. I see this question has been answered a lot on SO, and the answer is always to add the ip address to the ALLOWED_HOSTS, but in my case I've set ALLOWED_HOSTS=['*'] and I'm still getting the error. The weird thing is, I'm only getting the error when I try to access the site from my phone. When I access from the desktop browser, it works fine... Things I've tried: I've double checked my elastic beanstalk deployment and the changes are definitely deployed. -
Apache - Django - File upload error code 500
I'm having an issue with hosting my django project on Apache. In my project I have the models Product and ProductImage. A Product has multiple ProductImages, and creating a ProductImage simply saves an image file and saves the name of the file in the database. All of this works perfectly fine when I use the runserver command. However as soon as I use Apache to host my project (using mod_wsgi) it doesn't work anymore. I'm suspecting something is going wrong with the file upload. I'm quite new to this so I'm not sure what's a good way to debug this? I've checked /var/log/apache2/error.log but nothing useful is in there. ProductImage view: class ProductImageViewSet(viewsets.ModelViewSet): serializer_class = ProductImageSerializer queryset = ProductImage.objects.all() def create(self, request, *args, **kwargs): product_id = request.data["product_id"] name = request.data["name"] file = request.data["file"] name = default_storage.save(name, file) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(name=name, product_id=product_id) # success response return Response({"message": serializer.data}, status=status.HTTP_200_OK) Is there something I'm missing? -
Show all items of an invoice - django
I would like to get all items belonging to an invoice and show them to a template without success. What i have done so far is the following: I have two models: class Invoice(models.Model): PAYMENT_OPTIONS = ( ('CASH', _('CASH')), ('DEPOSIT', _('DEPOSIT')), ('CARD', _('CARD')), ) INVOICE_TYPE = ( ('Service', _('Service')), ) invoice_number = models.CharField(max_length=7, unique=True, default='INV4898') invoice_user = models.ForeignKey(Account, on_delete=models.CASCADE) invoice_type = models.CharField(max_length=30, choices=INVOICE_TYPE, default='Service') payment_option = models.CharField(max_length=30, choices=PAYMENT_OPTIONS) invoice_name = models.CharField(max_length=30, null=True, blank=True) vat = models.CharField(max_length=9, blank=True, null=True) gross_amount = models.DecimalField(max_digits=6, decimal_places=2) vat_amount = models.DecimalField(max_digits=6, decimal_places=2) net_amount = models.DecimalField(max_digits=6, decimal_places=2) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.invoice_user.first_name} {self.invoice_user.last_name} - {self.invoice_number}" class Item(models.Model): invoice = models.ForeignKey(Invoice, related_name='items', on_delete=models.CASCADE) title = models.CharField(max_length=255) quantity = models.IntegerField(default=1) unit_price = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00')) net_amount = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00')) vat_rate = models.CharField(max_length=10, default=0) discount = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00')) is_paid = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.invoice.invoice_number}" In the views.py i have a list view like, in which i'm trying to get a list of all invoices based on invoice_number and then match each invoice_number to an invoice in items. However using below code first pring brings all invoice_number(s) and second print brings all items for all invoices, not … -
How to get the current port in a django application?
How can I get the current port of my running django application? I don't have access to the request, and I can't use the Site object. -
How to make a view that lists project instances with option buttons
I am trying to build a django webapp that manages and executes a few python programs I wrote. Background information: The setup: I have a folder called projects with subdirectories called project_1, project_2 and so on. In every project_x folder, there are a few config_whatever.csv files and a routin_projectX.py python code file that reads the config_whatever.csv files and does a routine accordingly. All project_x subdirectories have the exact same structure. Currently I am managing the project instances by either editting the config files with an editor and restarting the routin_projectX.py function or for instance copying a template project_x directory , editing the config files and then executing the routin_projectX.py. The webapp is intended to be able to manage those project instances. My end goal: I would like to create a view that shows a table , listing all project_x subdirectories of the projects folder as rows and a few buttons with functionality as columns, specifically: edit forwards to a view where editting the config_whatever.csv files is possible, start/stop running the routine or restart-ing it, as well as delete-ing the project (removing it from the list and deleting the project directory) and less important ones (run once, read error logs), for … -
Run a function in background django
I have a function in Django I want to run in the background whenever a button clicks and should email the required result, it should not wait for current thread to complete. How can I achieve this without using any fancy background jobs -
How to remove 'b' literal from Raised validation error response in python serializer
When I raise a validation error in my serializer the output is prefixed with a 'b' (which I believe is a byte type) and every way I've tried to remove it has failed. My serializer class: class AppInputTypeSerializer(serializers.Serializer): #value = serializers.CharField(required=True, max_length = 100, min_length = 1) def validate_value(self, data): length = len(data['value']) if length < 1 or length > 100: message = "We are sorry, your reply should be between 1 and 100 characters. Please try again." data['error'] = message raise serializers.ValidationError(message) return data my view: class PresentationLayerView(generics.GenericAPIView): permission_classes = (permissions.AllowAny,) def post(self, request, *args, **kwargs): body = request.data cardType = body['cardType'] if cardType == "TERMS_CONDITIONS": serializer = AppTandCTypeSerializer(body) elif cardType == "CHOICE": serializer = AppChoiceTypeSerializer(body) elif cardType == "TEXT" or cardType == "INPUT": serializer = AppTextTypeSerializer(body) serializer.validate_value(body) #print(response.text) return Response({}, status=status.HTTP_200_OK,) Test_views: class StartAssessmentViewTests(APITestCase): # Return validation error if user input > 100 characters for an input cardType def test_input_type(self): #response = self.client.get( # reverse("app-start-assessment") #) response = self.client.post(reverse("app-start-assessment"), json.dumps({"message":"Please type in the symptom that is troubling you, only one symptom at a time. Reply back to go to the previous question or abort to end the assessment", "step":4, "value": "This is some rubbish text to see what … -
GeoDjango distance_lte query showing inaccurate results
I am trying to filter all the restaurants within a specific radius from the source location. Source location is coming from the user via GET request. Here's the code: from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.measure import D latitude = request.GET['latitude'] longitude = request.GET['longitude'] radius = request.GET['radius'] point = GEOSGeometry('POINT(%s %s)' % (longitude, latitude)) restaurants = Restaurant.objects.filter(location__distance_lte=(point, D(km=radius))) # checking the distance for i in restaurants: distance = pnt.distance(i.location) print(i, distance * 100) I am getting the results 80% correct but 20% wrong. Let me explain what is happening... By running the above filter with a radius of 55km, I get the results but when I check the distance from the source location to the restaurant locations, there are a few restaurants missing that are around 52km away from the source location. I am expecting them too to be in the results when I filter it with a 55km radius. If I increase the radius from 55km to 58km, then those missing restaurants are showing. I am unable to understand why some of the restaurants are not being pulled? Any help would be highly appreciated. Thanks. -
How to sort by field using ForeignKey
I have a queryset of all objects in the Room model. qs = Rooms.objects.all() I need to sort it by the last received message in the Message table. There I have a variable room, which has a FK relation to Room. I.e. the last created Message object, should act as 1 Room, the penultimate should go second, etc. How can I in Room refer to timestamp for sorting? qs.order_by("message_room__timestamp") I tried to do qs.order_by("message_room__timestamp"), but for some reason I get a very strange response, I get duplicate rooms class Room(models.Model): name = models.CharField(max_length=255, unique=True) class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, default=None, null=True, related_name="message_room") text = models.CharField(max_length=255) timestamp = models.DateTimeField(auto_now_add=True) -
Max column value of related django model where condition is true
TAssignment model has many entries related to TSlot model like for 1 pk of TSlot model there are many entries in TAssignment model.Now this queries outputs values from Tslot table and also latest related created on and updated on from Tassignment table.But what i want is latest value of 'assignment_Slot__created_on' and 'assignment_Slot__updated_on' when assignment_Slot__is_deleted=False. QUESTION: How to add "assignment_Slot__is_deleted=False" condition along with 'assignment_Slot__created_on' and 'assignment_Slot__updated_on' inside annotate without duplicating results. ** assignment_Slot here is related name TSlot.objects.filter(request__id=request_id, is_deleted=False ).values("slot_date", "type_of_work", "reason_for_less_assign", "request_id","slot", "remarks", slot_id=F("id"), request_status=F('request__request_status')).annotate( assigned_on=Max('assignment_Slot__created_on'), modified_on =Max('assignment_Slot__modified_on')) -
The view orders.views.place_order didn't return an HttpResponse object. It returned None instead
I am new to django and got this error. Can someboody please help me to figure out Here is my views.py code def place_order(request, total=0, quantity=0,): current_user = request.user if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.save() return redirect('checkout) else: return redirect('checkout') -
How to use Vuejs SFC (single file component) in django
fil1.vue <script setup> import { ref } from 'vue' const msg = ref('Hello World!') </script> <template> <h1>{{ msg }}</h1> <input v-model="msg"> </template> I would like to render this in my Django template. Previously with normal vue components I was able to do use them as follows: JS file: Vue.component('comp1', {...}) django html template: <comp1> </comp1> -
How to refer custom User model in settings.py using subapp in Django?
I followed this StackOverflow post to create a sub-app in Django. I've got a custom 'User' model which is inside an 'account' app which is then inside in parent app 'myapp'. -myapp (parent app) --accounnt (subapp) ---models.py User I changed the name of my account app to class accountConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'myapp.account' Installed app INSTALLED_APPS = [ ... 'myapp.account' ] Now, I need to refer this model for AUTH_USER_MODEL in my settings.py. The basic method is AUTH_USER_MODEL = 'app_label.model'. In my case its AUTH_USER_MODEL = 'myapp.account.User'. I got this error: ValueError: Invalid model reference 'myapp.account.User'. String model references must be of the form 'app_label.ModelName'. or if I refer User model as AUTH_USER_MODEL = 'account.User'. then, Django isn't able to recognize account as an installed app Is there any way, I can refer to my User model in AUTH_USER_MODEL? Any help is highly appreciated. -
Deserialize JSON with User ID
I am running into an issue while deserializing JSON data. One of the field is the customerID and i cannot find a way to user a Serializer class properly. Here is my code: class UserProfileData(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) captureDateTime = models.CharField(_('Capture datetime'), blank=True, null=True, max_length=100) class UserProfileDataSerializer(serializers.ModelSerializer): class Meta: model = UserProfileData fields = "__all__" The JSON i receive is the following: { "customerID": "someUUID", "captureDateTime": "..." } Here is the current state of my view: @api_view(['POST']) def register_profile(request): data = JSONParser().parse(request) serializer = UserProfileDataSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) It fails with the following error: {'user': [ErrorDetail(string='This field is required.', code='required')]} I understand i am missing something here, but can't figure out what... Also, i almost forgot to mention the User object has a customerId field. Thanks for your help. -
Connecting react.js to Django backend: Postman works but Axios post does not
I would like a decisive solution to linking my react to my django backend, as I have fallen into confusion by picking bits and pieces from various sources. I am trying to deploy a fine-tuned transformer model for inference, it works perfectly, and I am able to post and get a response with postman. Below is the Axios/node.js code from postman for reference. var axios = require('axios'); var data = JSON.stringify({ "data": "my input sentence..." }); var config = { method: 'post', url: 'http://127.0.0.1:8000/api/infer/', headers: { 'Content-Type': 'application/json', 'Cookie': 'csrftoken=zVbH181pBhnaAAtEoTmQGd0XLABvVLjsjVsDNYVudLZCmSMSXpe1RQJOd' }, data : data }; axios(config) .then(function (response) { console.log(JSON.stringify(response.data)); }) .catch(function (error) { console.log(error); }); This app doesn't require any login or authentication modules.. Below is the code of the single page in react which I expect to -> on click <-, send my "data" to the Django backend for prediction, and return my result. Below is the Home.js file import * as React from 'react'; import Box from '@mui/material/Box'; import TextField from '@mui/material/TextField'; import { IconButton } from '@material-ui/core'; import { InputAdornment } from '@mui/material'; import {useState, useEffect} from "react" import axios from "axios" import {component} from 'react' export default function MultilineTextFields() { const [data, setData] = React.useState(''); … -
Django Rest API returning ValueError: Invalid format string
Getting the error Invalid format string when creating a new user in Django. Even though I am getting this error, a new user is being created. Here is my serializers.py: from django.contrib.auth.models import User from rest_framework import serializers #changed from serializers.HyperLinked to ModelSerializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User #removed url from fields fields = ['username', 'email', 'password'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = User.objects.create_user( username=validated_data['username'], password=validated_data['password'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) class PasswordSerializer(serializers.Serializer): old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) My urls.py: from django.contrib import admin from django.urls import path, include from rest_framework import routers from . import views from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, TokenVerifyView) from .api import RegisterApi router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('api/register', RegisterApi.as_view()), ] and api.py: from rest_framework import generics, permissions, mixins from rest_framework.authentication import TokenAuthentication from rest_framework.response import Response from .serializers import RegisterSerializer, UserSerializer from django.contrib.auth.models import User from rest_framework.permissions import AllowAny #Register API class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer #remove this if it … -
Django : How can we custom login_required decorator?
I want to rewrite the login decorator of Django to check an Azure AD authentication. For the authentication, I used the tutorial (https://docs.microsoft.com/en-us/graph/tutorials/python). I do not how how to deal with groups and permission since I use this authentication, so I take the username, surname as a password to create un user in the User django models. For that I modify the callback function of the tutorial : def callback(request): # Make the token request result = get_token_from_code(request) #Get the user's profile user = get_user(result['access_token']) # Store user store_user(request, user) # Get user info # user attribute like displayName,surname,mail etc. are defined by the # institute incase you are using single-tenant. You can get these # attribute by exploring Microsoft graph-explorer. username = user['displayName'] password = user['surname'] email = user['mail'] try: # if use already exist user = User.objects.get(username=username) except User.DoesNotExist: # if user does not exist then create a new user user = User.objects.create_user(username,email,password) user.save() user = authenticate(username=username,password=password) if user is not None: login(request,user) messages.success(request,"Success: You were successfully logged in.") return redirect('home') return redirect('home') If I want to check if the user is authenticated by Azure AD, I have to do something like that : if request.session.get('user').get('is_authenticated') : But … -
Cookie collision: is it possible to distinguish between parent domain and subdomain cookies in Django and Javascript?
I have built a bunch of Django websites at a single domain: example.com site1.example.com site2.example.com site3.example.com They are supposed to be completely independent — used by different people for different purposes. However cookies set by example.com are given priority by Django, and values set by site1.example.com, site2.example.com etc. are ignored if the parent domain has set a cookie with the same name. How it works: When the first page is loaded, it sets a cookie so the server knows to send a computer page or a mobile page with the next request. The Django program builds the correct version based on the cookie value. When site1.example.com loads, it sets a cookie asking for the mobile version. But then the Django program sees the value set by example.com and ignores the correct cookie. So, I need a way to do one of the following: prevent site1.example.com from reading the cookie of example.com differentiate in Django the domain associated with the cookie so I can tell that the value is wrong find a way to set a parent domain cookie in Javascript that makes it inaccessible to subdomains (I'm not using www) If I can't find an elegant solution, I will likely … -
Insert data from SQL file in Django DB
I'm working on a Django Project, and I have all my datas in .sql files. I want to insert all of them in my Database. Can I use the python shell to do it ? Or should I use another method ?