Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Web App - Axios 502 Error - Debugging
I'm not that familiar with Django and Axios, but I'm currently getting a 502 Error. Here's the console error that appears: M {message: 'Request failed with status code 502', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …} Does anybody know what this means or where I should start to debug this? Is this a front end error or a back end error? I tried editing both my API and front end code back to a version that worked before but it's still not working for some reason. I also logged into my server console log but it doesn't seem to be logging any error related to this api call. -
How to show only 5 elements of each foreign ID elements in ORM query?
id comment answer_id question_id 1 some comment 2 1 2 some comment 2 1 3 some comment 42 1 4 some comment 42 1 5 some comment 42 1 6 some comment 42 1 7 some comment 2 1 8 some comment 2 1 9 some comment 2 1 10 some comment 2 1 11 some comment 2 1 12 some comment 42 1 13 some comment 2 1 14 some comment 2 1 15 some comment 2 1 16 some comment 2 1 17 some comment 42 1 18 some comment 42 1 19 some comment 42 1 20 some comment 42 1 21 some comment 42 1 Above is the table of name Comment which contains comments of answers and questions. Note: I have two more tables that is Answer and Question which contains data of question and answer. I want to get the records of only first 5 of each answer_id i.e.,(2 and 42) of that particular question_id i.e., (1). Following is the query I have tried, answer = Answer.objects.filter(question=question_id) answer_comment = Comment.objects.filter(answer_id__in=answer.values('id')) but the above query gives all the data of specific question. -
Use AllAuth authentication to authenticate current user to another API
I'm beginning with Oauth2 authentication with django allauth. I followed this tutorial The authentication with Google OAuth is working Now I'm wondering how to use this authenticated User to use another API that is using Google Oauth too by using information of the already logged in user. I imagine that the process is based on using the AccessToken used at first app authentication to log in the API, API that will validate this accessToken to Google too. But honestly I don't see at all the way to implement this behaviour Is there some explanation or tutorial or documentation describing this king of architecture ? or maybe I'm wrong on the way and there is a better way to do that ? Thank you in advance RV -
Disable DRF throttling for some users
I have a few test users that are used to run integration tests against my Django + DRF application. How can I disable throttling for these users only? Looks like I can override DRF's allow_request() method (see https://github.com/encode/django-rest-framework/blob/99e8b4033efa44930ace40fb48a4d7bcd224f9fb/rest_framework/throttling.py#L109): from rest_framework.throttling import SimpleRateThrottle class CustomSimpleRateThrottle(SimpleRateThrottle): def allow_request(self, request, view): if request.user in {<user1>, <user2>}: return True return super().allow_request(request, view) But I'd rather not choose this approach because it requires me to have to use this base method in all my throttling classes (e.g. UserRateThrottle, AnonRateThrottle, etc.). Is there another way to achieve this? -
How to specify multiple webpack output directories
I have a large django project, with multiple apps, and each application has its own static directory like this /[appname]/static/[appname]/[css, js, or img directory]. I have multiple entrypoints because of this (and because I want to use code splitting), so my webpack config file with two apps looks like this: const path = require('path') module.exports = { entry: { core: './core/static/core/js/base.js', info: './info/static/info/js/base.js', }, output: { filename: '[name]/bundle.js', path: path.resolve(__dirname, 'core', 'static', 'dist'), }, module: { rules: [ { test: /\.css$/i, use: ['style-loader', 'css-loader'], }, { test: /\.(woff|woff2|eot|ttf|otf)$/i, type: 'asset/resource', }, ], }, }; My problem is that instead of sending all the bundled files to the "dist" sub-directory inside my "core" app's static directory I want the output directory (path) to be dynamically generated like this [appname]/static/[appname]/dist. Is there a way to do this? One solution I thought of was to just set the output filename to be '[name]/static/[name]/dist/'. This worked, however, because the output directory wasnt specified any images loaded from the css files were placed in the root directory of my project, not the "dist" sub-directory. -
How to add default fonts to Django-TinyMCE
Like the title states. There is no clear explanation in the django-tinymce documentation on how to add fonts, let alone set a standard font. I use TinyMCE both in my admin as well as a view. See the Documentation here. -
Why we use super().perform_update(serialixer) when we redefining methods?
Why we use super().perform_update(serializer)? But not serializer.save() ? What's the difference? def perform_update(self, serializer): if serializer.instance.author != self.request.user: raise PermissionDenied('Сhange other people\'s content forbidden') super(PostViewSet, self).perform_update(serializer) #serializer.save() -
i am registering user using inbuilt "User" models but user's data is not displaying in "ADMIN panel" why
views.py in auth_system app veiw.py code urls.py in project project urls.py urls.py in app registration form enter image description here i am trying to add users using django built in models "User" i have created a registration view in views.py and saving data in User no error is showing. while clickin on submit button page is redirecting to newpage and when i go to check in admin panel the data is not showing there is no user to display only one user which was created using command - python manage.py createsuperuser -
Loading pickle ML model in Django causes website to freeze
I have a Django application using Apache that runs a website and on the back end, I need to run a machine learning model. I have trained and saved the model using pickle and am storing it in a "ml_models" directory off of the main directory. In my directory, I have urls.py pointing to my function that I am calling to run the model: path('classify', views.classify), in the views.py, I have the function: def classify(request): if request.method == "GET": str_data = request.GET.get("data") dataSplit = str_data.split(",") sendData = dataSplit[4] + "," + dataSplit[5] + "," + dataSplit[6] data = [[float(x) for x in sendData.split(",")]] model_path = settings.ML_ROOT + '/my_model.sav' with open(model_path, 'rb') as f: model = pickle.load(f) prediction = float(model.predict(data)) f.close() r = {"response": str(int(prediction))} return JsonResponse(r)` The data I'm sending is in the form: <mysite>/api/classify?data=1,1.2,42.2,12.3,57.84,0.2,29.67,0.95,3 data[0] = device ID, int data[1] = sensor measurement, float data[2] = sensor measurement, float data[3] = sensor measurement, float data[4] = sensor measurement, float data[5] = sensor measurement, float data[6] = sensor measurement, float data[7] = calculated value, float data[8] = Project ID, int The data comes from a mobile app (Android and iPhone) that is connected via bluetooth to a sensor suite. The … -
raise Http404( django.http.response.Http404: No StartUp matches the given query
newslink migration file from django.db import migrations, models from datetime import date from django.shortcuts import get_object_or_404 NEWSLINKS = [ { "title" :"Redundant Homepage Link", "link": "http://jambonsw.com", "pub_date" : date(2013,1, 18), "startup" : "jambon-software", }, { "title": "Monkey(Wikipedia)", "link": "https://en.wikipedia.org/wiki/Monkey", "pub_date" : date(2012, 7, 22), "startup" : "monkey-software", }, { "title" : "William Shakespeare", "link" : "https://en.wikipedia.org/wiki/William_Shakespeare", "pub_date" : date(2014, 4, 26), "startup" : "monkey-hardware", }, ] def add_newslink_data(apps, schema_editor): NewsLink = apps.get_model('organizer', 'NewsLink') StartUp = apps.get_model('organizer', 'StartUp') for newslink_dict in NEWSLINKS: newslink = NewsLink.objects.create( title = newslink_dict['title'], link = newslink_dict['link'], pub_date = newslink_dict['pub_date'], startup = get_object_or_404(StartUp, slug = newslink_dict['startup'])) def remove_newslink_data(apps, schema_editor): NewsLink = apps.get_model('organizer', 'NewsLink') StartUp = apps.get_model('organizer', 'StartUp') for newslink_dict in NEWSLINKS: newslink = NewsLink.objects.get( title = newslink_dict['title'], link = newslink_dict['link'], pub_date = newslink_dict['pub_date'], startup = StartUp.objects.get( slug = newslink_dict['startup'])) newslink.delete() class Migration(migrations.Migration): dependencies = [ ('organizer', '0004_startup_data'), ] operations = [ migrations.RunPython(add_newslink_data, remove_newslink_data) ] -------------------------------------------------------------------------------------------------- startup migration file from django.db import migrations from datetime import date STARTUPS = [ { "name" : "Arachnobots", "slug": "arachnobots", "contact": "contact@arachnobots.com", "description": "Remote-controlled-internet-enabled" "Spider Robots", "founded_date": date(2014, 10, 31), "tags" : ["mobile", "augmented-reality"], "website" : "http://frightenyourroommate.com/" }, { "name" : "Boundless-Software", "slug" : "boundless-software", "contact" : "hello@boundless.com", "description" : "The Sky … -
Efficiently Paginate Query when using multiple tables Django
I have a model in Django that gets its data from multiple tables. The tables are partitioned externally by another program, which I have no control over. To combat this and be able to query the data, I have a get_model() method to fetch the model class, and iterate over all the partitions then make a list class TagDataBase(BaseModel): tagid = models.IntegerField(primary_key=True) intvalue = models.BigIntegerField(blank=True, null=True) floatvalue = models.FloatField(blank=True, null=True) stringvalue = models.CharField(max_length=255, blank=True, null=True) datevalue = models.DateTimeField(blank=True, null=True) dataintegrity = models.IntegerField(blank=True, null=True) t_stamp = TimestampField() class Meta: managed = False abstract = True def get_tagdata_model(name=None): class TagData(TagDataBase): class Meta: managed = False db_table = name unique_together = (('tagid', 't_stamp'),) verbose_name = 'Tag Data' verbose_name_plural = 'Tag Data' return TagData Then, to actually get the data, whenever I do a query, I do something like this data = [] for p in get_all_partitions(): tags = get_tagdata_model(name=p.pname).objects.filter(tagid=tag.id) data.extend(tags) We have pagination enabled on this view. So it returns max 100 results at a time. However, it seems to query/evaluate all possible data every time. Whereas if I had one giant queryset, it would be sliced by the pagination and evaluate only the slice. But I can't concat the querysets because they're … -
Django project using firebase and postgresql host on heroku
I want to create a Django web app where I will read data from Firebase and save them in Postgresql using the Django backend. I also want to host this app or database in Heroku. Create a Django app Make it live on Heroku Database in firebase Fetch data from Firebase Save Firebase data in the local database using Django -
django.db.utils.OperationalError: ERROR: Endpoint ID is not specified
I'm trying to connect my django project to a neon database, but after modifying the 'DATABASE' section in the settings.py file, I get the following error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: ERROR: Endpoint ID is not specified. Either please upgrade the postgres client library (libpq) for SNI support or pass the endpoint ID (first part of the domain name) as a parameter: '?options=project%3D<endpoint-id>'. See more at https://neon.tech/sni This is how I edited the section (the commented lines are attempts to fix the problem): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'neondb', 'USER': myusername, 'PASSWORD': mypassword, 'HOST': 'myendpointid.eu-central-1.aws.neon.tech', 'OPTIONS': { #'service': 'my_service', #'sslmode': 'verify-full', 'sslmode': 'require', #'project': myendpointid #'endpoint_id': myendpointid }, 'PORT': '5432', } } I consulted https://neon.tech/docs/connect/connectivity-issues but I'm not sure I understand what it's saying. I also tried to search online how to 'upgrade the postgres client library (libpq) for SNI support' as the error message tells me, but with no result. Thanks in advance, hope you can help me -
Disabling allow_unicode in djangot-taggit without modifying the module
I'm using django-taggit and I have a problem that polish symbols like ś, ć, ę... appear in slugs of tags. I want slugs to be ASCII only. Using TAGGIT_STRIP_UNICODE_WHEN_SLUGIFYING = True solves the problem partially. When creating tags they actually change unwanted characters as this: ś -> s but when I create tag in admin, slug gets automatically prepopulated without striping/changing the characters. I would like it to do so. As far only solution I found is modifying source of django-taggit as follows: class TagBase(models.Model): name = models.CharField( verbose_name=pgettext_lazy("A tag name", "name"), unique=True, max_length=100 ) slug = models.SlugField( verbose_name=pgettext_lazy("A tag slug", "slug"), unique=True, max_length=100, allow_unicode=False, ) Precisely allow_unicode=False I was also considering unregistering TagAdmin and switching it to my own. Is there any clean solution that doesn't require modifying django-taggit module? -
django channels WebSocket connection to 'ws://127.0.0.1:8000/' failed:
I'm making a streaming website. I use django channels for this. The first part of the application is a chat in which the name is entered and a room is entered. But when I run the javascript I get an error that the connection failed and the connection is closed according to my reference console.log() . I don't find any problems in my code and chatGPT doesn't find them either. According to chatGPT it may be because my browser does not accept the type of connection through the firewall. I leave my code in case you can help me. Thanks Error in the browser console: WebbSocket connection to 'ws://127.0.0.1:8000/' failed: Line marked as error in the console: webSocket = new WebSocket(endPoint); Javascript: var inputUsername = document.querySelector('#username'); var btnJoin = document.querySelector('#btn-join'); var username; var webSocket; function webSockedOnMessage(event){ var parseData = JSON.parse(event.data); var message = parseData['message']; console.log('message: ', message); } btnJoin.addEventListener('click',()=>{ username = inputUsername.value; if (username == ''){ return; } else{ inputUsername.value =''; inputUsername.disabled = true; inputUsername.style.visibility = 'hidden'; btnJoin.disabled= true; btnJoin.style.visibility = 'hidden'; var labelUsername = document.querySelector('#label-username'); labelUsername.innerHTML = username; } var loc = window.location; //ws Start specify we are using websockets var wsStart = 'ws://'; if (loc.protocol == 'https:'){ wsStart … -
Asynchronous tasks in a django app deployed on heroku using Redis
I am working on a django app. The idea is that the user uploads a list, which can be very huge, the app iterates over the list and processes each item. Problem is that during the iteration, the app is inaccessible. So I tried to make that asynchronous using Django Q and redis. Locally it is working fine, but when deployed to heroku, it does not seem to be working. The Redis worker is running but the iteration is not happening. Following is the part about django Q in my settings.py: # Django-Q Configuration Q_CLUSTER = { 'name': 'DjangORM', 'workers': 4, 'timeout': 500, 'retry': 600, 'queue_limit': 50, 'bulk': 10, 'orm': 'default', 'redis': { 'host': config('REDIS_HOST', default="default"), 'password': config('REDIS_PASSWORD', default="default"), 'port': config('REDIS_PORT', default=32219, cast=int), 'db': 0, }, } Please suggest any solutions or tutorials that I can look at. I am using the Heroku Redis add on and it seems to be running on heroku. -
How to save "Shipping address" to fill it automatically every time I go to Stripe Checkout with Django?
I set shipping_address_collection in Django View as shown below: # "views.py" def test(request): customer = stripe.Customer.search(query="email:'mytest@gmail.com'", limit=1) checkout_session = stripe.checkout.Session.create( customer=customer["data"][0]["id"] if customer.has_more else None, line_items=[ { "price_data": { "currency": "USD", "unit_amount_decimal": 1000, "product_data": { "name": "T-shirt", "description": "Good T-shirt", }, }, "quantity": 2, } ], payment_method_options={ "card": { "setup_future_usage": "on_session", }, }, # ↓ ↓ ↓ Here ↓ ↓ ↓ shipping_address_collection={ "allowed_countries": ['US'] }, mode='payment', success_url='http://localhost:8000', cancel_url='http://localhost:8000' ) return redirect(checkout_session.url, code=303) Then, I can fill Shipping address of Shipping information as shown below but I need to fill it manually every time I go to Stripe Checkout because it is not saved while Payment details is saved with setup_future_usage as shown below: So now, how can I save Shipping address to fill it automatically every time I go to Stripe Checkout? Is there like setup_future_usage for Shipping address to fill it automatically? -
How to set a dirname and file instead of filepath or filename in Django logging?
We are looking to log the path of the file being logged. For example I have the file views.py - this file name is repeated in the many applications of a Django project thus we need the file name to include the app name - polls/views.py On the other hand we don't want to full absolute path.. This is the format line: format": "{levelname}: {message} at {asctime} in {filename} {funcName} {lineno} (process={process: d}, thread={thread:d})" According to this thread we only have the following related options: filename, module, and pathname which do not suffice. Have not found help from Django logging docs Also tried string manipulating with {os.path.dirname(pathname)} but it doesn't appear to parse right We get raise ValueError('Unable to configure ' ValueError: Unable to configure formatter 'verbose' This is the LOGGING snippet from our settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { "**format": "{levelname}: {message} at {asctime} in {filename} {funcName} {lineno} (process={process: d}, thread={thread:d})"**, "style": "{", }, 'default': { 'format': '%(asctime)s - %(levelname)s - %(module)s - %(lineno)d => %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, }, 'handlers': { 'error_file': { 'class': 'logging.handlers.RotatingFileHandler', 'level': 'DEBUG', 'formatter': 'verbose', 'filename': f'logs/error_{datetime.datetime.today().strftime("%Y-%m-%d")}.log', }, 'info_file': { 'class': 'logging.handlers.RotatingFileHandler', 'level': 'INFO', 'formatter': 'verbose', 'filename': … -
Django - passing named parameter to url in template
For some reason I don't understand, when I pass a parameter to my url inside my template, the generated url does not include the parameter keyword "?ts=". To be clearer, the code below generate as href the url my_view20230511 instead of my_view?ts=20230511. What puzzles me even more is that all urls still work : I mean I can access my_view, my_view20230511 and my_view?ts=20230511 my_view and my_view?ts=20230511 have the behaviour I want which is : the page is same for both but for the second I also have the content of some file rendered But I don't need my_view20230511 since I would like this line <a href="{% url 'my_view' ts=ts %}">{{ ts_fmt }}</a> to point to my_view?ts=20230511 urls.py from django.urls import re_path from . import views urlpatterns = [ re_path(r'^my_view(?P<ts>\d+)?$', views.my_view, name = "my_view") ] views.py def my_view(request, ts=""): ts = request.GET.get('ts', "") timestamps = [('20230509', datetime(2023,5,9), ('20230510', datetime(2023,5,10), ('20230511', datetime(2023,5,11)] context = { 'timestamps' : timestamps, 'ts' : ts } if ts != "": with open(f"filepath/that/depends/on/{ts}", "r") as f: lines = f.readlines() context['lines'] = lines return render(request, 'template.html', context) template.html {% for ts,ts_fmt in timestamps %} <p><a href="{% url 'my_view' ts=ts %}">{{ ts_fmt }}</a></p> {% endfor %} {% if msg … -
How to redirect to 2 different app in django, base on the user group from single login url
I have the following scenario: My project has two different Django apps, Dashboard and FrontView, with different user groups. Current login urls are as below: http://127.0.0.1:8000/dashboard/login http://127.0.0.1:8000/front/login However, have a requirement to have a single login url based on the user redirected to the correct app. EG: URL for logging in http://127.0.0.1:8000/login Once logged in, it should redirect the user to two different apps base on the user group. http://127.0.0.1:8000/dashboard/ http://127.0.0.1:8000/front/ How to achieve this in Django project Thanks in advance -
ModuleNotFoundError: No module named 'sendgrid_backend'
when my server is running im getting this error. my settings.py EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" SENDGRID_API_KEY=' my api key' i installed sendgrid by: pip install django-sendgrid-v5 and when i runing pip list i see that: Package Version ------------------ ------- asgiref 3.6.0 autopep8 2.0.2 distlib 0.3.6 Django 4.2.1 django-sendgrid-v5 1.2.2 filelock 3.8.0 pip 23.1.2 platformdirs 2.5.3 pycodestyle 2.10.0 python-http-client 3.3.7 sendgrid 6.10.0 sendgrid-django 4.2.0 setuptools 65.5.0 sqlparse 0.4.4 starkbank-ecdsa 2.2.0 tzdata 2023.3 virtualenv 20.16.6 and i got the same error. -
Django-Pycharm problem on Windows " OSError: no library called "cairo-2" was found "
Django project where I use Pycharm version 2023.1.1 on Windows. But when running the command in the terminal: python manage.py makemigrations or python manage.py migrate or python manage.py runserver It shows error with the following message: raise OSError(error_message) # pragma: no cover OSError: no library called "cairo-2" was found no library called "cairo" was found cannot load library 'C:\Program Files\GTK3-Runtime Win64\bin\libcairo-2.dll': error 0x7e cannot load library 'libcairo.so.2': error 0x7e cannot load library 'libcairo.2.dylib': error 0x7e cannot load library 'libcairo-2.dll': error 0x7e I have already reinstalled GTK3 and already defined the PATH in the GTK3 environment variables. -
Django debug toolbar not rendering properly
I'm trying to install the django debug toolbar. It does show up, but it renders really weirdly and doesn't match how I've seen it show up for other developers. Also, when I click on the different panel options, nothing happens. Below is a screen shot of what I'm seeing. debug toolbar In settings.py I have the following code: DEBUG = True INSTALLED_APPS = [..., 'debug_toolbar', ...] MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware', ...other middelware] DEBUG_TOOLBAR_CONFIG = { 'SQL_WARNING_THRESHOLD': 100, # milliseconds 'SHOW_TOOLBAR_CALLBACK': lambda x: True } if DEBUG: import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + "1" for ip in ips] + \ ['My REMOTE_ADDR', '127.0.0.1'] import mimetypes mimetypes.add_type("application/javascript", ".js", True) In urls.py, I also have the following: if settings.DEBUG: urlpatterns += [ path('__debug__/', include('debug_toolbar.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I'm using version 4.0 of the debug toolbar. Any suggestions? -
Django Models Tree Structure
Is there a possibility to create Tree-Like Structures in Django. I want to create a model called Workbook which contains different Worksheets. I also want to be able to switch in between the worksheets and edit them. The structure should be similar to excel. I already looked into django-mptt, but I am not sure if i should familiarize myself with it, since I am a beginner Thanks in advance -
Split a Django Queryset into subquerysets
I have a model with around 4 million objects. I would like to write a function which can split the all objects of a queryset into sub querysets of length 100000 objects. e.g. all_objects = MyModel.objects.all() # do the splitting to achieve something like below query_set1 = all_objects[0:100000] query_set2 = all_objects[100000:200000] # and so on until all objects are within query_setn = all_objects[3 900 000:4 000 000]