Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin: how to remove apps links
due to some reasons, I want to remove links on apps inside django admin panel. i have written some code inside base_site.html to customize the logo and title but I need to know how to remove the links of the apps. here is the code {% extends 'admin/base.html' %} {% load static %} {% block branding %} <h1 id="head"> <img src="{% static 'images/logo.png' %}" alt="Saleem's website." class="brand_img" width=170> Admin Panel </h1> {% endblock %} {% block extrastyle%} <link rel="stylesheet" href="{% static 'admin.css' %}"> {% endblock %} attached is the screenshot to know better where I wan to remove the links -
On automated sign up
I am learning Django/Python to make the multi-vendor e-commerce website I always wanted to make. I have this question in my mind for a long time and I couldn't see the tutorial anywhere. I didn't try anything because I am a complete beginner. My question is; I am accepting payments through Transferwise, and when the payment is done, how to automate creating profile? To create an AI to accept the payment or? -
How to delete an account in django allauth using a generic.DeletView
I'm currently developing a web application using python3, Django, and AllAuth. This application has a signup system using a custom user model and a user uses their email to log in. I want to make a system that user can delete their accounts using generic.DeleteView I'm trying to make it referring to the basic way to delete some items of Django. But in the case of deleting an account, It doesn't work... How could I solve this problem? Here are the codes: app/views.py class UserDeleteView(LoginRequiredMixin, generic.DeleteView): model = CustomUser template_name = 'app/user_delete_confirm.html' success_url = reverse_lazy('app:welcome') def delete(self, request, *args, **kwargs): return super().delete(request, *args, **kwargs) app/urls.py ... path('user_delete/<int:pk>/', views.UserDeleteView.as_view(), name='user_delete'), ... accounts/models.py class CustomUser(AbstractUser): class Meta: verbose_name_plural = 'CustomUser' app/user_delete.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>user_delete</title> </head> <body> <a href="{% url 'app:user_delete_confirm' object.pk %}"> <button type="button" >delete </button> </a> </body> </html> app/user_delete_confirm.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>user_delete_confirm</title> </head> <body> <form action="" method="post"> {% csrf_token %} <h2>Are you sure to delete your account? </h2> <button type="submit">DELETE</button> </form> </body> </html> ・python:3.7.5 ・Django:3.1.2 ・django-allauth:0.43.0 -
Filter and get values using OR and AND conditions in Django
I am querying a set of objects with a condition like this: for filter_for_dates_report in filters_for_dates_report: filter_dict.update({filter_for_dates_report: { filter_for_dates_report + "__range" : [start_date, end_date] }}) list_of_Q = [Q(**{key: val}) for key, val in filter_dict.items()] if list_of_Q: model_details = Model.objects.filter(reduce(operator.or_, list_of_Q)) .values(*values_list_for_dates_report) Now I want to exclude the objects which have null values for filter_for_dates_report attributes. A direct query would be Model.objects.filter( Q(filter_for_dates_report__range=[start_date, end_date] & filter_for_dates_report__isnull=False)) .values(*values_list_for_dates_report) But how can I do this for multiple values wherein I want only the values within that range and also which are not null for multiple filter_for_dates_report attributes. Something like: Model.objects.filter( Q(filter_for_dates_report__range=[start_date, end_date] & filter_for_dates_report__isnull=False) | Q(filter_for_dates_report__range=[start_date, end_date] & filter_for_dates_report__isnull=False) | Q(filter_for_dates_report__range=[start_date, end_date] & filter_for_dates_report__isnull=False) .values(*values_list_for_dates_report) -
Show absolute URL for uploaded file
I implemented a file upload endpoint with DRF the issue is the documents do not show the absolute url of the file as shown below on the screenshot. I expect the absolute url start with http://localhost .... Here is my django settings STATIC_URL = '/static/' # The folder hosting the files STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] ## Serving the STATIC FILES # As declared in NginX conf, it must match /src/static/ STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), 'static') MEDIA_URL = '/media/' # do the same for media files, it must match /opt/services/djangoapp/media/ MEDIA_ROOT = os.path.join(BASE_DIR, 'media') models.py class Document(models.Model): """This represents document class model.""" file = models.FileField(upload_to='documents/inspections/%Y/%m/%d') timestamp = models.DateTimeField(auto_now_add=True) @property def name(self): name = self.file.name[33:] return name -
Django AWS S3 - 400 "Bad Request" - Can't access image from bucket
I recently decided to merge the images used in my application from a static folder in my root directory to an AWS S3 bucket. However, I am getting this error when I open my app in a browser: localhost/:65 GET https://django-plantin-bugtracker-files.s3.amazonaws.com/profile_pics/aragorn_SztKYs6.jpg?AWSAccessKeyId=AKIA3KFS7YZNOMSRYG3O&Signature=fYWSQFdzTvtOF9OXAfw9yqfGyQc%3D&E I unblocked all public access on my S3 bucket and added these lines of codes to the following files: In my app's settings.py I added: AWS_STORAGE_BUCKET_NAME=config('AWS_S3_BUCKET_NAME') AWS_ACCESS_KEY_ID = config('AWS_S3_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_S3_SECRET_ACCESS_KEY') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' In my S3 bucket's Bucket Policy: { "Version": "2008-10-17", "Statement": [ { "Sid": "AllowPublicRead", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::django-plantin-bugtracker-files/*" } ] } In my S3 bucket's CORS: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "PUT", "POST", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] Does anyone know why my images won't appear? The webpage loads fine and there is no error from Django. The images look like this: -
Why is my Django login not getting authenticated?
I do know that this is a repeated question. I did refer those answers but still I couldn't get my issue fixed. Kindly do help. Registration works just fine. The registered users gets added to the DB fine. Logout works fine. The issue is with login. Whenever I try logging in , I keep getting the response "Invalid login details". views.py from django.shortcuts import render, redirect from . forms import * from django.http import HttpResponse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required # USER LOGIN def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user =authenticate( username=username, password=password) if user is not None: if user.is_active: login(request,user) return redirect('home') else: return HttpResponse("Account not active") else: return HttpResponse("Invalid login details") #whenever I try to login, I always gets this response. else: return render(request, 'basic_app/login.html') #USER LOGOUT @login_required def user_logout(request): logout(request) return redirect('login') urls.py(application). from django.urls import path from . import views urlpatterns = [ path('',views.index, name='home'), path('register/',views.register, name='register'), path('login/',views.user_login, name='login'), path('logout/',views.user_logout, name='logout'), ] login.html {% extends 'basic_app/base.html' %} {% block body_block %} <div class='jumbotron'> <h2>User Login</h2> <form action="{% url 'login' %}" method="post"> {% csrf_token %} <label for="username">Username:</label> <input id="username" type="text" placeholder="Enter Username"> <label for="password">Password</label> <input id="password" … -
What is the most efficient way to compare a string to Enums?
I have the following Enum class: class LabelEnum(str, Enum): ENUM_ONE = "Enum One" ENUM_TWO = "Enum Two" ENUM_THREE = "Enum Three" FOUR = "FOUR" FIVE = "FIVE" SIX = "SIX" I want to compare a string with all of the members of this enum and see if the string exists in the enum class or not. I can do this by following snippet: if string in LabelEnum.__members__: pass But I want to compare the lower case of the string (string.lower()) with the lower case of the enum members. I can't do this in the above way I think. Another way is to loop through the members but that will slow the execution and I don't want that. Is there any way I can compare the lowercase of these in a single line and more efficiently than looping? -
Is it possible to develop rasa chatbot inside django as an app and managing through manage.py
I’m new to RASA platform. I wanted to develop RASA chatbot as an app inside django instead of creating rasa init and running separate servers like action and core nlu servers. Is it possible and if yes please guide me through. -
Get highest 3 count records from the query in django
I want to get total of all same records from user table . what i am doing is given below result = User.objects.filter(active=1).values('location__state').order_by().annotate(Count('location')) Using this i am getting result like : <QuerySet [{'location__state': 'noida', 'location__count': 9}, {'location__state': 'okhla', 'location__count': 5}, {'location__state': None, 'location__count': 0},{'location__state': goa, 'location__count': 3},{'location__state': up, 'location__count': 12},, {'location__state': 'uk', 'location__count': 1}]> it is returning me the state name with count .it is perfect . in that way i will get the count with state what i actuall want is i want only 3 records with highest count how can i solve this can anyone please help me related this ?? -
Django: Unexpected keyword error when trying to create with correct parameters
I'm just starting out in Django and following along with a tutorial. I've copied exactly what they did, but I'm still getting this unexplained error. For this particular app, my very simple models.py file looks like this: from django.db import models # Create your models here. class Product(models.Model): title = models.TextField description = models.TextField price = models.TextField summary = models.TextField(default='This is cool!') I can't see anything wrong with the code, but when I use the Python shell and write Product.objects.create(title="test", description = "test2", price = "test3", summary = "test4"), it throws the error TypeError: Product() got an unexpected keyword argument 'title'. What am I missing? Is there a deeper problem here? -
Django(CSRFToken), GET http://localhost:3000/api/player/ 403 (Forbidden)
------ react ------ csrftoken.js import axios from 'axios'; import React from 'react'; axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].replace(' ', ''); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const initialState = { keyValue: '' }; export const CSRFToken = (state = initialState) => { const csrftoken = getCookie('CSRF-TOKEN'); console.log('token : ' + csrftoken); // state.keyValue = state.props.keyValue; return( <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken}/> ) }; export default CSRFToken; module.js const getPlayerEpic = (action$, state$) => { return action$.pipe( ofType(GET_Player), withLatestFrom(state$), mergeMap(([action, state]) => { console.log(state.CSRFToken.props.value ) return ajax.get('/api/Player/' ,{ Authorization: "Token " + state.token, 'X-CSRFTOKEN': state.CSRFToken.props.value }).pipe( map(response => { const Player = response.response; return getPlayerSuccess({Player}); }), catchError(error => of({ type: GET_Player_FAILURE, payload: error, error: true, }) ) ); }) ); }; ------ django (python) ------ view.py class Listplayer(generics.ListCreateAPIView): authentication_classes = [SessionAuthentication, ] permission_classes = [djangomodelpermissions, ] queryset = playerList.objects.all() serializer_class = playerListSerializer settting.py ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'post', … -
Sending an email from python django app with azure logic apps
I followed this tutorial to deploy a basic python django app to azure app service. The full code for the app can be found here. This works fine, its a basic polling app where I can add questions and visitors can answer the poll questions and I can monitor the results. I then tried to follow this tutorial to create a logic app that will send an email when a poll question is answered. The logic app seems to have been created successfully. At the end of this tutorial there is a short section on integrating this logic app with my django app by adding an HTTP post into the code. However, the section of code it tells me to put it in is in a non python file that doesn't exist in the provided repo. It seems to be some sort of mistake. So basically I'm not sure where to put the HTTP post in my django app. I've been reading through the django docs to try to better understand what the example app code is doing exactly but I feel like I'm in a bit over my head at this point. The azure tutorials were pretty explicit about … -
Django admin not being updated by custom method
I have a meta-model that stores website information. Model Code class MetaModel(models.Model): name = models.CharField(max_length=4) students = models.IntegerField(default=0) instructors = models.IntegerField(default=0) courses = models.IntegerField(default=0) transactions = models.IntegerField(default=0) cashins = models.IntegerField(default=0) cashouts = models.IntegerField(default=0) balance = models.IntegerField(default=0) There are some other models like Students, Instructors, Transactions etc. So I am using a custom method that will update meta info automatically def update_meta(self): self.students = StudentModel.objects.count() self.instructors = InstructorModel.objects.count() self.courses = CourseModel.objects.count() self.transactions = CourseModel.objects.count() self.cashins = CashinModel.objects.count() self.cashouts = CashoutModel.objects.count() The index view looks somewhat like this def index(request): f = MetaModel.objects.first() f.update_meta() return render(request, "app/index.html", {'meta':f}) The index page gets updated everytime and shows me the info correctly. But when I go to the django admin page, the data are not updated. Image attached for clarity How do I fix this? -
POST JSON from Android app to Django backend
I am trying to POST a JSON from Android front ent to Django backend, that is hosted as localhost in my computer. The android app is also running on an emulator on the same device. I am sending it like this: package com.example.smartgov; import android.os.AsyncTask; import android.util.Log; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class SendDeviceDetails extends AsyncTask<String, Void, String> { @Override public String doInBackground(String... params) { String data = ""; HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream()); wr.writeBytes("PostData=" + params[1]); wr.flush(); wr.close(); InputStream in = httpURLConnection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(in); int inputStreamData = inputStreamReader.read(); while (inputStreamData != -1) { char current = (char) inputStreamData; inputStreamData = inputStreamReader.read(); data += current; } } catch (Exception e) { e.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return data; } @Override public void onPostExecute(String result) { super.onPostExecute(result); Log.e("TAG", result); // this is expecting a response code to be sent from your server upon receiving the POST data } } And on clicking a button i am sending this, this is the code for the onclick of the button: public void createAccount(View view) … -
How to let Django see files under dist/static generated by Vue.js compilation?
I'd like to know how to specify static directory for Django in the following case. I don't use Django template at all (I don't use {% static ... %} in html file). vue-cli generates outputs under dist/, which is not in the scope of Django project, and I don't like to change this. In index.html, bundle.js is loaded by <link href="static/js/bundle.js"> Would like to let Django see index.html and all js files under static/js dir. Directory tree root ├── vue_proj │ └── dist │ ├── index.html <- SPA, and no Django template in this. │ └── static <- I wouldd like to let Django see this dir! │ └── js │ └── bundle.js └── django_proj <- I executed "django-admin startproject project" here. └── project <- I executed "django-admin startapp app" here. ├── manage.py ├── app └── project ├── settings.py <- What should I do here? So far I could let Django see dist/index.html by setting TEMPLATES parameter to ../vue_proj/dist. I tried the follows but resulted in failure of loading js files... STATIC_ROOT = '../vue-proj/dist' STATIC_URL = '/static/' -
Django: Unable to run async requests.get on google. Exception Response can't be used in 'await' expression
I am unable to understand how async works. I send simple get requests to google with a proxy to check the validity of proxy in a async method. I get the error: '''object Response can't be used in 'await' expression''' Method to get proxies. Code for getting the list of proxies is copied from a tutorial: def get_proxies(self, number_of_proxies=10): """Returns max 10 free https proxies by scraping free-proxy website. @arg number_of_proxies to be returned""" try: if number_of_proxies > 10: number_of_proxies = 10 url = 'https://abc-list.net/' response = requests.get(url) response_text = response.text parser = fromstring(response_text) proxies = set() for i in parser.xpath('//tbody/tr'): if len(proxies) >= number_of_proxies: break if i.xpath('.//td[7][contains(text(),"yes")]'): #Grabbing IP and corresponding PORT proxy = ":".join([i.xpath('.//td[1]/text()')[0], i.xpath('.//td[2]/text()')[0]]) proxies.add(proxy) return proxies except Exception as e: print('Exception while abc list from url: ', e) return None Method to check the validity of proxy: async def is_valid_proxy(self, proxy): """Check the validity of a proxy by sending get request to google using the given proxy.""" try: response = await requests.get("http://8.8.4.4", proxies={"http": proxy, "https": proxy}, timeout=10) if await response.status_code == requests.codes.ok: print('got a valid proxy') return True except Exception as e: print('Invalid proxy. Exception: ', e) return False Method to get the valid proxies: async … -
Python Django: Filter within for loops
Context I currently have 'Building' and 'Room' objects stored in my database - linked by a Foreign Key. I'm trying to generate a Room query set for each Building using for loops and objects.filter() Problem See the code posted below - I can't seem to solve a seemingly simple problem. 'BuildingList' returns two objects, but for some reason my for loop only queries and appends a 'RoomList' for one of two buildings. (The second one) I don't understand why, but RoomList = Room_Data.objects.filter(Room_Building=b) seems to disrupt the logic and flow of my basic for loop. Python Script: # # # 1.) GET DATA FOR RELEVANT SET OF BUILDINGS FusionBuildingName = "Renal Dialysis Unit x6" BuildingRoomLists = [] # GET DATA FOR ALL BUILDINGS MATCHING 'FusionBuildingName' BuildingList = Building_Data.objects.filter(Building_Name=FusionBuildingName) print(len(BuildingList)) print(BuildingList) # GENERATE BUILDING ROOM LISTS for b in BuildingList: print(b) print("Building Author: " + b.Building_Author) print("Building Room List:") # GET LIST OF ROOM OBJECTS FOR CURRENT BUILDING RoomList = Room_Data.objects.filter(Room_Building=b) print(str(RoomList)) # APPEND LIST OF ROOM OBJECTS TO BUILDING ROOM LIST BuildingRoomLists.append(RoomList) Below is what my Python Shell returns upon running the above code: In [43]: In [44]: ...: ...: ...: ...: ...: ...: ...: Building_Data object (1) 1 Building … -
Django display multiple uploaded files
I am trying to display multiple uploaded file URLs but I'm not sure how to do it. I am a form that the users can use to upload multiple files that are working perfectly but now I want to be able to display these files. For instance, a company can have more than one file. class InternationalCompany(models.Model): International_company_Name = models.CharField(max_length=50) International_company_Id = models.CharField(max_length=50) options = ( ('Yes', 'Yes'), ('No', 'No'), ) Does_it_have_a_Financial_Dealers_License = models.CharField(max_length=20, choices=options, null=True) Register_Office = models.TextField(max_length=500, null=True) Beneficial_owner = models.CharField(max_length=100, null=True) Beneficial_owner_id = models.FileField(upload_to='passport/pdf/',null=True) expire_date = models.DateField(null=True) BO_Phone_number = models.IntegerField(null=True) BO_Email_Address = models.EmailField(null=True) BO_Residential_Address = models.TextField(max_length=200, null=True) def __str__(self): return self.International_company_Name class SupportDocuments(models.Model): Supporting_Documents = models.FileField(upload_to='support_doc/pdf/', null=True) internationalcompany = models.ForeignKey(InternationalCompany, on_delete=models.CASCADE) def __str__(self): return self.Supporting_Documents.url I try something like this but it only displayed one url of the file instead of the multiple urls for the files that are associate with that company. {%for company in doc%} <tr> <td></td> <td>{{company.internationalcompany.Beneficial_owner}}</td> <td>{{company.Supporting_Documents.url}}</td> </tr> {%endfor%} I have also try out this but it doesn't display anything. {%for company in doc.Supporting_Documents.all%} {{company.url}} {%endfor%} -
OkHttp keeps getting StreamResetException: stream was reset: INTERNAL_ERROR when it's 200
I got StreamResetException: stream was reset: INTERNAL_ERROR from OkHttp. What's the problem? Here's the logs. I/okhttp.OkHttpClient: <-- 200 https://www.example.com/user/list (396ms) I/okhttp.OkHttpClient: date: Fri, 04 Dec 2020 02:21:35 GMT I/okhttp.OkHttpClient: content-type: application/json I/okhttp.OkHttpClient: content-length: 99730 I/okhttp.OkHttpClient: server: nginx/1.18.0 I/okhttp.OkHttpClient: allow: GET, HEAD, OPTIONS I/okhttp.OkHttpClient: x-frame-options: DENY I/okhttp.OkHttpClient: x-content-type-options: nosniff I/okhttp.OkHttpClient: referrer-policy: same-origin D/okhttp.Http2: << 0x00000003 5792 DATA D/okhttp.Http2: << 0x00000003 4 RST_STREAM D/okhttp.TaskRunner: Q10092 canceled : OkHttp ConnectionPool D/force: okhttp3.internal.http2.StreamResetException: stream was reset: INTERNAL_ERROR D/okhttp.Http2: >> 0x00000000 8 GOAWAY D/okhttp.TaskRunner: Q10096 finished run in 216 ms: OkHttp www.example.com This is issued in Okhttp Gihub Repository. But any issues haven't solved yet. I called the API like this @Headers("Content-Type: application/json") @GET("/user/list") fun getUserList(@Header("Authorization") jwt: String): Call<ArrayList<UserData>> It's 200 but I get nothing. It's very weird behaviour.. Is it a server problem or my problem? (The server is Django). -
Django Model Equality Returning None Value
I have the following Django Classes: class Article(Model): source = ForeignKey("ArticleSource") class ArticleSource(Model): url = URLField() When I create an ArticleSource object, then create a new Article with that source referenced, then compare the referenced source to the source object, I get a None value. Example: source = ArticleSource.objects.create(url="https://example.com/") article = Article.objects.create(source=source) # THE ISSUE article.source == source # returns None Some other examples: source.id >>> <ArticleSource: ArticleSource object (1)> article.source >>> <ArticleSource: ArticleSource object (1)> article.source.id == source.id >>> True What am I missing here? Why does article.source == source not return True when article.source.id == source.id does? -
redis-server.exe: cannot execute binary file in heroku
I'm trying to deploy my django app with redis by heroku, but it didn't work and got the error in logs. I installed redis for windows from here. Procfile web: gunicorn mysite.wsgi --log-file - worker: bash Redis/redis-server.exe logs 2020-12-04T01:56:26.263759+00:00 app[worker.1]: Redis/redis-server.exe: Redis/redis-server.exe: cannot execute binary file 2020-12-04T01:56:26.346545+00:00 heroku[worker.1]: Process exited with status 126 2020-12-04T01:56:26.735800+00:00 heroku[worker.1]: State changed from up to crashed Heroku version heroku/7.47.3 win32-x64 node-v12.16.2 I'm using windows and I'm pretty sure that my system type is 64bit operation system. What's wrong with my app? How can I fix this? Thank you :) -
Looking for expert advice on programming language
I know this question is a bit unorthodox for this type of site, and I will probably hear some feedback to reinforce that - but I also have used this site many (many) time sin the past to solve coding issues so i know there are some high-level experts here who are kind and helpful. With that said - I have been a front-end designer for about 10 years. I primarily use Wordpress and Bootstrap for developing customer websites. Reasons for this are simple - it is a quick, all in one solution that can be customized according to any taste, and can be made secure with enough attention to detail. I learned to be proficient at Adobe AE, PP, PS, AI, etc. I am 43 years old. I have been able to work form home developing small to medium sized client websites, graphics, video production, etc for the last 12 years. Before that I was an auto mechanic. I got in the game late in life. I have noticed the world of webdev has passed me by considerably. I now hear a lot about API's, Docker, kubernettes, SDK's, see guys using the CLI to create and deploy websites and … -
Avoid race condition inside values of JSONField
I have a JSON field with multiples ID as counters, something like: details = models.JSONField() With content like: { 'id1': 0, 'id500': 42, } And I need to add some values avoiding a race condition: details['id500'] += 10 I've tried to solve that using: obj.details['id500'] = F('details__id500') + 10 But got: TypeError: Object of type 'CombinedExpression' is not JSON serializable I've also tried: obj.details['id500'] = F('details')['id500'] + 10 but got TypeError: 'F' object does not support indexing What is a proper way to do that increment? -
Django Python how to take data from another sessionid cookie?
So I'm working with django python, and on every new browser I get a new sessionid for my cookie, every sessionid got a unique session database itself. I'm looking for a way to grab data from other sessionid's if possible. Example: Im on my site, in 2 different browsers. Each browser got a unique sessionid cookie, therefore a unique session database. (cookie examples (not real or valid)): Chrome: a7363dc Firefox: a3621bcz In chrome, I got request.session["foo"] Set too "bar" In Firebox, I got request.session["foo"] set too "zoo" Is there a way I can like var = request.session[a3621bcz]['foo'] so it takes the value of session "foo" in firefox? (lets say i perform this in chrome) Or alternatively, is there any way I can make every sessionid cookie the same all the time for everybody? so that everyone has the same access to the request.session["elm"] elements? Like example: wether im on chrome, firefox, or even at starbucks on my chromebook, when I search for the request.session['foo'] it returns "bar" no matter which one im logging in from?