Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 5.0 how to serialize class-based sessions without django.contrib.sessions.serializers.PickleSerializer
I saw Django 5.0 was released today and I am messing around with it, but I see that the PickleSerializer was removed. What is the preferred way of serializing class-based session data now? I see it states use JSON but that breaks my code as I store actual objects in the session for easy reference in some instances (so I get messages that Model object is not JSON serializable), is there an easier, yet still secure way to pickle sessions in Django? -- I store objects inside of sessions occasionally and it works really well for db related access and things of the sort as I don't need to recall the DB. In my settings I was using: SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' You can see it was depreciated in 4.2 and removed in 5.0 here: https://github.com/django/django/blob/stable/4.2.x/django/contrib/sessions/serializers.py As a note, I am trying to figure out if I should alter my code to not store objects via pickle in my session, or if it really matters given I validate and grab data based on my defined objects, not specifically user-defined input -
ERROR on gunicorn: Can't connect to ('156.220.159.63', 8000)
I want to link NGINX with the Django project, so made conf/gunicorn_conf.py file, which includes: command = '/home/omnia/griphr-backend/.venv/bin/gunicorn' pythonpath = '/home/omnia/griphr-backend' bind = '156.220.159.63:8000' workers = 3 I ran it, but got this error: why raise this error? I am sure that the IP is correct -
Trouble Parsing JSON Data in Python [closed]
I'm currently working on a Python project where I'm receiving JSON data from an API, but I'm facing difficulties parsing it correctly. The JSON data looks like this: "name": "John Doe", "age": 30, "email": "johndoe@example.com", "address": { "street": "123 Main St", "city": "Anytown", "zip": "12345', "skills": ["Python", "JavaScript", "SQL"] I'm trying to extract specific information from this JSON object, such as the person's name, age, and skills. However, I'm not sure how to correctly parse this JSON in Python to access this data. Could someone provide an example of how I can extract this information from the JSON object and store it into variables or access it directly? -
"MultipleObjectsReturned or ObjectDoesNotExist error when accessing 'google' provider in Django-allauth"
I'm encountering an issue when trying to access the 'google' provider in Django-allauth. I'm getting either a MultipleObjectsReturned or ObjectDoesNotExist exception. I have followed the documentation and tried various troubleshooting steps, but the problem persists. Here is the code snippet from my views.py file: from allauth.socialaccount.models import SocialApp from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist def home(request): try: google_provider = SocialApp.objects.get(provider='google') except MultipleObjectsReturned: print("Multiple 'google' providers found:") for provider in SocialApp.objects.filter(provider='google'): print(provider.client_id) raise except ObjectDoesNotExist: print("No 'google' provider found.") raise return render(request, 'home.html', {'google_provider': google_provider}) I have also imported the necessary modules SocialApp and MultipleObjectsReturned/ObjectDoesNotExist from allauth.socialaccount.models and django.core.exceptions respectively. I have checked my database, and there is only one entry for the 'google' provider in the SocialApp table. The client_id is correctly set for this provider. Despite taking these steps, I am still encountering the mentioned errors. I have made sure to restart my Django server after any code or database changes. -
Django : can't return redirect in a sub function exception. The first function continues
I've got a function a() that calls other functions b() , c() and d() this way (I schematize): a() def a(request): try: b(request) except Exception: messages.error(request, 'error') try: c(request) except Exception: messages.error(request, 'error') try: d(request) except Exception: messages.error(request, 'error') return redirect('namespace:url_name') b() def b(request): try: do_something() messages.success(request, 'I did') except Exception: messages.error(request, 'Couldn\'t do the thing') return redirect('namespace:url_name') But if an exception triggers in b() , its redirection doesn't work and c() and d() are still executed in a(). Did I miss something in my redirect or exception handling comprehension ? Because even if I set a redirect in all a functions' Exceptions, the behavior doesn't change. -
Issue with Django Migration - "Table already exists
I'm encountering a problem while trying to run migrations in my Django project. When I run python manage.py migrate, I'm getting the following error: django.db.utils.OperationalError: (1050, "Table 'myapp_mymodel' already exists") This error seems to be related to a table already existing in the database, but I haven't manually created it, and it's not in my migration files. I've tried the following steps: Checked migration files for any duplicates or errors. Deleted the database and recreated it. Verified that there are no stray migration files in the app. -
"How can I implement user authentication and authorization in a modern web application using [specific technology or framework]?" [closed]
How do I implement secure user authentication and authorization in a web application using the Django framework? Seeking best practices and code examples to ensure robust user management and access control." I implemented Django user authentication and authorization using official documentation. Expected users to register, log in, and access authorized content. Encountered an issue where authentication succeeded, but authorization failed for specific views." -
Reverse for 'create_submission_form' with keyword arguments '{'docstash_key': ''}' not found
- this is the error: NoReverseMatch at /dashboard/ Reverse for 'create_submission_form' with keyword arguments '{'docstash_key': ''}' not found. 1 pattern(s) tried: ['core/submission/new/(?P<docstash_key>[^/]+)/\\Z'] this is the line in html that is causing the error: <a class="dropdown-item" href="{% url 'core:create_submission_form' docstash_key=docstash.key %}"> this is the url path: path('new/<str:docstash_key>/', views.create_submission_form, name='create_submission_form'), -this is the view function: @with_docstash() def create_submission_form(request): if request.method == 'POST' and 'initial' in request.docstash: del request.docstash['initial'] # XXX: docstash will be saved further down form = SubmissionFormForm(request.POST or request.docstash.POST, initial=request.docstash.get('initial', {}).get('submission_form')) formsets = get_submission_formsets(request.POST or request.docstash.POST, initial=request.docstash.get('initial')) documents = Document.objects.filter(pk__in=request.docstash.get('document_pks', [])) protocol_uploaded = documents.filter(doctype__identifier='protocol').exists() if request.method == 'GET' and not request.docstash.POST and \ not 'initial' in request.docstash: protocol_uploaded = True # don't show error on completely new # submission # neither docstash nor POST data: this is a completely new submission # => prepopulate submitter_* fields with the presenters data profile = request.user.profile form.initial.update({ 'submitter_contact_first_name': request.user.first_name, 'submitter_contact_last_name': request.user.last_name, 'submitter_email': request.user.email, 'submitter_contact_gender': profile.gender, 'submitter_contact_title': profile.title, 'submitter_organisation': profile.organisation, 'submitter_jobtitle': profile.jobtitle, }) if 'notification_type_id' in request.docstash: notification_type = NotificationType.objects.get( id=request.docstash['notification_type_id']) else: notification_type = None if 'submission_id' in request.docstash: submission = Submission.objects.get( id=request.docstash['submission_id']) else: submission = None valid = False if request.method == 'POST': submit = request.POST.get('submit', False) save = request.POST.get('save', False) autosave = … -
Django capture traces of all invoked function Open Telemetry
I am a newbie to Open Telemetry and trying to see how traces are captured for a Django app. I am assuming that OTel should be able to provide traces of all invoked functions for a particular Django Request. E.g.I have a very basic Django app with a views.py as def log_console(): print("Print in terminal") def show_date(): now = datetime.now() log_console() return HTMLResponse() The url is configured to serve show_date My expectation js that when I configure manage.py with DjangoInstrumentor().instrument() In the console I should be able to see reference to the function log_console as it is invoked when serving the show_date But cant see any reference to log_console, not sure if this is a valid use case for Tracing in Open Telemetry -
Django's Very slow initial execution of select query on remote Oracle 11 database when table contain big blobs
I actually understand what is causing the problem but can't figure out a solution that works with Django. suppose you are trying to read 10,000 records from oracle database over network, normally that would result in 10,000 network connections being open and closed which causes bad performance. Oracle's answer to that is to send say 1000 records at once per connection, that significantly improve the speed. However in my case, each row contains blobs that are 1-2MBs, so trying to prefetch 1000 records means nothing happens until I've downloaded (and kept in memory) 1GB-2GB worth of data. oracle's sqlplus provides option to control that, either using the fast parameter or issuing set rowprefetch 10 but I can't find solution that works with Django. I only want to prefetch 10 records or so -
How to deploy a multi domain/language website with one settings.py
Currently I am running a multi language website. example.com example.it example.at example.ch … example.fr I use the sites framework and run each website in a different docker container like described here. https://docs.djangoproject.com/en/4.2/ref/contrib/sites/#enabling-the-sites-framework In order to serve different sites in production, you’d create a separate settings file with each SITE_ID (perhaps importing from a common settings file to avoid duplicating shared settings) and then specify the appropriate DJANGO_SETTINGS_MODULE for each site. I have a global settings.py and for each website I create a custom settings.py which imports the settings from the global settings.py ├── ... ├── urls.py ├── settings.py ├── sites │ ├── examplecom.py │ ├── exampleit.py │ ├── exampleat.py │ ├── examplech.py │ ├── ... │ └── examplefr.py ├── ... └── wsgi.py Here is an example how my custom examplepl.py file looks like. from myapp.settings import * SITE_ID = 19 LANGUAGE_CODE = SITEID_INFO[SITE_ID]['language'] COUNTRY_CODE = SITEID_INFO[SITE_ID]['country'] ALPHABET_CHARACTERS = SITEID_INFO[SITE_ID]['alphabet'] SITE_RELATED_COUNTRIES = ['PL'] DEFAULT_FROM_EMAIL = SITEID_INFO[SITE_ID]['default_from_email'] DEFAULT_FROM_EMAIL_NAME = SITEID_INFO[SITE_ID]['default_from_email_name'] SHORT_DATE_FORMAT = 'd.m.Y' SOME_TOKEN = 'foobar' AVAILABLE_ORDER_PACKAGES = [28, 5, 6, 29, 14, 15, 30, 23, 24 ] PAYMENT_CURRENCY_CODE = "PLN" PAYMENTOPTION['przelewy24'] = True ... As you can see, I hardcoded the language for each website and setting some specific variables which … -
How to restore deleted permissions on a model in a django project
I want to create a new group and add permissions to the group called "mod". The permission I want to give to this group is Can add, Can Change, Can Delete, and Can View. After I added all the permissions in the "Post" model for the group , I was curious to delete one of the permissions and try to restore it, but the permissions in that model apparently deleted. Here I import the library that I will use. I want to create a new Group called "mod". Then, I want to give permission to that group regarding the "Post" model. import library Below I am trying to add all the permissions in the "Post" model for the "mod" group. try to add all permissions for the group Below I try to display all the permissions that I have set in the "mod" group. Then, I deleted the "main | post | Can add post" permissions. Finally, after I checked, it was true that the permission was removed from the "Post" model. delete one permission However, after I checked the permissions in the "Post" model. The permission was actually deleted. Even though I only want to delete permissions for the … -
Get dustbin locations near user's location and display on leaflet map
I am getting the type of garbage from the backend. Eg: plastic, glass, metal, paper, etc. I am showing the user's location on a map using Leaflet in React. How can I get dustbin locations based on the type of garbage near users' locations in React? I can have garbage type for example const garbage = "glass". Here is my React Leaflet code to display the user's location. <MapContainer center={location} zoom={13} scrollWheelZoom={true} style={{ height: '450px', width: '100%' }}> <TileLayer attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> {location && <Marker position={location} icon={userLocationIcon}> <Popup> Your location </Popup> </Marker> } </MapContainer> I am using Django as the backend where I classify uploaded garbage image. -
Secure connection between django and mysql
We have Django application and we are configuring ssl in the DATABASES settings in settings.py. settings.py DATABASES['default']['ENGINE'] = 'django.db.backends.mysql' DATABASES['default']['NAME'] = 'database' DATABASES['default']['HOST'] = "v2_host" DATABASES['default']['USER'] = "v2_user" DATABASES['default']['PASSWORD'] = "password" DATABASES['default']['CONN_MAX_AGE'] = 180 DATABASES['default']['OPTIONS'] = {'init_command': 'SET SESSION wait_timeout=300', 'ssl': {'cert': "/home/myuser/certpath", 'key': "/home/myuser/keypath", } } We are able to connect the database using this. Db team recently enforce secure/encrypted connection from client. When they enforced, we are start getting error Connections using insecure transport are prohibited while --require_secure_transport=ON. We though, passing ssl is secure connection. But still we are getting error. What we have to pass to make sure connection between Django and mysql are secure? -
Django: list comprehension with Q objects
As far as I know you can create a list of your filters and then just unpack the list inside the filter() or exclude() methods. Looks super convenient. I tried to do just that: words_to_exclude = ['one', 'two', 'three'] excluded_clauses = [Q(title__icontains=word) for word in words_to_exclude] search_result = MyObject.objects.exclude(*excluded_clauses) The query works, but there is one problem. If I create a filter list using this method, this list (excluded_clauses) will look like this: [<Q: (AND: ('title__icontains', 'one'))>, <Q: (AND: ('title__icontains', 'two'))>, <Q: (AND: ('title__icontains', 'three'))>] These are Q objects with AND operator, so the queryset will only exclude objects which do not contain all of the words. And I need it to exclude results where the title includes ANY of the words, so I need the OR operator. Can I manually change the operator in Q objects? Or is there no way to use list comprehension like this? I'm sorry, I know how to write filters manually, but I need this for a filter function with unspecified number of arguments. -
my web application is working ok in my local laptop but online it gives error how to fix it using git
i cant do it with git push proper explanation using git this is a python Django problem how can i fix also it gives error of you are a 1 commmit ahed beside git push give a solution if any one is having proper explanation using git this is a python Django problem how can i fix also it gives error of you are a 1 commmit ahed beside git push give a solution if any one is having -
Trying to send multiple values in a htmx request [Django] [HTMX]
I'm encountering an issue when trying to send two values from the frontend to the backend using htmx. Here's my code: {% include "base.html" %} {% block content %} <div class='flex flex-col h-screen w-screen overflow-y-hidden'> {% include "sidebar.html" %} <div class='h-full flex items-center justify-center'> <div class='w-4/5 max-h-screen h-4/5 border border-black flex flex-col overflow-x-hidden overflow-y-scroll mb-12'> <!-- Form Data --> {% for field, value in data.items %} <div class='w-full h-28 p-1 m-5 flex flex-col mx-24'> <label for="{{ field }}" class="block mb-2 text-sm font-medium text-gray-900">{{ field }}</label> <input type="hidden" name="field" value="{{ field }}"> <input type="text" name="value" value="{{ value }}" class="editable-field bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-3/4 p-2.5" hx-trigger="blur" hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}' hx-post="{% url 'form' formId %}" hx-vals='{"field": "{{ field }}", "value": "{{ value }}"}'> </div> {% endfor %} <!-- End form data --> </div> </div> </div> {% endblock content %} I've tried using hx-vals and included quotes for those values, but the backend only receives the value, not the field. Here's the output in the backend: <QueryDict: {'value': ['valiue']}> valiue None In my view, I'm attempting to retrieve both values using the following code: def post(self, request, formId): print(request.POST) field = request.POST.get('field') value = request.POST.get('value') print(value, field) … -
Django filter many to many fields on admin panel each time
I'm a new Django learner and in my project I'm facing a massive database. I'm using many to many fields for Parts that can be used in several Models(models of Home Appliances) and every model has its own category so my code is kinda like this : class Category(models.Model): name = models.CharField(max_length=255) class Model(models.Model): model_name = models.CharField(max_length=255) model_category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) class Part(models.Model): name = models.CharField(max_length=255) used_models = models.ManyToManyField(Model) so every time I want to add a Part I have choose from lots of Models . there is formfield_for_manytomany but that will filter it for good and I want to filter every time I want to add a Part based on Models categories . if there is a way I would be happy to learn it. -
how to make elasticsearch query to filter specified user out?
I have no idea how to work with elasticsearch, but what I want to do is this: We have companies, which has applications which are created by users Let's say I have a list of all companies now I want to make a filter that when I'm providing user_id, qs returns only those companies where user didn't create application, so the cases where company.application.user.id = user_id exists should be excluded i tried updating existing qs this way: ` def get_queryset(self): .... user_id = self.kwargs.get('user_id') if user_id: qs_dict["query"]["bool"]["filter"].append( { "bool": { "must_not": [ { "terms": { "company.application.user.id": [user_id], }, }, ], }, }, ) ` but i only see an error because "bool" expects true/false, but gets list ([user_id]) instead -
django.db.utils.ProgrammingError: relation " " does not exist when running pytest
I am experiencing a very funny bug in Django. I have gone every way possible including resetting migrations. I have written a pytest for a Django project however the above error occurs when running. -
Paginator only working for one web page django
Paginator is only working for the first index page but it doesn't work on the profile page def profile(request, profile): cur_profile = User.objects.get(username=profile) user_posts = Posts.objects.filter(creator=cur_profile.id).all().order_by('-id') follow_num = cur_profile.following.all().order_by('id') following_num = cur_profile.followers.all().order_by('id') paginator2 = Paginator(user_posts, 5) page_numberr = request.GET.get(paginator2) page_objj = paginator2.get_page(page_numberr) return render(request, "network/profile.html", { "profile": profile, "cur_profile": cur_profile, "user_posts": user_posts, "follow_num": follow_num.count(), "following_num": following_num.count(), "page_objj": page_objj }) my html is this <div class="pagination"> <span class="step-links"> {% if page_objj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_objj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_objj.number }} of {{ page_objj.paginator.num_pages }}. </span> {% if page_objj.has_next %} <a href="?page={{ page_objj.next_page_number }}">next</a> <a href="?page={{ page_objj.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> My first page had the same variable names so i changed them but it didn't work -
Streaming video delay during openCV rtsp streaming
In 'python - django', I created a video streaming on the HTML screen using rtsp and opencv. Initially, the video is output immediately after running the server, but as time passes, the request time increases when re-outputting a new video?? Because of the delay, the video is output late. Also, when you restart the django server, the video is displayed immediately again at first, but becomes slower over time. I am aware that it may not be a code problem. I am not an English speaker, so please understand any translation errors. ---------views.py---------- video_capture_lock = threading.Lock() def gen(camera_id): video_path = f'rtsp://61.84.128.127:554/chID={camera_id}&streamType=main' with video_capture_lock: if camera_id in camera_dict: camera_dict[camera_id].release() del camera_dict[camera_id] cap = cv2.VideoCapture(video_path) camera_dict[camera_id] = cap while True: success, frame = cap.read() if success: reframe = cv2.resize(frame, dsize=(0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) ret, jpeg = cv2.imencode('.jpg', reframe) frame = jpeg.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') else: print(f"Failed to read frame for camera {camera_id}") cap.release() time.sleep(1) cap = cv2.VideoCapture(video_path) camera_dict[camera_id] = cap def streaming(request, camera_id): return StreamingHttpResponse(gen(camera_id), content_type='multipart/x-mixed-replace; boundary=frame') @csrf_exempt def stop_streaming(request): if request.method == 'POST': camera_id = int(request.POST.get('camera')) if camera_id is not None and camera_id in camera_dict: camera_dict[camera_id].release() del camera_dict[camera_id] return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'error', … -
When a user clicks or select the user profile picture in Django, user details should appear
When I select or click the logged user profile image, a multivaluedict key error appears. I want to be able to show and edit user details. when I call objects.all() it shows all user details,but ineed only logged user detail Here is my view.py def profile(request): if request.session.has_key('id'): uid = request.GET.get('sid') if uid is not None: try: profile = registertb.objects.get(id=uid) return render(request, 'profile.html', {'profile': profile}) except registertb.DoesNotExist: return HttpResponse("User not found.") else: return HttpResponse("Sid parameter is missing.") else: return HttpResponseRedirect('/') And here is my html code: <body> {% if profile %} <form action="/myprofile/?sid={{ profile.id }}/" method="post" enctype="multipart/form-data"> {% csrf_token %} <div id="profile-container"> <input type="file" id="image-input" name="user_image" accept="image/*" onchange="displayUserProfile()"> <img id="profile-image" src="{{ profile.user_image.url }}" alt="Profile Picture"> <label for="name">Name:</label> <input type="text" id="name" name="name" value="{{ profile.User_name }}" placeholder="Your Name" required> <label for="email">Email:</label> <input type="email" id="email" name="email" value="{{ profile.email }}" placeholder="Your Email" required> <!-- Other profile fields --> <button type="submit">Update Profile</button> </div> </form> <script> function displayUserProfile() { var input = document.getElementById('image-input'); var image = document.getElementById('profile-image'); // Assuming you're using FileReader to read the selected image var reader = new FileReader(); reader.onload = function (e) { image.src = e.target.result; }; reader.readAsDataURL(input.files[0]); } </script> {% endif %} </body> </html> So this my code -
Celery instead of Async views with asyncio in django
I am new to django! (So basically i am seeking suggestions for this approach). In my project i had so many views and each view had atleast 1 database i/o and as all my views are synchronous i find this is not efficient way, So to make it efficient :- 1.)I can use asyn views with await asyncio on Database update operations (create, update, delete records), but read operations should be done synchronously as it should be delivered to frontend. 2.)I can use celery tasks to do Database update operations and do DB read operations normally. suggest me which approach is better/efficient and are they both logically same for the above usecase? -
Alignment and Table Issues when Copy-Pasting from Doc to Summernote Editor
I am experiencing alignment and table-related issues when copying and pasting content from a document into the Summernote editor. The issues persist when displaying the data on the website. I believe this is a significant problem that needs attention. Steps to Reproduce: Copy content from a document. Paste the content into the Summernote editor. Observe alignment and table issues. Expected Behavior: I expect the copied content to be displayed correctly in terms of alignment and table formatting on the website. Actual Behavior: While copy and paste from doc it is showing alignment and lot of issues in website.