Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add unlimted values to a django model's attribute
I want to add an attribute to a django model as much as the user wants to. For example I want to add a few academic degrees class Employer(models.Model): academic_degree = models.CharField(max_length=100, null=True, blank=True) with this code We can just add one degree and if a person has more, he or she can't add them. I need a way to add as much degrees as i want in django forms. Is that possible? -
Using Bootstrap tab view in Django
I am trying to implement tabs using Django and Bootstrap. The following code does not switch tabs properly and the contents of all tabs are displayed on the active tab. Also, tab switching is not working even thought URL is changing Please let me know how I can switch tabs without any problems. Code <div class = "company-info-tab"> <div class="container"> <!-- Nav tabs --> <ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#home">Home</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#menu1">Baby computer Man</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#menu2">Menu 2</a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane container active" id="home">A "Hello, World!" program generally is a computer program that outputs or displays the message "Hello, World!". Such a program is very simple in most programming languages, and is often used to illustrate the basic syntax of a programming language. It is often the first program written by people learning to code.</div> <div class="tab-pane container fade" id="menu1">The Manchester Baby, also known as the Small-Scale Experimental Machine, was the world's first electronic stored-program computer. It was built at the University of Manchester, UK, by Frederic C. Williams, Tom Kilburn, and Geoff Tootill, and ran its first program on … -
django-python unsupported operand type(s) for -: 'float' and 'decimal.Decimal'
I don't know how to fix this, I already tried to change int to float and it didn't work, I need help :(, if anyone has any ideas I'd appreciate it '''def get_total(self): # recupera desconto e atribui 0 se não existir desc = Venda.objects.filter(numero_ven=self.numero_ven).values_list('desconto_ven') or 0 d = 0 if None in desc[0] else sum(map(lambda d: d[0], desc)) # recupera itens da venda e atribui 0 se não existir qs = self.vendas_det.filter(num_ven_ite=self.numero_ven).values_list( 'unitario_ite', 'quantidade_ite') or 0 t = 0 if isinstance(qs, int) else float(sum(map(lambda q: q[0] * q[1], qs))) - d return f'R$ {number_format(t, 2)}''' -
Simplifying flags when filtering models
I have a user model that has a set of notifications: class User(AbstractUser): # Notification flags send_to_all = models.BooleanField(default=True) send_to_me = models.BooleanField(default=True) send_to_friends = models.BooleanField(default=True) # ... I am passing them from front-end to my views where I trigger send_notifications function. # ... def update(self, request, *args, **kwargs): # ... send_notifications(request.data.get('send_to_all', False)) # ... And in the send_notifications I want to query User.objects.filter() and inlcude only those that have the flag passed from front-end set to True. My question is: Is there any way to simplify it? I am asking because there is many notifications options, like 20. And currently my code has 20 ifs: def send_notifications(flag): if flag == 'send_to_all': users_to_send = User.objects.filter(send_to_all=True) if flag == 'send_to_me': users_to_send = User.objects.filter(send_to_me=True) if flag == 'send_to_friends': users_to_send = User.objects.filter(send_to_friends=True) if flag == 'another_send_flag': users_to_send = User.objects.filter(another_send_flag=True) if flag == 'another_send_flag': users_to_send = User.objects.filter(another_send_flag=True) Thanks! -
How to upload data like images, PDFs and excel files in DevExtreme File Manager?
I have an app in which I want to show the replica of the google drive folder structure in my app. I can get data from google drive via its API. But I do struggle in uploading that data to the FileManager library of DevExtreme. Also how to send the data obtained from backend via an AJAX request (POST|GET). The file obtained from the API: from pydrive2.auth import GoogleAuth from pydrive2.drive import GoogleDrive gauth = GoogleAuth() gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Authenticate if they're not there gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds.txt") img = drive.CreateFile({'id': file_id}) img.GetContentFile('sample.jpg') Code for creating the file manager from Javascript: data = [ { name: "MyFile.jpg", size: 1024, dateModified: "2019/05/08", thumbnail: "/thumbnails/images/jpeg.ico", isDirectory: true, items: [ // ... // Nested data objects with the same structure // ... ] } ] new DevExpress.ui.dxFileManager(document.getElementById("file-manager"), { "fileSystemProvider": data, "itemView": { "mode": "thumbnails" }, "permissions": { "copy": true, "create": true, "delete": true, "download": true, "move": true, "rename": true, "upload": true }, "rootFolderName": "PayUP", "rtlEnabled": false, "currentPath": path, onSelectionChanged: function (e) { console.log(e) } }); The thing I want … -
How to perform sum aggregation on n number of documents after sorting records (descending) ? elastic
{so, i want latest 30 document between 20/6 to 20/4 and perform the sum aggregation on field duration_seconds of those 30 latest doc. we had tried multiple aggregation on that like top_hits, terms for sorting but then we got the sum of all doc between 20/6 to 20/4} "aggs": { "videosession": { "sampler": { "shard_size":30 }, "aggs": { "sum_duration_seconds": { "sum": { "field": "duration_seconds" } } } } } }``` -
django-tenants: Python shell with specific tenant
I want to use "./manage.py shell" to run some Python commands with a specific tenant, but the code to do so is quite cumbersome because I first have to look up the tenant and then use with tenant_context(tenant)): and then write my code into this block. I thought that there should be a command for that provided by django-tenants, but there isn't. -
React i18next doesn't display translation after running npm build
React i18next fails to fetch translation from the JSON file after running the build command. Note, everything works fine without the build in react localhost:3000 I'm using React build file in Django. I checked a similar issue but the solution didn't work for me : Using i18next for a react production build causes the translation to display only strings index.js : import React, {Suspense} from 'react'; import ReactDOM from 'react-dom'; import i18n from "i18next"; import { initReactI18next } from "react-i18next"; import App from './App'; import 'bootstrap/dist/css/bootstrap.min.css'; import LanguageDetector from 'i18next-browser-languagedetector'; import Backend from 'i18next-http-backend'; import './index.css'; const languages = [ { code: 'fr', name: 'Français', country_code: 'fr' }, { code: 'en', name : 'English', country_code: 'en' }, { code: 'ar', name: 'العربية', country_code: 'ly', dir: 'rtl' } ] i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) // passes i18n down to react-i18next .init({ lng: 'en', react: { useSuspense: false, wait: true, }, // the translations // (tip move them in a JSON file and import them, // or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui) supported: ["en", "fr", "ar"], fallbackLng: "en", detection: { order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'], caches: ['cookie'], }, debug: false, whitelist: languages, interpolation: { escapeValue: false, // not needed … -
Django get the current email of the user by default in a different serializer based on the selected "userid"
I was wondering what the correct way is to get the current email of the user by default in a different serializer based on the selected "userid". I have tried many examples from the ModelSerializer docs but without success. serializers.py from rest_framework import serializers from ticker.models import Ticker from users.models import NewUser from rest_framework.permissions import IsAuthenticated from alerts.models import SectionAlerts from users.serializers import UserlistSerializer from rest_framework.fields import CurrentUserDefault class TickerSerializer(serializers.ModelSerializer): class Meta: model = Ticker fields = "__all__" class UserlistSerializer(serializers.ModelSerializer): class Meta: model = NewUser fields = "__all__" class AlertsSerializer(serializers.ModelSerializer): ticker = TickerSerializer(read_only=True) email = UserlistSerializer(read_only=True) ticker_id = serializers.SlugRelatedField( queryset=Ticker.objects.all(), source="ticker", slug_field='crypto', write_only=True ) class Meta: model = SectionAlerts fields = "__all__" models.py from django.db import models from ticker.models import Ticker from django.conf import settings from import_export.resources import ModelResource from import_export.fields import Field from users.models import NewUser from django.core.mail import EmailMessage class SectionAlerts(models.Model): id = models.AutoField(primary_key=True) # auto increment field valuenow = models.FloatField(null=True, blank=True, default=None) valuealarm = models.FloatField(null=True, blank=True, default=None) user = models.CharField(max_length = 40,blank=True, null=True) userid = models.ForeignKey( NewUser, related_name='userid', blank=True, null=True, on_delete=models.CASCADE, ) email = models.ForeignKey(NewUser, blank=True, null=True, on_delete=models.CASCADE) ticker = models.ForeignKey(Ticker, blank=True, null=True, on_delete=models.CASCADE) -
Django Rest Framework complex SQL query
I was asked to create the backend of a project using Django (the frontend is angular). So I thought about using rest framework but I'm a total beginner and raw sql queries are needed for this project. To be more precise it's a complex query that needs many tables: they provided the sql script that I need to use it directly. My question is does rest framework allow such raw queries (because I was not able to find a tutorial about that) or do I need something else? -
How to upload file to AWS S3 with Django running on Heroku?
I have an app deployed on Heroku. I followed the manual by link to set up static files uploading to S3, and it works. And now I need to upload the CSV file, that was created by the celery task and upload it to S3. The problem is that the Heroku file system is read-only and I can not save a file on it. Hence, I get an error FileNotFoundError: [Errno 2] No such file or directory: 'tmp/a30113c5-bbbc-4432-9826-3918e547d407.csv' How do I? @app.task def upload_file(file_name, bucket, object_name=None): """Upload a file to an S3 bucket.""" # If S3 object_name was not specified, use file_name if object_name is None: object_name = os.path.basename(file_name) # Upload the file s3_client = boto3.client("s3") try: response = s3_client.upload_file(file_name, bucket, object_name) except ClientError as e: logging.error(e) return False return True @app.task def make_csv(data: List[Any], task_id: str): """Produce csv file with generated fake data and name it as task id.""" headers: List[str] = ["name", "phone", "email"] file_path = os.path.normpath(f"tmp/{task_id}.csv") with open(file=file_path, mode="w", encoding="UTF-8", newline="") as csv_file: writer = csv.writer( csv_file, delimiter=";", quotechar='"', quoting=csv.QUOTE_MINIMAL ) writer.writerow(headers) writer.writerows(data) return csv_file @app.task(bind=True) def generate_fake_data(self, total: int): """Generate fake data function.""" fake_data: List[Any] = [] for _ in range(total): name = fake.name() phone = … -
Import "faker" could not be resolved (PylancereportMissingImports)
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() #FAKE POP SCRIPT import random from first_app.models import Topic, AccessRecord, Webpage from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Market', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name = random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): #Get the topic for the entry top = add_topic() #Create the fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() #Create the new webpage entry webpg = Webpage.objects.get_or_create(topic = top,url = fake_url, name = fake_name)[0] #Create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create(name = webpg, date = fake_date)[0] if __name__ == '__main__': print("populating script!") populate(20) print("populating complete!") The code executes but does nothing. I've already try uninstall faker and install it again, install older versions, I tried to install with pip and anaconda as well but none of these worked. I would appretiate any help. -
Django rest framework custom Token (send User object with the token access and refress)
I am trying to create a custom token to send the user object alongside the access and refresh. token_serializer.py from rest_framework_simplejwt.serializers import ( TokenObtainSerializer, RefreshToken, api_settings, update_last_login, ) from django.core import serializers from app.models.user import AppUser class TokenSerializer(TokenObtainSerializer): @classmethod def get_token(cls, user): return RefreshToken.for_user(user) def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data["refresh"] = str(refresh) data["access"] = str(refresh.access_token) serialized_app_user = serializers.serialize("json", Appuser) app_user = serialized_app_user .objects.filter(pk=self.user.id).first() if app_user: data["user"] = app_user else: data["user"] = None if api_settings.UPDATE_LAST_LOGIN: update_last_login(None, self.user) return data token_view.py from rest_framework_simplejwt.views import TokenViewBase from app.api.serializers import TokenSerializer class TokenView(TokenViewBase): serializer_class = TokenSerializer This code led to this error: 'ModelBase' object is not iterable Should I add queryset to the view class? If yes, what model should I add? -
Django add custom action to router without adding method
Assume a ModelViewSet. Intention is to add a new action to the ModelViewSet just by returning a serializer and not defining a new action/method. Here is the code example: class ABViewSet(RGBaseViewSet): queryset = AB.objects.filter(~Q(status="Executed")) permissions_classes = IsAuthenticated def get_serializer_class(self): if hasattr(self, "action"): if self.action == "list": return ABSerializer elif self.action == "retrieve": return ABDataSerializer elif self.action == "mark_as_executed": return ABExecuteSerializer If an @action(detail=True) mark_as_executed method is not added, now is there any way router can return data using this serializer on mark_as_executed being called and the view / method not being defined? If the action / view is defined all it will do is to return this serializer data. So why add that view if we can make it work like the buildin views in the ModelViewSet. Thank you. -
Why won't my env recognise django rest framework
When I switch the interpreter to global, it seems to be fine, but is not working when using a env. Even though everything is installed correctly on both? I also have everything correct in my settings.py and urls.py from rest_framework.decorators import api_view from rest_framework.response import Response def getRoutes(request): routes = [ 'GET /api' 'GET /api/rooms', 'GET /api/rooms/:id' ] -
Querying threaded related objects
I have two models : WorkflowStep and WorkflowStepPR. (PR stands for prerequisite). class WorkflowStep(BaseModel): name = models.CharField(max_length=200) workflow = models.ForeignKey('Workflow', on_delete=models.CASCADE) allowed_status = models.ManyToManyField('WorkflowStepStatus', related_name='workflow_step') default_status = models.ForeignKey('WorkflowStepStatus', blank=True, null=True, on_delete=models.SET_NULL) recheck_on_new_version = models.BooleanField(default=False) watch_folder = models.BooleanField(default=False) def __str__(self): return self.name class Meta: ordering = ['created_on'] class WorkflowStepPR(BaseModel): PR_for = models.ForeignKey('WorkflowStep', related_name='PR_for', on_delete=models.CASCADE) PR_step = models.ForeignKey('WorkflowStep', related_name='as_PR_step', on_delete=models.CASCADE) PR_step_status = models.ForeignKey('WorkflowStepStatus', on_delete=models.CASCADE) def __str__(self): return "{} 's PR - {}".format(self.PR_for, self.PR_for.workflow) class Meta: ordering = ['created_on'] Every WorkflowStep has a prerequisite which is maintained via WorkflowStepPR model. Now assume that I have the below scenario: Every box represents a workflow step. Every arrow connecting two boxes shows pre requisite relation (i.e. box on the right of the arrow is dependent on the box on the left of the arrow). For example : "B" is the pre requisite for "C" and "D". I want to find all the steps which are directly or indirectly related to Step B. Directly related : C, D Indirectly Related: E (related to C), G (related to C), H(related to D), J (related to H) How can I write a query the to get this? I have tried the following @receiver(pre_save, sender=WorkflowInstanceStep) def status_of_workflowInstanceStep_updated(sender, instance,**kwargs): if … -
Github Actions abnormal post request time (19s) Django 4.0.4 DRF
First picture is in github actions (19s exec time) Second picture is in my local terminal (0.05s) For some reason this is only with post requests I checked the execution time in the view (section influenced by developer) and it's ok on both. The issue is between when the request is returned from the view and the get_response() call in the middleware, I'm not sure how to debug this as profiling library code in github actions is difficult? Please advise me on what you would do in this situation. -
Django Rest - 405 DELETE Method Not Allowed
I have a problem for several days now. Here the model in question : class Contributor(models.Model): """Model defining a contributor""" user = models.ForeignKey(to=User, on_delete=models.CASCADE, blank=True, null=True) project = models.ForeignKey(to=Project, related_name="project_contributor", on_delete=models.CASCADE, blank=True, null=True) permission = models.CharField(max_length=16, choices=[(permission.name, permission.value) for permission in enums.ProjectPermission], default="ALL") role = models.CharField(max_length=16, choices=[(role.name, role.value) for role in enums.ProjectRole], default="AUTHOR") def __str__(self) -> str: return f"Contributor: {str(self.user)}" views.py : class ContributorViewSet(viewsets.ModelViewSet): serializer_class = ContributorSerializer permission_classes = [IsAuthenticated] def get_queryset(self): """return the contributors list of the project""" return Contributor.objects.filter(project=self.kwargs.get('project_pk')) def create(self, request, *args, **kwargs) -> Response: """ Add contributor to a project If user added already in this project return 400 """ project = Project.objects.get(pk=self.kwargs.get('project_pk')) serializer = ContributorSerializer(data=request.data) user = request.data['user'] if Contributor.objects.filter(user=user).filter(project=project).exists(): return Response('This user is already a contributor of this project', status=status.HTTP_400_BAD_REQUEST) else: if serializer.is_valid(): serializer.save(project=project) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and urls.py : router = DefaultRouter() router.register(r"projects", views.ProjectViewSet) project_router = routers.NestedSimpleRouter(router, r"projects", lookup="project") project_router.register(r"issues", views.IssueViewSet, basename="issues") project_router.register(r'users', views.ContributorViewSet, basename='users') issue_router = routers.NestedSimpleRouter(project_router, r"issues", lookup="issue") issue_router.register(r"comments", views.CommentViewSet, basename="comments") urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), path('', include(project_router.urls)), path('', include(issue_router.urls)), path('signup/', RegisterView.as_view(), name='signup'), path('login/', TokenObtainPairView.as_view(), name='obtain_tokens'), path('login/refresh/', TokenRefreshView.as_view(), name='refresh_token'), ] I use Postman for testing endpoints and i have 405 DELETE Method Not allowed I … -
How I can concat strings in Django template?
I'm trying to localize a component with get_current_language and I need to pass the language_code inside a filter: {% get_current_language as LANGUAGE_CODE %} {{ field|set_data:'flatpickr:{"locale": LANGUAGE_CODE}' }} but set_data argument is a string. How I can achieve this? -
TemplateDoesNotExist on Django Site
I am currently coding a webpage using django but there when I run python server, a TemplateDoesNotExist error pops up. Here are my template Django settings: DEBUG = True ALLOWED_HOSTS = ['*'] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'wiki2.wsgi.application' How do I fix this? -
Does 'Docker-compose build' run pip as root?
I ran docker-compose build as a non-root user from the terminal of my IDE with activated virtual environment. When building the service relative to my Django app, and installing requirements.txt I got the red message warning about the well known dangers of running pip as root, immediately followed by pip installing everything in requirements.txt. Is it safe and normal behavior because it is in a container? I'm new to orchestrator so I'm asking for confirmation. -
Django model filter elements
I have four models as follows: class modelA(models.Model): name = models.CharField(...) class modelB(models.Model): date = models.DateTimeField(...) A = models.ForeignKey(modelA, ...) class modelC(models.Model): email = models.CharField(...) B = models.ForeignKey(modelB, ...) class modelD(models.Model): uid = models.CharField(...) C = models.ForeignKey(modelC) Given modelA element id, I have to filter modelD elements based on that id. But I am not sure about how to do that. I appreciate any ideas! -
Making my Django Endpoint Restricted so that only I can access it
I'm very new to websites. I'm trying to process payments using Stripe in a JS file, and this file is static meaning it is public. I'm trying to take the part that makes an API request with a secret key and move it to the backend and then call the backend to receive the response that comes from using the secret key. However, currently any person is able to make the request, which defeats the purpose of what I am doing. def payment(request): return render(request, 'interface/about.html') def get(self, request, *args, **kwargs): return(HttpResponse("laterthere")) urls.py path('payment', views.payment, name="payment") JS: var resp1 = await fetch('https://url.com/payment', { method: 'GET' }); Is there any way to do this? If suggesting a better direction to go in please do provide resources. -
Writing Integration Test of a Django ListView
How to write an integration test of the following list view in django? I need an example. class HomeView(ListView): model = Donor template_name = 'recipient/home.html' context_object_name = 'donors' paginate_by = 10 def get_queryset(self): form = self.request.GET.get('q') if form: return Donor.objects.filter( Q(name__icontains=form) | Q(location__icontains=form) | Q(sex__icontains=form) | Q(age__icontains=form) | Q(blood_group__icontains=form) ).order_by('id') queryset = Donor.objects.all().order_by('id') return queryset def get_context_data(self, **kwargs): kwargs['q'] = self.request.GET.get('q') return super().get_context_data(**kwargs) -
Django - Get input of Radio buttons in a loop
I need a page for absence control, where there are looped over all users and with each user is displayed 3 radio buttons : present, absent and allowed_absent. After it is filled in for each user, it should be submitted. This is the important part of my code: HTML baksgewijs_attendance.html <form class="createattendance-form" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} {% for user in users %} {{ user }} <div class="form-group"> <div> {{ form.attendance}} {{ form.attendance.errors }} </div> </div> {% endfor %} <br> <div class="form-group"> <button type="submit" class="btn btn-primary save"> Save absence </button> </div> </form> Models.py class Attendance(models.Model): attendance = models.CharField(max_length=13) forms.py attendance_choices = ( ('absent', 'Afwezig'), ('allowedabsent', 'Geoorloofd afwezig'), ('present', 'Aanwezig'), ) class CreateAttendance(forms.ModelForm): class Meta: model = Attendance fields = ['attendance'] widgets = { 'attendance': forms.RadioSelect(choices=attendance_choices) } views.py def baksgewijs_attendance(request): peloton = Peloton.objects.all() users = User.objects.all() if request.method == "POST": form = CreateAttendance(request.POST, request.FILES) if form.is_valid(): form.save() message = messages.success(request, ("De aanwezigheid is opgeslagen")) return HttpResponseRedirect(reverse("baksgewijs_index"), { "message" : message }) else: return render(request, 'baksgewijs/baksgewijs_attendance.html', {"form": CreateAttendance}) User.objects.all gives all user names. The problem is: in this way I can only select one option in total, while I want to be able to select the absence per …