Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mailchimp issue production
the issue is it works fine locally and not on production i have teh same keys in local and production and also when i move config keys up and down on local the error generates on local as well for example if i put key in center it works and if i put on top or last it gives error. But in production it thorougly gives error this is the error An error occured due to : HTTPSConnectionPool(host='us-17.api.mailchimp.com', port=443): Max retries exceeded with url: /3.0/lists/5897c44639/members (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7fd70a0e01f0>: Failed to establish a new connection: [Errno -2] Name or service not known')) @api_view(['POST']) @permission_classes([AllowAny]) def complete_reference(request, short_code): try: try: reference = Reference.objects.get(short_code = short_code) except: return Response({'status' : 400, 'message' : 'No reference found'}) else: reference.dt_referred = timezone.now() message = request.data.get('message') if message: reference.message = message reference.save() i = intercom.intercom_reference_request_submitted(reference) try: mailchimp = MailchimpClient() list_id = settings.MAILCHIMP_AUDIENCE_LIST_ID response = mailchimp.add_to_list( email=reference.email if reference.email else None, phone=reference.phone if reference.email else None, list_id=list_id, tags=[get_campaign_tag(reference.email, reference.phone)] ) except Exception as ex: raise Exception(ex) return Response({'status' : 200, 'message' : f"Reference saved {response['id']}, {response['status']}"}) except Exception as ex: return Response({'status' : 400, 'message' : f"An error occured due to : {str(ex)}"}) ``` -
How to change the empty_label value in Django's ModelChoiceField?
In Django, I’m using a ModelChoiceField with the empty_label parameter to allow users to unselect a value in a dropdown. Here’s the code: department = forms.ModelChoiceField( queryset=Department.objects.all(), label="Department", required=False, empty_label="------" # Add an empty option ) This works fine, but the default behavior assigns an empty string ("") as the value for the empty_label option. Unfortunately, one of the JavaScript libraries I’m using does not handle empty string values properly. I need to assign a custom value (e.g., -1) for the empty_label option, but I still want to retain its functionality to "unselect" the current object. I’ve tried overriding the choices in the init method, like this: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['department'].widget.choices = [("-1", "------")] + list( self.fields['department'].queryset.values_list('id', 'name') ) However, when I do this, the functionality doesn’t work as expected — it doesn’t allow the "unselect" option as it does with the empty_label. How can I change the empty_label value (from the empty string) to -1 and still maintain the same behavior of unselecting the option? Thanks in advance for your help! -
Is this api endpoint is correctly following standard REST guidelines [closed]
List Bundles added to the wishlist GET http://localhost:8000/api/bundles/?wishlist=true Add Bundle to wishlist POST http://localhost:8000/api/bundles/0f0c6be3-665d-4d98-8153-817149bcd3bc/wishlist/ Remove bundle from wishlist DELETE http://localhost:8000/api/bundles/0f0c6be3-665d-4d98-8153-817149bcd3bc/wishlist/ In the response of the bundles API I am sending the is_in_wishlist boolean I am confuse -
Django model FileField with dynamic storage location in migration
I need to store file outside MEDIA_ROOT so I use this approach from django.core.files.storage import FileSystemStorage from django.db import models from myproject.settings import SOME_DIR fs = FileSystemStorage(location=SOME_DIR) class Car(models.Model): photo = models.ImageField(storage=fs) Now, when I makemigrations the result is something like: migrations.AlterField( model_name='car', name='photo', field=models.ImageField(storage=django.core.files.storage.FileSystemStorage(location='C:/temp/documents')), ), The problem is that my local path to SOME_DIR is hardcoded in migration file. So when I push it to production server, where SOME_DIR is /home/xyz/documents, I get warning: Your models in app(s): 'x' have changes that are not yet reflected in a migration, and so won't be applied. Is there any way to suppress the warning or change my code, so it won't use the dynamic location path in migration file? I use Django 4.2, but I think it's the same in all versions. Thanks a lot for help -
How to load 3D models in Django
This is the main.js file that i have for a website that i just made: // Import necessary Three.js modules import * as THREE from 'three'; import { GLTFLoader } from './libs/addons/loaders/GLTFLoader.js'; import { OrbitControls } from './libs/addons/controls/OrbitControls.js'; // Get the container element for the 3D model const modelContainer = document.getElementById('model-container'); // Create a WebGL renderer with transparency and anti-aliasing const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.outputColorSpace = THREE.SRGBColorSpace; // Function to handle renderer resize function updateRendererSize() { renderer.setSize(window.innerWidth, window.innerHeight); } updateRendererSize(); // Configure renderer settings renderer.setClearColor(0x000000, 0); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; modelContainer.appendChild(renderer.domElement); const scene = new THREE.Scene(); scene.background = null; // Lighting setup const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); scene.add(ambientLight); const directionalLight1 = new THREE.DirectionalLight(0xffffff, 1.5); directionalLight1.position.set(5, 5, 5); directionalLight1.castShadow = true; scene.add(directionalLight1); const directionalLight2 = new THREE.DirectionalLight(0xffd700, 1); directionalLight2.position.set(-5, 3, -5); scene.add(directionalLight2); const frontLight = new THREE.DirectionalLight(0xffffff, 1); frontLight.position.set(0, 0, 5); scene.add(frontLight); const pointLight1 = new THREE.PointLight(0xff9000, 1, 10); pointLight1.position.set(2, 2, 2); scene.add(pointLight1); const pointLight2 = new THREE.PointLight(0x0066ff, 1, 10); pointLight2.position.set(-2, 2, -2); scene.add(pointLight2); // Camera setup const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000); camera.position.set(4, 5, 11); // Controls setup const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping … -
add a button for transcription to a Django form
I am building a website and have views with Django forms. I want to add a transcription button to each field in the Django form class PostForm(StylishForm): class Meta: model = Post fields = ["title", "body", "upload"] widgets = { "owner": forms.HiddenInput(), } and give the user the option either to fill the form by typing or pressing the button to transcribe then filling the field. # add new def add(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.owner = request.user post.save() return HttpResponseRedirect(reverse("view_posts")) else: form = PostForm() return render( request, "posts/index.html", { "form": form, }, ) I have prepared the function to use whisper api for transcription. def record_audio(request): RATE = 16000 CHUNK = 1024 recordings = os.path.join(settings.MEDIA_ROOT, 'recordings') # Ensure the folder exists if not os.path.exists(recordings): os.makedirs('recordings') # Define the path to save the audio file file_path = os.path.join(recordings, 'output.wav') # def callback(data_input, frame_count, time_info, status): # wav_file.writeframes(data_input) # return None, pyaudio.paContinue with wave.open(file_path, "wb") as wav_file: wav_file.setnchannels(1) # Mono channel wav_file.setsampwidth(2) # 16-bit samples wav_file.setframerate(16000) # 16kHz sample rate audio = pyaudio.PyAudio() stream = audio.open( format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK, ) for _ in range(0, RATE // CHUNK): wav_file.writeframes(stream.read(CHUNK)) stream.stop_stream() stream.close() … -
Python Django Hangs at runserver
Any ideas on how to solve this issue? Is there a way to show some logs/errors while runserver is being executed (hanged)? When running: python manage.py runserver It hangs... (venv-saas) jdv@jdv-MBP src % python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). -
Testing an Update a Post function
I'm not really sure about how to update blog posts based on my code. I've been using method-based views. def create_post(request): form_class = PostForm template = 'addpost.html' if request.method == "POST": form = form_class(request.POST) title = request.POST.get("title") content = request.POST.get("content") user_id = request.POST.get("author") if request.user.has_perm("posts.add_post"): Post.objects.create( title=title, content=content, author=User.objects.get(pk=user_id) ) else: pass return render(request, template) def edit_post(request): form_class = PostForm template = 'editpost.html' if request.method == "PATCH": form = form_class(request.PATCH) Title = request.PATCH.GET("title") Content = request.PATCH.GET("content") User_id = request.PATCH.GET("author") if request.user.has_perm("posts.update_post") and (User_id == User.pk): Post.objects.update( title=Title, content=Content, author=User.objects.get(pk=User_id) ) else: pass return render(request, template) For the update_post method, do I use PATCH, UPDATE, or a POST request in this scenario? Keep in mind that I'm also using this method for testing purposes as well. Here's the Pytest Code: class TestPermissions: @pytest.mark.django_db def test_post_add_contributor_group_permission(db): client = Client() user = User.objects.create_user( username="testuser", email="test@example.com", password="pass123" ) post_data = { "title": "Post Title", "content": "Post Content", "author": user.id } group = Group.objects.create(name="Contributor") client.login(username="testuser", password="pass123") response = client.post(reverse("add_post"), post_data) assert response.status_code == 200 assert Post.objects.all().count() == 0 content_type = ContentType.objects.get_for_model(Post) permission = Permission.objects.get( content_type=content_type, codename__icontains="add" ) group.permissions.add(permission) user.groups.add(group) response = client.post(reverse("add_post"), post_data) assert response.status_code == 200 assert Post.objects.all().count() == 0 @pytest.mark.django_db def test_post_update_contributor_group_permission(db): client … -
How to lock read access while creating a model in django?
We notice a lot of trouble within our django application, where we use get_or_create. model, created = SomeModel.objects.get_or_create(user=user, name=name, defaults={...}); if created: get_some_dimensions # SLOW as we call to third party model.dimension_values.set(created_dimensions) # Code here that depends on dimensions being there for the model The problem is that the code above runs twice at the same time. The first time it creates the model, it starts "get_some_dimensions" but doesn't finish that (so not saved) then the second time runs and it sees the model is already there the second run however goes to the "cod here that depends on dimensions" before the first run saves. At step 3 the database gets transformed to an erroneous state. How can I prevent the second run of actually running, lock the database, until the full object is built? -
How to make a dropdown list that can send data to Django (to Models) with Kivymd?
I found a recipe where I could save the results into a variable using the instructions in the KivyMD documentation, but some of the codes shared there did not work in my editor. So, the versions I use are: "python 3.11", "kivymd version 1.2.0" and the MDDropDownItemText module I need to use is not included in kivymd. For this reason, I cannot give special IDs to items and I cannot save the selected values into a variable. What can be done here? My goal was to record whether the user was male or female in the model I created in Django. And I thought I could do this by transferring the result from the drop down list into a variable. I tried following the instructions in the Kivymd documentation, but I encountered the results I mentioned above. KivyMD documentation: text -
How can I make an rtsp stream as correct as possible in a Django application?
I am writing a mini video surveillance system on Django. I want the stream to be output to the tag. now I have output to the img tag using a stream and jpeg images (using OpenCV)how to make a stream from a video, you may need to use WebRTC for the stream and somehow decode the video using ffmpeg, please tell me def generate_frames(rtsp_url): cap = cv2.VideoCapture(rtsp_url) # Замените на ваш RTSP URL while True: success, frame = cap.read() if not success: break # Кодируем кадр в JPEG ret, buffer = cv2.imencode('.mp4', frame) frame = buffer.tobytes() yield (b'--frame\r\n' b'Content-Type: video/mp4\r\n\r\n' + frame + b'\r\n') i vant to stop video and start in video tag my html looks like this <div class="video-container"> <img src="{% url 'video_feed' %}?rtspurl={{ rtsp_url }}" width="640" height="480" alt="{{ rtsp_url }}" /> <div class="separator"></div> <!-- Added separator div --> <p class="cam-name">Трансляция камеры: {{ cam_name }}<br>RTSP: <a>{{ rtsp_url }}</a></p> </div> -
Django websocket channel message handler not executing after invocation in webhook
Objective - Setup and run django as asgi, have a websocket endpoint. Accept webhook request in django and send udpates to websocket so all clients listening to websocket will be notified. Views.py from django.shortcuts import render from django.http import JsonResponse from channels.layers import get_channel_layer from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST def websocket_notifications(request): return render(request, 'my_app/notifications.html') @csrf_exempt @require_POST def send_message_to_websocket(request): message = request.POST.get('message', 'Hello, WebSocket clients!') # Get the channel layer channel_layer = get_channel_layer() # Broadcast the message to the WebSocket group channel_layer.group_send( 'notifications_notification_room', # The group name (matches your consumer) { 'type': 'chat_message', # Type that the consumer will listen for 'message': message } ) return JsonResponse({'status': 'Message sent', 'message': message}) consumers.py import json import logging import asyncio from channels.generic.websocket import AsyncWebsocketConsumer # Set up a logger logger = logging.getLogger(__name__) class MyWebSocketConsumer(AsyncWebsocketConsumer): async def connect(self): logger.debug(f"WebSocket connection attempt from {self.channel_name}") print(f"WebSocket connection attempt from {self.channel_name}") self.room_name = 'notification_room' self.room_group_name = f'notifications_{self.room_name}' # Log to confirm the WebSocket joins the group logger.debug(f"Joining group: {self.room_group_name}") await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() # Start a task to send messages every 2 seconds # self.message_task = asyncio.create_task(self.send_periodic_messages()) async def disconnect(self, close_code): logger.debug(f"WebSocket connection closed for {self.channel_name} (Close code: {close_code})") # Cancel … -
How can I solve pycharm django type hint problem
I am using pyhcarm. My pycharm syas “Expected type QuerySet[MemberMetaModel, MemberMetaModel], got QuerySet[MemberMetaModel] istead” I think this lint info is wrong, how can I fix my lint? Or if this warnning is right, how can I fix my code? Plz save me, this warnning is so annoying… (I am using python 3.13.0, black, pydantic, mypy) Thanks -
Pymemcache OSError: [Errno 99] Cannot assign requested address
Context: We have a django application running inside a container on our cloud instance. We recently started seeing errors when we try to access value from django cache in an api end point. cache.get('key') This api endpoint is very frequently accessed by our users. The full error that we are seeing is attached below. Error trace Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/srv/www/iridize/tipcms/views.py", line 2141, in cross_app_new cache_value = cache.get(cache_key, {}) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/cache/backends/memcached.py", line 75, in get return self._cache.get(key, default) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/pymemcache/client/hash.py", line 347, in get return self._run_cmd("get", key, default, default=default, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/pymemcache/client/hash.py", line 322, in _run_cmd return self._safely_run_func(client, func, default_val, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/pymemcache/client/hash.py", line 211, in _safely_run_func result = func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/pymemcache/client/base.py", line 1494, in get return client.get(key, default) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/pymemcache/client/base.py", line 687, in get return self._fetch_cmd(b"get", [key], False, key_prefix=self.key_prefix).get( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/pymemcache/client/base.py", line 1133, in _fetch_cmd self._connect() File "/usr/local/lib/python3.11/site-packages/pymemcache/client/base.py", line 424, in _connect sock.connect(sockaddr) OSError: [Errno 99] Cannot assign requested address We are using memcached for caching … -
No run django, Cannot install django
PS D:\aaa\WorkSpace_31\py\testDjango\test\hello> python manage.py runserver 8888 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Hoang\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner self.run() File "C:\Users\Hoang\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1010, in run self._target(*self._args, **self._kwargs) File "D:\aaa\WorkSpace_31\py\testDjango\test\env\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\aaa\WorkSpace_31\py\testDjango\test\env\Lib\site-packages\django\core\management\commands\runserver.py", line 144, in inner_run run( File "D:\aaa\WorkSpace_31\py\testDjango\test\env\Lib\site-packages\django\core\servers\basehttp.py", line 270, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\aaa\WorkSpace_31\py\testDjango\test\env\Lib\site-packages\django\core\servers\basehttp.py", line 77, in init super().init(*args, **kwargs) File "C:\Users\Hoang\AppData\Local\Programs\Python\Python312\Lib\socketserver.py", line 457, in init self.server_bind() File "C:\Users\Hoang\AppData\Local\Programs\Python\Python312\Lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\Hoang\AppData\Local\Programs\Python\Python312\Lib\http\server.py", line 138, in server_bind self.server_name = socket.getfqdn(host) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hoang\AppData\Local\Programs\Python\Python312\Lib\socket.py", line 795, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) ^^^^^^^^^^^^^^^^^^^ UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 19: invalid start byte I have changed the computer name I have switched to an older version I have installed navicat, xampp, SQL Server Management Studio 19 -
Digital Ocean Spaces and Django: Can upload but not open/check if the file exists
I am able to upload to my digital ocean space using my api key from my django app on python 3.10.13. I can see the files as well as open the hyperlinks to them successfully. Images that get uploaded show up on my site as expected. I made all the files public, I've made and re-made my api-keys, I've made my own Media Storage class (I was able to backdoor the functionality by using the response library but that was very slow). I disabled the CDN in case that was interfering. I've re-arranged my folder structure. Tried CORS allow *. Below is the relevant code I am working with. ... CREDS ABOVE AWS_S3_ENDPOINT_URL = config["remote_storage"]["AWS_S3_ENDPOINT_URL"] AWS_LOCATION = 'media' AWS_QUERYSTRING_AUTH = False # Set to False if files are public MEDIA_URL = f"https://{AWS_S3_ENDPOINT_URL}/{AWS_LOCATION}/" DEFAULT_FILE_STORAGE = 'spyglass.storage_backends.MediaStorage' class MediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' querystring_auth = False def exists(self, name): print(f"Checking if {self.url(name)} exists") return super().exists(name) The link that is printed works without a problem however the exists returns False. I've been scratching my head for 2 days and could really use a nudge in the right direction as this is all new to me. -
How to configure JWT to work with cookies?
I have a Django application that functions as an API. Currently, it can generate access and refresh JWT tokens and save these tokens as cookies. My problem arises when verifying these tokens in other endpoints. Even though they are being sent correctly, authentication fails. It would be too much information to explain here, but I customized the user class and configured it to use JWT. I appreciate any help, as I'm not sure what to do. When I try to access an endpoint that requires authentication with a token, I receive the message 'Authentication credentials were not provided' and get a 401 error in the response. I believe it could be an issue with the parent class, maybe a method that wasn't overridden but should have been. Here's the repository of the project, which is a small-scale study/test project: https://github.com/MasterTJ123/servant_rpg_back -
How do I GET and POST from different urls to the same class based view in my django project?
I am working on this coursework where I need to create a Django back-end with API routes and templated routes. Within the descriptor, I was given the routes which the project needs to follow. I made a class based view which successfully creates albums. However, the issue which I see is that my implementation GET and POST to /albums/new. Where the descriptor, says I have to GET from /albums/new and POST to /albums to create a new album. I've looked everywhere online to figure out how to implement this and haven't found anything. The lecturer then gave us a tip: The POST of /albums/new/ could be mapped to POST /albums/ using the Django URL dispatcher, where it calls the same class or method for POST. But still had no luck finding anything. Here's my code: views.py album creation view class AlbumCreateView(SuccessMessageMixin, generic.edit.CreateView): form_class = AlbumForm template_name = 'label_music_manager/update_album.html' success_message = _('AlbumCreated') def get_success_url(self): return self.object.get_absolute_url() def dispatch(self, request): if not check_editor(request.user): return redirect('album_list') return super().dispatch(request) url patterns of my view (I created a temporary fix where I can POST to /albums by calling the same view but I don't think that's intended because they wouldn't have separated it) path('albums/', views.AlbumCreateView.as_view(), … -
Problem with Django Forms and models (Enter a valid URL.)
My idea is to get a img from the user using the form (it can be local on her computer) and after the form is sent the system upload it to imgBB. The problem is that the form is not valid, because it says "Enter a valid URL.". class FeriaForm(forms.ModelForm): #... Others fields image = forms.URLField( label="", widget=forms.ClearableFileInput(attrs={'class': 'form-input'}) ) class Meta: model = JobFair fields = [ 'title', 'description', 'start_event_date', 'end_event_date', 'start_hour', 'end_hour', 'department', 'city', 'direction', 'maximum_capacity', 'is_visible', 'keynote_speaker', 'image' ] This model JobFair class JobFair(models.Model): organizer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='job_fairs', null=True) title = models.CharField(max_length=255) description = models.TextField() start_event_date = models.DateField() end_event_date = models.DateField(null=True) department = models.CharField(max_length=255) city = models.CharField(max_length=255) start_hour = models.TimeField(auto_now=False, auto_now_add=False) end_hour = models.TimeField(auto_now=False, auto_now_add=False, null=True) maximum_capacity = models.IntegerField(null=True) number_of_registered = models.IntegerField(default=0, null=True) is_visible = models.BooleanField(default=True) direction = models.CharField(max_length=255) keynote_speaker = models.CharField(max_length=255) image = models.URLField(blank=True, null=True) and this view where I used the form. def add_fair_view(request): if request.method == 'POST': form = FeriaForm(request.POST, request.FILES) # Manejar datos y archivos if form.is_valid(): image_file = request.FILES.get('image') # Obtener el archivo de la imagen # Subir el archivo a ImgBB try: response = requests.post( IMGBB_API_URL, data={'key': config('IMGBB_API_KEY')}, files={ 'image': (image_file.name, image_file.file, image_file.content_type) } ) response_data = response.json() if response.status_code … -
DRF issue while attempting to inspectdb command error appears: # The error was: ORA-00904: "USER_TABLES"."DEFAULT_COLLATION": invalid identifier
I have an Oracle database version 11.5.10.2. Recently, I study DjangoRestFramework in order to perform own APIs. Firstly, command python manage.py runserver doesn't work due to unable to connect to database. Then I imported oracledb module to settings.py file and added following command: oracledb.init_oracle_client(lib_dir=r'C:\\oracle\\instantclient_23_6') Without client no any connection appears for Oracle database. After that command 'python manage.py runserver' does connect to Oracle DB without errors. Since I don't need to do any changes in database due to many finance records I would upload models structure for my necessary tables only for API use GET HTTP method protocol. So, not at all tables are need to be inspected and moved to models.py file. Thus, for testing I add following command im command prompt: 'python manage.py inspectdb ap.ap_invoices_all' and output text is following: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # \* Rearrange models' order # \* Make sure each model has one field with primary_key=True # \* Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # \* Remove `managed = False` lines if you wish to allow Django to create, modify, and … -
Google Picker popup window not loading - Django
I am using Google's documentation on the Google Picker at https://developers.google.com/drive/picker/guides/sample and the popup for google drive is not opening when i use this code in django template. I authorize my gmail account but the popup is just not loading. It works fine when i run it via live server on a plain html ( so everything is setup good regarding API_KEY, CLIENT_ID and APP_ID ) but when i run the code inside django, the popup is not there. I tried 3 different (django) projects and the issue persists. Google console is not showing any errors, nothing, it's blank. I do see that APIs return 200 message, so i suspect something about Django is not working well. Cookies or whatever it can be, but i spent past several hours on this and can't find a solution -
How to persist model changes for specific models on transaction rollback in django atomic request
I have a Django project with ATOMIC_REQUESTS=True. When authentication fails I need to store critical data for the login attempt, here is example code: class LoginSerializer(serializers.Serializer): ... def validate(self, data): ... user = authenticate(email=email, password=password) if user is None: failed_login_attempt(email) raise serializers.ValidationError("Invalid credentials") def failed_login_attempt(email): user = User.objects.get(email=email) user.lock_status = "LOCKED" user.save() Device.objects.create(user=user, ip="127.0.0.1", fingerprint="some-fingerprint") Activity.objects.create(user=user, type="failed_login_attempt") Constraints: Raising the ValidationError causes all changes (including updates to user.lock_status, Device and Activity) to be rolled back. This behavior is expected because of the global transaction but I need these changes to persist. I cannot remove ATOMIC_REQUESTS=True as it's crucial for other parts of the application. Goal: I want to ensure that the failed_login_attempt function persists changes even if the ValidationError rolls back the rest of the transaction. What’s the best way to persist those critical changes? What I've tried: Wrapping failed_login_attempt in transaction.atomic() This doesn’t work because they are still part of the outer transaction. Bypassing the ORM and using raw SQL connections.cursor() feels like a hack so I would prefer to avoid it. -
Single 'through' model for multiple m2m fields
I'm trying to extend and refactor some legacy project. I have some set of models which represent "hardware" of some assebled device. Something like : class ComponentA(models.Model) brand = models.CharField() model = models.CharField() category = models.ForeignKey(Category) class Configuration(models.Model): component_a = ForeignKey(ComponentA) component_b = ForeignKey(ComponentB) component_n... class Device(models.Model): configuration = models.ForeignKey(Configuration) The goal is to extent ComponentA...ComponentN with Many2Many field which suppose to contain some extra parts and those parts quantity it consist of. However I found it weird to have through model for each Component model. All of the Component models shoud have a quantity for further statistic/calculations. Is there is some "clean" approach for implementation such a functionality? -
Firebase Push Notifications are not received in Django template but working in other external applications
I have a major problem with Firebase push notifications. I have a Django application with a configured function to send notifications. The function works for sending notifications to a mobile app and a separate React app. However, recently there has been a need for notifications to also reach the same application in Django - meaning the server sends a notification, and the template receives and displays an alert. I configured everything as per the documentation, and notifications are received when they originate from the Firebase console, but those sent from my server are completely ignored and not received. Where should I start looking for the issue? Let me add that sending notifications does not throw any errors. I’m out of ideas on what to do. -
Want to integrate onlyoffice text editor in my project
I used React in frontend and django in bbackend want to use onlyoffice text editor i used docker container and follow the steps after running in frontend i got pop up message that the document security token is not correctly formed .please contact your Document Administrator. I'll try to create api and then integrate in frontend but got that message