Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
How to remove some items form queryset depending on @property?
I don't know how to remove results from a queryset without using .exclude(). I want to filter the result if the argument is_active is passed as a parameter of my search based on the result of the property is_active. My model with the calculated property 'is_active': class Discount(models.Model): name = models.CharField(_("name"), max_length=255) date_start = models.DateField(_("Date start"), null=True, blank=True) date_end = models.DateField(_("Date end"), null=True, blank=True) [...] @property def is_active(self): if self.date_start and self.date_end: return self.date_start <= date.today() <= self.date_end return True My viewset: class DiscountViewSet(viewsets.ModelViewSet): """ A simple ViewSet for listing or retrieving discounts. """ permission_classes = [CustomDjangoModelPermission] filter_backends = [DjangoFilterBackend] filter_fields = '__all__' def get_serializer_class(self): if hasattr(self, 'action') and self.action in ['list', 'retrieve']: return DiscountListSerializer return DiscountSerializer def get_queryset(self): if self.request.user.is_staff: return Discount.objects.all().prefetch_related('products') \ .prefetch_related('machines').prefetch_related('categories') else: return Discount.objects.all().prefetch_related('products') \ .filter(machines__site__client__in=self.request.user.profil.client.all()) \ .prefetch_related('machines').prefetch_related('categories') @swagger_auto_schema(manual_parameters=[height, width], responses={200: DiscountListSerializer}) def list(self, request): height = self.request.query_params.get('height') width = self.request.query_params.get('width') queryset = self.get_queryset() queryset = self.filter_queryset(self.get_queryset()) active_filter = request.data.get('is_active') if active_filter: for item in qs: if not item.is_active: ???? // remove item if height and width: for discount in queryset: if discount.menu_photo: discount.menu_photo = generate_thumbnail(discount.menu_photo, width, height) if discount.standby_photo: discount.standby_photo = generate_thumbnail(discount.standby_photo, width, height) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, … -
Issue with CSS file in Django
Trying to load a css file into my base.html file. When I load the webpage, it is not updating the webpage with the css styling I loaded. Everything is running as expected, 0 issues when I activate it in terminal. -
How to add multiple forms in one page using django formset
Using Django formset, you can add multiple forms at once on one page. However, two problems arose. Googling for a few days doesn't solve it. [forms.py] from django import forms from django.forms import modelformset_factory, ModelForm, DateTimeInput, Select from .models import Supporting SupportingModelFormset = modelformset_factory( Supporting, fields=('date', 'student', 'kinds', 'post_hour', 'teacher', 'comment', 'technician'), extra=1, widgets={'date': forms.DateTimeInput(format=('%Y-%m-%d %H:%M'), attrs={'name': 'date', 'id': 'date', 'autocomplete': 'off', 'class': 'form-control col-sm-12 date'}), 'student': forms.Select(attrs={'id': 'student', 'name': 'student', 'class': 'chosen'}), 'kinds': forms.Select(attrs={'id': 'kinds', 'name': 'kinds'), 'post_hour': forms.TextInput(attrs={'type': 'text', 'class': 'form-control col-sm-3', 'name': 'post_hour', 'placeholder': 'hr'}), 'cteacherrc': forms.TextInput(attrs={'type': 'text', 'class': 'form-control col-sm-12', 'name': 'teacher'}), 'comment': forms.TextInput(attrs={'class': 'form-control position-relative', 'name': 'comment', 'rows': '4'}) } ) [views.py] def add_supporting(request): if request.method == 'GET': formset = SupportingModelFormset(queryset=Supporting.objects.none()) elif request.method == 'POST': formset = SupportingModelFormset(request.POST) if formset.is_valid(): for form in formset: form.save() return redirect('supporting_list') return render(request, 'supporting/add.html', {'formset': formset}) [supporting/add.html] <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer mt-4"> <div class="form-group row"> <label>{{form.date.label}}</label> <div class="input-group"> {{form.date}} </div> </div> <div class="form-group row"> <label>{{form.student.label}}</label> <div class="input-group"> {{form.student}} </div> </div> <div class="form-group row"> <label>{{form.kinds.label}}</label> <div class="input-group"> {{form.kinds}} </div> </div> <div class="form-group row"> <label>{{form.post_hour.label}}</label> <div class="input-group"> {{form.post_hour}} </div> </div> <div class="form-group row"> <label>{{form.teacher.label}}</label> <div … -
How to put the product price with a ManyToManyField between Sellers and Products Table
I want a product price between two table Sellers and Products. Here are my models- class Products(models.Model): name = models.CharField(max_length=60) price= models.IntegerField(default=0) category= models.ForeignKey(Category,on_delete=models.CASCADE,default=1 ) description= models.TextField(blank=True, null= True) image= models.ImageField(upload_to='uploads/products/') def __str__(self): return self.name class Sellers(models.Model): name = models.CharField(max_length=60) products = models.ManyToManyField(Products) description= models.TextField(blank=True, null= True) image= models.ImageField(upload_to='uploads/sellers/') def __str__(self): return self.name Where to put the product price for each seller? -
FilterSelectMultiple | Django Form | widget | Django Template - Not able to see the form, return NoReverseMatch Error
I am trying to build a form, taking input through a FilterSelectMultiple field from Group model My urls.py looks like from django import views as django_views urlpatterns = [ # some other patterns url(r'^jsi18n/', django_views.i18n.JavaScriptCatalog.as_view(), name='javascript-catalog'), ] forms.py looks like from django import forms from django.contrib.auth.models import Group from django.contrib.admin.widgets import FilteredSelectMultiple class MyForm(forms.Form): """Form for assigning groups to new users.""" options = [(group_name, group_name) for group_name in Group.objects.all()] # other fields groups = forms.MultipleChoiceField(required=False,widget=FilteredSelectMultiple("Groups", is_stacked=False),choices=options) class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) def __init__(self, *args, **kwargs): """Init.""" super(MyForm, self).__init__(*args, **kwargs) template looks like {% extends base.html %} {% block head %} {% load staticfiles %} some stuff {% endblock head %} {% block content %} <script type="text/javascript" src="{% url 'jsi18n' %}" > </script> {{ form.media }} <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Submit</button> </form> {% endblock content %} But I am getting error - NoReverseMatch Reverse for 'jsi18n' not found. 'jsi18n' is not a valid view function or pattern name -
Why is my Python for loop running out of memory?
I have a for loop in Python/Django to iterate over a long list of users and create recommendations for them using a saved tensorflow model: def create_recommendations_for_users(): user_ids = User.objects.values_list("id", flat=True) retrieval_model = tf.saved_model.load("tensorflow_models/model") ranking_model = tf.saved_model.load("tensorflow_models/ranking_model") for user_id in user_ids: create_recommendations_for_user(user_id, retrieval_model, ranking_model) def create_recommendations_for_user(user_id, retrieval_model, ranking_model): _, items = retrieval_model([user_id]) for item_id in items[0]: item_id = item_id.numpy() rating = ranking_model.ranking_model( (tf.constant([user_id]), tf.constant([item_id])) ).numpy() Recommendation.objects.create(user_id=user_id, item_id=item_id, rating=rating) The issue is that calling create_items_for_users is causing a memory leak. Why would this happen? items is scoped to the create_items_for_user function, so wouldn't this be garbage collected, as would item_id and rating, each time it gets run? user_ids is a long list of integers, but doesn't grow over time and isn't all that large. I'm not storing a growing list of results anywhere. Why would these functions cause a memory leak? -
Populating a hidden field after form save
I am very new to Django and I wanted some guidance on building this. I have a form that works well right now, but I want to change a functionality. There is a hidden field that doesn't show on the form but is in the model, I want to be able to populate that hidden field based on an entry on the form. I've tried overriding the clean method in the view but that wasn't working. Any guidance would be appreciated, thanks! -
Django Import Export Strip White Space & Additional Condition
I'm using the Django Import and Export plugin and in my Admin.py I need to solve two problems. The excel file I'm uploading has white space at the end of the cells, I need to remove that. This import is uploading test scores, there is no test id in the import to determine if its a different test. However, there is a test date field. I need to be able to get the date field before the import of each row and analyze it to determine if this is an update of the current test data or make a new record signaling this was a different test. I appreciate the help. Here is my admin.py class MindResource (resources.ModelResource): state_province = fields.Field(column_name='state_province', attribute='state_province',widget=ForeignKeyWidget(Student, 'state_province')) def import_row(self, row, instance_loader, **kwargs): # OVERRIDE ERROR TO IMPORT RECORDS (STOPS FAILURE OF IMPORT) import_result = super(MindResource, self).import_row(row, instance_loader, **kwargs) if import_result.import_type == RowResult.IMPORT_TYPE_ERROR: # COPIES VALUES TO DISPLAY ON THE REPORT import_result.diff = [row[val] for val in row] # ADD COLUMN WITH ERROR MESSAGE import_result.diff.append('Errors: {}'.format([err.error for err in import_result.errors])) # CLEAR ERRORS AND MARK TO SKIP import_result.errors = [] import_result.import_type = RowResult.IMPORT_TYPE_SKIP return import_result class Meta: model = Mind clean_model_instances = True import_id_fields = … -
Django Abandoned/Unused Models
I have a models.py file with 6-10 unused models on a Django Project. What do you do with these unused models? Do you delete them (and migrate them out)? Do you just push them to the side and ignore them? -
Present Python variable in HTML Template in Django
I have a value extracted from JIRA API showing a total for a particular project. When I print the value, I can see the correct values and these are clearly being stored in the variable. # Emergency Changes Query jira_emergency_changes = jira.search_issues('labels = new-emerging-audit AND resolution = Unresolved').total # Open Issues Query jira_open_issues = jira.search_issues('project = UTILITY AND status = Open').total # Open JIRA Ticket Total Query jira_open_tickets = jira.search_issues('project = "UTILITY" AND status not in (Closed, Completed, Resolved) ORDER BY created DESC').total I want to add these values to a template page in a <p> tag, but no matter what method I try, it just doesn't render. Could some advice? :)