Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Plotly in Django should I use Dash?
I am a reasonably experienced amateur python coder. With this site's help I have fought my way through, celery, channels, websockets, NGINX, docker etc etc to produce a website which controls my astronomy dome and some house automation. Part of the astronomy setup is a 3rd party weather station which collects data (temperature, wind speed, humidity, brightness, rain etc) and distributes a json file every 15 secs. I have successfully coded pyhton / Django / Plotly to collect the data and produce one graph (temperature). I have successful embedded this graph in a webpage. The next step is to add a drop down box as a choice mechanism for what data (e.g. temperature or bightness) to show in the graph. I think I can do this with websocket calls. Should I use Dash instead ? I have found plotly relatively easy to use and I am attracted to the idea of using the bootstrap plugin to manage bootstrap in python code as opposed to in an html page. but Problem: installing Django-Plotly-Dash v2.0 downgrades django (v4.0.5 to 3.2.13), daphne (v3.0.2 to 2.5.0) and channels (v3.0.4 to 2.4.0). I'm not sure if that is going to 'break' anything but since everything … -
Store extra data like refresh_token when signing up via access_token
I am trying to signup using access token for google. My frontend is next.js with next-auth.js fetching the access_token, refresh_token, etc. I am using python social auth with Django to persist the user information. I use the access_token provided by next-auth to signup the user in Django. How do I make sure that the other response fields like refresh_token, and expires are saved in the Django DB? I can pass the required fields from next-auth to an API in Django but not sure what the expected format is. https://python-social-auth.readthedocs.io/en/latest/use_cases.html#signup-by-oauth-access-token @psa('social:complete') def register_by_access_token(request, backend): # This view expects an access_token GET parameter, if it's needed, # request.backend and request.strategy will be loaded with the current # backend and strategy. token = request.GET.get('access_token') user = request.backend.do_auth(token) if user: return HttpResponse(json.dumps(get_tokens_for_user(user))) else: return HttpResponse('Unauthorized', status=401) def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) update_last_login(None, user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } -
Pass Django list as argument to Javascript
I have a list passed through the context into the html page of a Django project which I want to read inside of a .js which contains chartjs code. The problem is that .js is reading as string and not as a list/array. views.py def index(request): context = { "data": [1, 2, 3, 4, 5]} return render(request, 'index.html', context) Then, in the html page I have to pass the {{ data|safe }} to a javascript like so: <script src='{% static "js/chart.js/linechart.js" %}' var label = "fakelabel"; var index = {{ data|safe }}; ></script> Inside the .js I'm reading the 'index' input as: document.currentScript.getAttribute("index") How can I fix this? ('label' is read correctly as str indeed). -
Pylance, functions not defined
I have a simple code with 3 functions. the first one get some values from the 2 others to check some conditions, but I get an error from Pylance saying the functions sub1 and sub2 are not defined. any clues? @staticmethod def main_test() var1 = sub1() if not var1: return ('test1 not even') var2 = sub2() if not var2: return ('test2 not even') return True @staticmethod def sub1(): test = random.randint(1, 10) if (test % 2)==0: return True return ( str(test) + 'is Odd') @staticmethod def sub2(): test = random.randint(1, 10) if (test % 2)==0: return True return ( str(test) + 'is Odd') -
Template variables doesn't updates after redirect in Django?
I am building simple django app where I want to do some parsing when user click button on the frontend. I have template variable {{ parsing }} which I am using inside index.html to disable button for parsing when user click on it <div class="btn-group mr-2" role="group" aria-label="Parsing group"> <button class="btn btn-dark btn-lg" id="parseButton" {% if parsing %} disabled {% endif %}> <i class="fa fa-terminal gradient-text"></i> <span class="gradient-text">| Parse</span> </button> </div> Next what I do is JQuery method which sends ajax request to my backend to initialize variables for parsing and method from views.py returns redirect to the same page (index.html). $('#parseButton').click(function () { $.ajax({ type: 'POST', url: 'initialize_parsing/', headers: {"X-CSRFToken": $.cookie("csrftoken")}, data: {} }); Then my views.py: def initialize_before_parsing(request): if request.method == 'POST': frontendTracker = FrontendTracker() frontendTracker.progress = 0 frontendTracker.parsing = True return redirect("index") class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): frontendTracker = FrontendTracker() context = super(IndexView, self).get_context_data(**kwargs) context["showAnnotation"] = frontendTracker.showAnnotationButton context["parsing"] = frontendTracker.parsing context["progress"] = frontendTracker.progress return context and urls.py urlpatterns = [ path('', IndexView.as_view(), name="index"), path("initialize_parsing/", initialize_before_parsing, name="initialize_before_parsing"), ] Finally what is bother me is that when I send that ajax request and everything works fine when my page being redirected {{progres}} template variable isn't changed … -
Python NameError: name '_mysql' is not defined
I am trying to have a working ubuntu server with Python, Django and MySQL. But when I switch from SQLite to MySQL and trying to reach my server I get the following error "NameError: name '_mysql' is not defined". It does work if I run the project in virtual environment mode with the command "python manage.py runserver". The database is also correctly created with the command "python manage.py migrate". This does not work when I try to reach my URL. I think there is an issue with my virtual host file, but I am unable to see it. Any help would be appreciated! Virtual host file: <VirtualHost *:80> ServerName mysite.com ServerAlias www.mysite.com WSGIDaemonProcess myprocess python-path=/var/www/myproject/myname:/var/www/myproject/myname/venv/lib/python3.7/site-packages WSGIProcessGroup myprocess WSGIScriptAlias / /var/www/myproject/myname/myproject/wsgi.py <Location / > Order deny,allow Deny from all # ek Allow from ${IP_USER1} Allow from ${IP_USER2} </Location> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> The error log: mod_wsgi (pid=55852): Failed to exec Python script file '/var/www/myproject/wsgi.py'. mod_wsgi (pid=55852): Exception occurred processing WSGI script '/var/www/myproject/myname/myproject/wsgi.py'. Traceback (most recent call last): File "/var/www/myproject/myname/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: cannot import name '_mysql' from partially initialized module 'MySQLdb' (most likely due to a circular import) (/var/www/myproject/myname/venv/lib/python3.7/site-packages/MySQLdb/__init__.py) During handling of the … -
How to get the Current User IP in Python / Django
I am trying to capture the IP Address and the System Name of the current Login user during the login Process. I Use following code for the same: import socket system = socket.gethostname() IPAddr = socket.gethostbyname(system) It works fine in Local Server but when I push to Server it takes the server name and server IP instead of user IP. -
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 = …