Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Can't login with Allauth
I tried all login, signup process with usign allauth in Django. But I have this problem: File "C:\Users\Mircal\Desktop\Project\core\urls.py", line 22, in <module> path('accounts/login/', name='account_login'), TypeError: _path() missing 1 required positional argument: 'view' core/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('accounts/login/', name='account_login'), ] I have got apps/accounts/login.py and templates/accounts/login.html I setup this using https://django-allauth.readthedocs.io/en/latest/overview.html What can I do for solution? -
How to plug a function inside django ImageFiled
I'm trying to upload images from Django admin. the files are bigger most of them more than 5 MB, I want to rescale them so the size should be 1 MB before upload. I have a function that could re-scale the image and is working fine, But I'm not sure how to plug that function into ImageField in Django models. def scaled_image(input_image_path, output_image_path, width=600, height=None): image = Image.open(input_image_path) w, h = image.size if width and height: max_size = (width, height) elif width: max_size = (width, h) elif height: max_size = (w, height) else: # No width or height specified sys.exit("Width or height required!") image.thumbnail(max_size, Image.ANTIALIAS) image.save(output_image_path) scaled_image = Image.open(output_image_path) return scaled_image Now how can I change my ImageField so that should work doucment_image = models.ImageField(upload_to='sellerinfo', null=True, blank=True) Help would be appreciated. Thanks -
TemplateDoesNotExist heroku working fine on local
When Deploying to Heroku throws an error TemplateDoesNotExist but it works fine on local -
Django and Celery logs
We have a Django app (with Celery) that process several tens of thousands of http requests per minute. We are getting a huge volume of logs from Django like ip... - - [date...] "POST /url... HTTP/1.0" 200 311 "-" "libcurl-agent/1.0" and logs from Celery like INFO:celery.worker.strategy:Task backend.tasks.my_task_name[62c288f0-63ad-45b5-8abd-bbfe11a8b612] received INFO:celery.app.trace:Task backend.tasks.my_task_name[c633ad89-9e2c-4622-bf50-077d8dcf61b6] succeeded in 0.008994809817522764s: None How can I limit these logs? From one side I want to know that the app works. On another side, it is too much log data. Can I set something like store no more 5 log lines per second exclude errors? -
Different serializers based on user object rights
I'm looking for a way to use different serializers within a ModelViewSet depending on the request.user properties making the call. Case 1: The request.user is the owner of the profile and must use the serializer called 'UserProfileOwnerSerializer' which allows a partial edit of their properties. Case 2: request.user has full control rights over profiles properties and must therefore use 'UserProfileViewEditSerializer' Case 3: request.user has only read rights on user profiles and must use 'UserProfileViewOnlySerializer' which sets all fields to readonly. I created 3 permission checkers also used to check permissions within 'permissions.BasePermission': def haveProfileOwnerRights(request, obj): if (request.user.userprofile.id == obj.id): return True else: return False def haveProfileViewRights(request): roleRightsProfileView = [ 'MA', 'AM', 'ME', 'VI', ] role = request.user.userprofile.role if (role in roleRightsProfileView): return True else: return False def haveProfileViewEditRights(request): roleRightsProfileViewEdit = [ 'MA', 'AM', 'ME', ] role = request.user.userprofile.role if (role in roleRightsProfileViewEdit): return True else: return False class IsOwnerOrHaveProfileViewEditOrViewRight(permissions.BasePermission): def has_object_permission(self, request, view, obj): if (request.user.is_anonymous): return False if (haveProfileOwnerRights(request, obj)): return True if (haveProfileViewEditRights(request)): return True return False class UserProfileViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated, IsOwnerOrHaveProfileViewEditOrViewRight ] queryset = UserProfile.objects.all() def get_serializer_class(self): if haveProfileViewEditRights(self.request): return UserProfileViewEditSerializer if haveProfileViewRights(self.request): return UserProfileViewOnlySerializer # # MISSING SERIALIZERS FOR 'UserProfileOwnerSerializer' # I need to … -
Django - tensorflow: ModuleNotFoundError: No module named '_ctypes'
I'm using tensorflow in a django project, when I try to use tensorflow I'm getting this error: ModuleNotFoundError: No module named '_ctypes' I'm using ubuntu 22.04 and python 3.10 I already tried : sudo apt install libffi-devel but it doesn't work Thank you -
How can I optimze Django Code to only one query request
I have a simple django project which displays previous reservations dates based on id's. However currently there are 2 requests being made. (N+1 sql requests, where N is the reservation’s count) Do you have any idea how i would be able to optimize this code to only 1 query? This is the model.py file from django.db import models class Rental(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Reservation(models.Model): rental = models.ForeignKey( Rental, on_delete=models.CASCADE, related_name="reservations") checkin = models.DateField() checkout = models.DateField() def get_previous_reservation(self): latest_reservation = Reservation.objects.order_by('-checkout').filter( rental=self.rental, checkout__lt=self.checkout).first() if latest_reservation is not None: return latest_reservation.id return '-' def __str__(self): return f"({self.id}, {self.checkin}, {self.checkout})" This is the view.py file -> Where the queries are being made from django.views.generic import CreateView from .models import Reservation from .forms import ReservationForm class HomeView(CreateView): template_name = "index.html" form_class = ReservationForm success_url = '/' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reservations'] = Reservation.objects.all( ).select_related('rental') return context -
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 …