Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid redirect_uri in instagram oauth
I am using python django and django-allauth to implement oauth to instagram. I think I have set all the required things in instagram app setting and got the application id and secret. This is my app setting and I have added in my project to work with this configuration. This is my views.py from django.views.generic import TemplateView from allauth.socialaccount.models import SocialAccount class ConnectInstagram(TemplateView): template_name = 'connect.html' And connect.html file looks like this {% load socialaccount %} <a href="{% provider_login_url 'instagram' %}"> Connect with Instagram </a> I have already registered social applications in django admin site with site and application id and secret. This is my settings.py file import os from dotenv import load_dotenv from pathlib import Path load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent INSTAGRAM_APP_ID = os.getenv('INSTAGRAM_APP_ID') INSTAGRAM_APP_SECRET = os.getenv('INSTAGRAM_APP_SECRET') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['41b3-107-155-105-218.ngrok-free.app'] CSRF_TRUSTED_ORIGINS = ['https://41b3-107-155-105-218.ngrok-free.app'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 3rd party 'django.contrib.sites', 'allauth', … -
How to edit claims in ID Token supplied with openid scope in django Oauth toolkit?
When working with Django OAuth Toolkit, using OIDC if you supply openid as the scope in request you get a id_token with access token. This ID Token can initially be used to identify the user you have got access token for and also create a session. { "aud": "audience", "iat": 1681801110, "at_hash": "hash of included access token", "sub": "1", "given_name": "Dushyant", "preferred_username": "dsh", "iss": "authEndpointurl", "exp": 1681837110, "auth_time": 1681567804, "jti": "tokenid" } But I wish to modify the claims in this JWT ID Token, it reveals the primary key of the database of Authorization Server as the unique id of the user which i don't want in the claim called sub. I want to use another unique key as the value of sub claim. I tried overriding the response a Custom Backend: class CustomOAuthLibCore(OAuthLibCore): def __init__(self, server): super().__init__(server) def create_token_response(self, request): response_data = super().create_token_response(request) #Modify the response here return response_data And added this as the Custom Backend in the settings. "OAUTH2_BACKEND_CLASS":"pathto.CustomOAuthBackend", I haven't written any modification code for the response here since the token here is already created. I want to intercept this at earlier stage where the claims dict is being made. Where and how can I achieve this … -
How to insta load css files
I`m using select2 in my django project and i override some css styles in my own style.css which i load in header And when you refresh page or load page, page shows me default css styles from this package for like 0.5 seconds but for user this is really a lot and im wondering how to load css styles instant or something like that I know that i can add my custom css style in my settings like SELECT2_CSS =['custom_css.css',] but it will delete all css styles from original css How can i solve that problem I load my custom css like this template.html <link rel="stylesheet" href="{% static 'css/django-select2/select2-theme.css' %}"> <script> $(document).ready(function () { $("#id_presence_info__object_presence").select2(); }); </script> -
Djnago path attribute is set to root "/"
I have no idea how to fix it. The URL path that the cookie is valid for can be specified. If the domain and path match, then the cookie will be sent in the request. If the path attribute is set too loosely, then it could leave the application vulnerable to attacks by other applications on the same server If the path attribute is set too loosely, then it could leave the application vulnerable to attacks by other applications on the same server which may help attacker to establish the authenticated session with other applications hosted under default directory Set the appropriate path in cookie interface I have tried doing this in settings.py CSRF_COOKIE_PATH = '/test/' but if 'mydomain/test' path exists then only it works for this path. otherwise for any other path, it do not show csrf_token and when I keep it default CSRF_COOKIE_PATH = '/' it gives as below screenshot cookies section I tried CSRF_COOKIE_PATH = '/test/' what I actually want is to change path from '/' to any other path if I hit any path -
Download the file from the server or output an error if there is one
I have something like this Python code: with open('test.bin', 'rb') as file: file_content = file.read() response = HttpResponse(file_content, content_type='application/octet-stream') response['Content-Disposition'] = f'attachment; filename=test.bin' return response There may not be a file, so you should return an error somewhere, but how to do it so that it can be read on Ajax and output to the user. $.ajax({ url: 'test', type: 'GET', headers: { 'X-CSRFToken': getCookie('csrftoken'), }, xhrFields: { 'responseType': 'blob' }, success: function(data, status, xhr) { var contentDisposition = xhr.getResponseHeader('Content-Disposition'); var matches = /filename=([^;]+)/ig.exec(contentDisposition); var fileName = (matches[1] || 'untitled').trim(); var blob = new Blob([data], {type: xhr.getResponseHeader('Content-Type')}); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); }, error: function(xhr, status, error) { }, }); But the fact is that because of the xhrFields field, the data is perceived as a blob, so in xhr.responseText(type string) I get [object Blob] How do I get the file downloaded and the error output in case of an error? -
How to use filter to check if strings stored in a Django array field are a substring of the input string
Here is how my model looks like. class TestModel(models.Model): test_field= ArrayField(models.CharField(max_length=255, null=True, blank=True),default=list) I want to filter objects which have any substring of the input string as an entry in their test_field. Example: Assume a TestModel object1 has the ['good','morning'] stored in its test_field. object2 has ['run','crew']. Input String is 'Good Evening'. The output should return a query set containing object1. -
how to call value of request.session in django forms
i didnot get item list in outward forms which comes from store items database enter image description here -------------------------forms.py---------------------------- class OutwardForm(forms.Form): item = forms.ModelChoiceField(queryset=StoreItems.objects.none()) quantity = forms.IntegerField() name = forms.CharField() emp_id = forms.IntegerField() def __init__(self, *args, **kwargs): self.warehouse_id = kwargs.pop('warehouse_id', None) super().__init__(*args, **kwargs) if self.warehouse_id: self.fields['item'].queryset = StoreItems.objects.filter(warehouse_id=request.session['warehouse_id']) def clean(self): cleaned_data = super().clean() # process cleaned_data as before return cleaned_data ---------------------views.py---------------------------- def outward(request): warehouse_id = request.session.get('warehouse_id') message = "" form = OutwardForm(request.POST or None, warehouse_id=warehouse_id) if request.method == 'POST': # form = OutwardForm(request.POST) form.request = request if form.is_valid(): item = form.cleaned_data['item'] quantity = form.cleaned_data['quantity'] name = form.cleaned_data['name'] emp_id = form.cleaned_data['emp_id'] opr_name = request.user.username if item.quantity >= quantity: item.quantity -= quantity item.save() record_transaction(item, quantity, name, emp_id, 'outward', opr_name, warehouse_id) message = "Success" form = OutwardForm() else: message = "Quantity must not be less than available quantity" else: form = OutwardForm() context = { # 'items': StoreItems.objects.filter(warehouse=warehouse_id), 'form': form, 'message': message } return render(request,'outward.html',context) -------------------------outward.html---------------------- <h1>Outwoard Item</h1> {% csrf_token %} Item Name : {{form.item}} Quantity : {{form.quantity}} Name of User : {{form.name}} Employee ID : {{form.emp_id}} -
Optimize Supabase insertion
I'm writing a code which is fetching around 100k data from Supabase and inserting it into default Django database and it's taking too much time. Please help me in making it faster. I am using two Supabase databases; one contains data and the other is the default database of Django. I'm also using Multithreading in this code. from django.db import connections from django.core.management.base import BaseCommand import json from concurrent.futures import ThreadPoolExecutor from api.GAmodel import Organization,Client from django.utils import timezone from api.GoogleConsoleModel import GC_Search_AB_Queries, GC_Search_AB_Pages, GC_Search_AB_Country, GC_Search_AB_Device class Command(BaseCommand): help = 'Inserts JSON data into the ModelName model' def handle(self, *args, **options): start=timezone.now() other_db_connection = connections['other'] # Define the SQL query to retrieve table names sql_query = """ SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ('_airbyte_raw_search_analytics_by_query', '_airbyte_raw_search_analytics_by_page','_airbyte_raw_search_analytics_by_device','_airbyte_raw_search_analytics_by_country') ORDER BY table_name; """ org_name="abc" org_table,created_org=Organization.objects.get_or_create(company=org_name) try: with other_db_connection.cursor() as cursor: cursor.execute(sql_query) rows = cursor.fetchall() # Extract table names from the query results table_names = [row[0] for row in rows] with ThreadPoolExecutor() as executor: futures = [] for table_name in table_names: futures.append(executor.submit(self.process_table, table_name, org_table)) # Wait for all futures to complete for future in futures: future.result() except Exception as e: print(f"Error occurred: {e}") end = timezone.now() print(f"Total time taken: {end-start}") … -
Error while installing `mysqlclient` on `vercel` for `django` app
I am trying to deploy a django app on vercel that requires a module mysqlclient but it seems to be failing because of some error for mysql_config. I am using PlanetScale and had added integration. The error is: Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: mysql_config: command not found /bin/sh: mariadb_config: command not found /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-xudcpdyi/mysqlclient_9d1c2ef21f0b41d6aa185af14610a5f3/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-xudcpdyi/mysqlclient_9d1c2ef21f0b41d6aa185af14610a5f3/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-xudcpdyi/mysqlclient_9d1c2ef21f0b41d6aa185af14610a5f3/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed And the final error is: 1: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: mysql_config: command not found /bin/sh: … -
Cronjob not working in django. The task is not performed automatically at given time
I have a Django application. In that, there is an application. Within the application, I have a function py file calculate_rev and it has a function calculate_weekly. I have set cronjob in settings and added the cronjob. When crontab -l is executed it shows my added task. But is not running at the specified time. It runs when I do it in this way python manage.py crontab run 3c46f4f7c6d33456f68f9796cb22ffc3. I have added logging. When I run it manually the log is created. Otherwise, the log is not created. I am working on RedHat Linux based system CRONJOBS = [ ('52 09 * * 2', 'myapp.calculate_rev.calculate_weekly') ] -
I keep on getting this error TypeError: Invalid path type: module each time i try to run my html files on the django server. i've been stuck forever
Please i can provide more screenshots if needed. I've meet with my lecturer and he doesn't seem to know why the are errors on the code and why its not running properly. Tried including the templates to templates directory in settings.py I've tried creating an entirely different project to see where i made my mistake still can't find it -
Django testing function that sets external managed database autocommit to True
Say I have this function I want to test from django.db import connections def to_be_tested(...): connections['external'].set_autocommit(True) .... and in my transactionised test case class MyTestCase(TestCase): def test_function(self): to_be_tested(...) ... This causes django to complain File "/Users/jlin/projects/service/api/views/serviceorder.py", line 100, in post connections['external'].set_autocommit(True) File "/Users/jlin/virtualenvs/service/lib/python3.7/site-packages/django/db/backends/base/base.py", line 404, in set_autocommit self.validate_no_atomic_block() File "/Users/jlin/virtualenvs/service/lib/python3.7/site-packages/django/db/backends/base/base.py", line 443, in validate_no_atomic_block "This is forbidden when an 'atomic' block is active.") django.db.transaction.TransactionManagementError: This is forbidden when an 'atomic' block is active. How do I get Django unittest to ignore this since it's not a default database? My current workaround is lying about it and it seems work fine when to_be_tested(...) doesn't cause an error to roll back. class MyTestCase(TestCase): def test_function(self): connections['external'].in_atomic_block = False to_be_tested(...) connections['external'].in_atomic_block = True ... -
Google authentication does not work on my html/js code
I am building a web application with html/js and I need to have a Google signing. I did everything I needed to do based on the Google OAuth 2.0 docs. this is my login page {% extends "home/layout.html" %} {% block body %} <script src="https://apis.google.com/js/platform.js" async defer></script> <meta name="google-signin-client_id" content=key.com"> <h2>Login</h2> {% if message %} <div>{{ message }}</div> {% endif %} <form action="{% url 'login' %}" method="post" id="loginForm" style="margin-left: 540px;"> {% csrf_token %} <div class="form-group"> <input autofocus class="form-control" type="text" name="username" placeholder="Username"> </div> <div class="form-group"> <input class="form-control" type="password" name="password" placeholder="Password"> </div> <input id="loginBTN" class="btn btn-primary" type="submit" value="Login"> </form> <div class="g-signin2" data-onsuccess="onSignIn" style="margin-left: 643px; border-radius: 205px; scale: 1.4; width: 200px; font-size: 23px;"></div> <div id="test" style="margin-left: 300px;"> </div> <script> function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); console.log("this is log"); console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead. console.log('Name: ' + profile.getName()); console.log('Image URL: ' + profile.getImageUrl()); console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present. fetch("/loginWithGoogle", { method:"POST", body: JSON.stringify("email"=profile.getEmail()) }); } </script> {% endblock %} I already have a domain and the website is published. when I try to login with google it takes me to the google … -
Djongo Error = AttributeError: 'Identifier' object has no attribute 'get_parameters'
My system environment. Django==4.1.4 django-oauth-toolkit==2.2.0 djangorestframework==3.14.0 djongo==1.3.6 pymongo==3.12.3 Execute this. python manage.py cleartokens I got this error => AttributeError: 'Identifier' object has no attribute 'get_parameters'. But I can't find a 'get_parameters' function. The djongo package does not define a get_parameters function. Is this a version problem? My djongo is a latest version. It's a 1.3.6 version. Where is a get_parameters function? How can fix a sql error? Traceback Traceback (most recent call last): File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 933, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 116, in __init__ super().__init__(*args) File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 123, in parse self.selected_columns = ColumnSelectConverter(self, statement) File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/sql2mongo/converters.py", line 44, in __init__ super().__init__(query, statement) File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/sql2mongo/converters.py", line 27, in __init__ self.parse() File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/sql2mongo/converters.py", line 53, in parse for sql_token in SQLToken.tokens2sql(tok, self.query): File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 49, in tokens2sql yield SQLFunc.token2sql(token, query) File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/sql2mongo/functions.py", line 24, in token2sql return CountFunc.token2sql(token, query) File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/sql2mongo/functions.py", line 78, in token2sql token[0].get_parameters()[0] AttributeError: 'Identifier' object has no attribute 'get_parameters' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/python_backend/.venv/lib/python3.10/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( … -
Images are loading in all pages except for one in Django
So I am extending base.html onto another page in Django. The images load in every single page that extends the base.html except for one. I've included the {% load static %} tag inside the template that is not loading the image. I have no clue why the images are not loading in this one specific page. What's wrong with it? base.html {% load static %} <!doctype html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href='https://unpkg.com/boxicons@2.0.9/css/boxicons.min.css' rel='stylesheet'> <link rel="stylesheet" href="{% static 'styles/style.css' %}" /> <title>BugTracker</title> {% block htmlhead %} {% endblock htmlhead %} <link href="https://fonts.googleapis.com/icon?family=Material+Icons+Sharp" rel="stylesheet"> </head> <body> {% include 'navbar.html' %} <!-- END OF NAVBAR --> <div class="container"> {% include 'sidebar.html' %} <!-- END OF ASIDE --> {% block content %}{% endblock %} </div> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="{% static 'js/script.js' %}"></script> <script src="{% static 'js/charts.js' %}"></script> </body> </html> This is where I am loading the <img src> navbar.html <nav> <div class="container2"> <img src="../static/images/logo-no-background.png" class="logo"> <div class="search-bar"> <span class="material-icons-sharp">search</span> <input type="search" placeholder="Search"> </div> <div class="profile-area"> <div class="theme-btn"> <span class="material-icons-sharp active">light_mode</span> <span class="material-icons-sharp">dark_mode</span> </div> <div class="profile"> <div class="profile-photo"> <img src="../static/images/avatar.svg" alt=""> </div> <h5>Miko Dawili</h5> <span class="material-icons-sharp">expand_more</span> </div> <button id="menu-btn"> <span class="material-icons-sharp">menu</span> </button> </div> </div> </nav> sidebar.html <!-- … -
Why I'm receiving a connection time out on my Django + AWS RDS project?
I'm trying to make a deploy of a project using Django + AWS RDS + PostgreSQL, when I try to run the "python manage.py runserver" code I'm receiving this error: connection to server at "ang-trading.......amazonaws.com" (18.218.211.5), port 5432 failed: Connection timed out (0x0000274C/10060) I rode this once and it work, but now I'm facing this problem and I don't know exactly why I try to check my traffic rules on AWS, I've double check the information necessary in the Django settins.py file -
Error while installing pillow with pip windows10
i have tried to install pillow with pip inside the cmd to make my django preoject use pictures but i have found an error of this kind Collecting pillow Using cached Pillow-9.5.0.tar.gz (50.5 MB) Preparing metadata (setup.py) ... done Building wheels for collected packages: pillow Building wheel for pillow (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [189 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.mingw_x86_64-cpython-310 creating build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BdfFontFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\ContainerIO.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\CurImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\ExifTags.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\features.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FitsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FitsStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FliImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FontFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GdImageFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GifImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GimpGradientFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GimpPaletteFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GribStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\Hdf5StubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\IcnsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\IcoImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\Image.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\ImageChops.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\ImageCms.py -> build\lib.mingw_x86_64-cpython-310\PIL copying … -
no such table: users_profile
I am creating a web application for my university assignment, however I have followed the worksheets and I am not able to get passed this problem. I have copied the work from my peers, and also the example copy of the assignment the lecturer has made which works. The problem stems from when I try to register an account, it comes up with "no such table: users_profile". It is running on a Azure Portal Ubuntu VM. I am also using visual studio code. enter image description here The server is running, the models have been created and I believe they are correctly defined. Model(table) Registration Form view page I have also tried make migration and migrate, in which doesnt work. I have also tried the SQlite3.db file. -
My Visual Studio Code terminal won't reset to cd anymore
this is my problem. Every time I run python manage.py runserver this happens. How can I make to where I don't have to reset my VSC every time I want access to the terminal again? I did try to control break but my laptop keyboard doesn't include the break button. I tried FN+CTRL+B, CTRL+B, and FN+CTRL+F11. None worked. -
DJANGO | How to update relation nested without validate each foreign key
How to update relation nested without validate each foreign key. Is there a way to avoid validating each foreign key inside a relation list? { "name": "Item 0037", "price": 10, "category":2, "prices_list": [ { "id": 192, "price_list_id": 1, "price": 999.97 }, { "price_list_id": 2, "price": 888.99 }, { "price_list_id": 2, "price": 234.99 } ] } I'm using django-rest-framework (serializers, viewset), but every time I send the data I see that it does a validation for each relationship, is there something similar to fetch_related that only does a query? -
Why don't I have a button in django rest framework for dynamically adding nested form data, if there should be one?
I ask for help Take a look at the screenshot please, I can't understand why I can't add links dynamically Click 1 This is the kind of Json format data you should get: values { "firstname": "l", "lastname": "m", "links": [ { "linkname": "https://www.youtube.com/", "linkurl": "https://www.youtube.com/" }, { "linkname": "https://www.youtube.com/", "linkurl": "https://www.youtube.com/" } ] } And besides, even if all these existing fields are filled in (well, that is, those fields that are already in the django rest framework, namely, one array of links and the First Name along with the Last Name), an error is displayed: The .create() method does not support writable nested fields by default. Write an explicit .create() method for serializer schedule.serializers.WorkSuperSerializer, or set read_only=True on nested serializer fields. I went through a lot of solutions to the problem, for example, I declared the create() method: def create(self, validated_data): links_data = validated_data.pop('links') worksuper = WorkSuper.objects.create(**validated_data) for link_data in links_data: Link.objects.create(worksuper=worksuper, **link_data) return worksuper But it didn't fix the error((((( In general, here is my code: Models.py: class WorkSuper(models.Model): firstname = models.CharField("Имя", max_length=10, blank=True) lastname = models.CharField("Фамилия", max_length=30, blank=True) class Link(models.Model): links = models.ForeignKey(WorkSuper, related_name='links', on_delete=models.CASCADE, blank=True) linkname = models.CharField("linkname", max_length=100, blank=True) linkurl = models.CharField("linkurl", max_length=100, blank=True) … -
In the app engine dashbord, requests from uri are displayed that I don't know the origin, does anyone know where it comes from?
Dashboard do App engine A friend told me that it looks like wordpres was downloaded along with the app because they are common wordpress uris, but he's not sure. I thought that they were due to Google Cloud services (App engine, Storage, Logging, Build, Secret manager) but I'm not sure either? Is it one of those cases? Is it a problem and if so is there a fix? Obs: I don't know it it helps, but the site is develop with django, boostrap and jquery. I even write in browser the uri but nothing that i wouldn't expect appear. I don't even know how to work with wordpress. -
Annotation by condition
I have 2 models: class City(models.Model): title = models.CharField() class VisitedCity(models.Model): city = models.ForeignKey(City) user = models.ForeignKey(User) I want to make a queryset with annotated fields visited boolean type: if this city in visitedcity model and user=self.request.user => True if not => False `City.objects.annotate( ... something ... )` I tried to use annotate() like this one, but it is not work: queryset_visited = VisitedCity.objects.filter(user=self.request.user) queryset_all = City.objects.annotate( visited=Case( When(title__in=queryset_visited, then=Value(True)), default=Value(False) ) ) Could you please help me with this question? -
NPM error in Django application deployment in Render
I’m trying to deploy a Django application in Render. My operating system is Windows. I use tailwind and when it is executed in the Render virtual machine the command 'python manage.py tailwind build' appears the following error of npm: sh: 1: rimraf: not found npm ERR! code ELIFECYCLE npm ERR! syscall spawn npm ERR! file sh npm ERR! errno ENOENT npm ERR! theme@3.4.0 build:clean: `rimraf ../static/css/dist` npm ERR! spawn ENOENT npm ERR! npm ERR! Failed at the theme@3.4.0 build:clean script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. I have in the requirements.txt nodejs==0.1.1 and npm==0.1.1. And in the settings.py: NPM_BIN_PATH = "/usr/bin/npm". Below I show the build.sh file: set -o errexit pip install -r requirements.txt python manage.py collectstatic --no-input python manage.py migrate python manage.py tailwind build if [[ $CREATE_SUPERUSER ]]; then python manage.py createsuperuser --no-input fi -
Custom "per-tenant" views in Django
I developed a multi-tenant Django app (single DB with single schema and domain-based, eg. https://tenant-xyz.esample.com) and I'd like to be able to customize some views according to the current tenant. For example, /my_app/some_view might include some logic while /my_app/tenant_xyz/some_view might behave in a different way. Of course I could also have /my_app/tenant_abcdef/some_unique_view_for_tenant_abcdef_only. Following Django's urls.py phylosophy, I guess custom views could be enclosed in their own views_tenant_xyz.py and tenant-related URLs would point to custom views files. The simplest intuition was to to dynamcally include tenants' custom views URLs in urls.py (without typing them statically). Given a urls.py fragment: urlpatterns = [ path('', include('my_app.urls')), path('admin/', admin.site.urls), ] I thougth I could include the following code in urls.py: for tenant in Tenant.objects.all(): urlpatterns += [ path(f'custom_views/{tenant.name}/', include(f'myapp.tenants.urls_{tenant.name}', namespace=f'customviews{tenant.name}')), ] and then define custom CVB (or functions) in each myapp.tenants.urls_{tenant.name}.py but I get an "SynchronousOnlyOperation at / You cannot call this from an async context - use a thread or sync_to_async." (I'm running ASGI with Gunicorn + Uvicorn workers). Btw I suppose using ORM inside settings.py is not the best approach. What would you advise me to do? Keep in mind that each tenant.name is a sort of slug. Thanks in advance.