Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get Django-CMS to work with Apache and mod_wsgi
I am trying to get django-cms to run with apache wsgi. I am using Python 3.12 and the latest version of all software (a fresh bare metal install of ubuntu 24.04). Django-cms runs with runserver. My vhost file: Define impact_lab_partners_path /home/mark/python-projects/impact_lab_partners WSGIApplicationGroup %{GLOBAL} <VirtualHost *:80> ServerName impactlabpartners.com ServerAlias www.impactlabpartners.com ServerAdmin xxxxxxxxxxxxxxxxx DocumentRoot /home/mark/python-projects/impact_lab_partners ProxyRequests off ProxyPreserveHost On WSGIDaemonProcess ilp python-home=/home/mark/.virtualenvs/impact_lab_partners python-path=${impact_lab_partners_path}/impact_lab_partners WSGIProcessGroup ilp WSGIScriptAlias / ${impact_lab_partners_path}/impact_lab_parthers/wsgi.py process-group=ilp Alias /static "/home/mark/Documents/impact_lab_partners/do_not_change/static" <Directory "/home/mark/Documents/impact_lab_partners/do_not_change/static"> Require all granted </Directory> Alias /documents "/home/mark/Documents/impact_lab_partners/do_not_change/documents" <Directory "/home/mark/Documents/impact_lab_partners/do_not_change/documents"> Require all granted </Directory> <Directory ${impact_lab_partners_path}/impact_lab_partners> <Files wsgi.py> Require all granted </Files> </Directory> # LogLevel Debug # LogLevel debug # ErrorLog ${APACHE_LOG_DIR}/impact_lab_partners/error.log # CustomLog ${APACHE_LOG_DIR}/impact_lab_partners/access.log combined </VirtualHost> I have verified the paths are correct. The error I am getting in /var/log/apache2/error.log every second or so: Current thread 0x0000731f722d1780 (most recent call first): <no Python frame> [Thu Dec 05 18:27:05.634492 2024] [wsgi:warn] [pid 21694:tid 126578896738176] (13)Permission denied: mod_wsgi (pid=21694): Unable to stat Python home /home/mark/.virtualenvs/impact_lab_partners. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/mark/.virtualenvs/impact_lab_partners' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = … -
How to revert migrations when there are multiple leaf nodes?
manage.py showmigrations shows me a list like ... [X] 0240_employer_data (A) [X] 0241_person_metadata (B) [ ] 0242_delete_capability_delete_collection (C) [X] 0242_personemployer_employerworkplace (D) [X] 0243_personemployer_employed_personemployer_stage (E) [X] 0244_remove_employerworkplace_and_more (F) 0242_delete_capability_delete_collection arrived after doing a git pull and rebase. My local branch stuff that I had been working with is 0242_personempl..0244. I believe the graph looks like | A | B / \ D C | E | F Because all my migrations are just in development, I'm trying to undo them to reach the same state that the main branch is at, then make them again. I thought I could manage.py migrate myapp C delete my local D, E, F migration files files manage.py makemigrations manage.py migrate But both manage.py migrate myapp C and manage.py migrate myapp B throw the same error: CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0242_delete_capability_delete_collection, 0244_remove_employerworkplace_and_more in myapp). It looks like I cannot even revert migrations while the migration graph is in this state. What can I do to just reset my local branch's migrations and compatibilise with the main branch before building my local branch's needed migrations again? "Rebasing" the migrations in a way? -
How do I convert a complex Postgres SQL query into a Django queryset?
I have the following SQL query working: SELECT mrc.token_id, ARRAY_AGG(mt.name) AS tracking FROM markets_rankscurrent mrc LEFT JOIN ( SELECT mtg.id, mtg.index_id, mtg.favorites_group_id, mtg.name, COALESCE(ufe.token_id, mte.token_id, mie.token_id) AS token_id FROM markets_trackinggroup mtg LEFT JOIN users_favoritesentry ufe ON mtg.favorites_group_id = ufe.group_id LEFT JOIN markets_trackingentry mte ON mtg.id = mte.group_id LEFT JOIN markets_indexentry mie ON mtg.index_id = mie.index_id ) mt ON mrc.token_id = mt.token_id GROUP BY mrc.token_id; Here are my models: class Token(models.Model): class RanksCurrent(models.Model): token = models.ForeignKey(Token, on_delete=models.CASCADE, db_index=False) class TrackingGroup(models.Model): name = models.CharField(max_length=60, verbose_name='Name') favorites_group = models.ForeignKey(FavoritesGroup, on_delete=models.CASCADE, related_name='tracking_groups', blank=True, null=True) index = models.ForeignKey(Token, on_delete=models.CASCADE, related_name='tracking_groups', blank=True, null=True) class TrackingEntry(models.Model): group = models.ForeignKey(TrackingGroup, on_delete=models.CASCADE, related_name='tokens') token = models.ForeignKey(Token, on_delete=models.CASCADE, related_name='tracking_entries') class IndexEntry(models.Model): index = models.ForeignKey(Token, on_delete=models.CASCADE, related_name='index_tokens') token = models.ForeignKey(Token, on_delete=models.CASCADE, related_name='indices') class FavoritesGroup(models.Model): pass class FavoritesEntry(models.Model): group = models.ForeignKey(FavoritesGroup, on_delete=models.CASCADE, related_name='favorites_entries') token = models.ForeignKey('markets.Token', on_delete=models.CASCADE, related_name='favorites_entries') The TrackingGroup.index foreign key will only be set to a Token object that is also a foreign key in the IndexEntry table. My end goal is to be able to query the RanksCurrent table and annotate a tracking_groups column that contains a list of TrackingGroup names where the Token is a member. My attempts have made use of Subquery and ArrayAgg to try and … -
Django / Stripe - Webhook not found
I am trying to establish a webhook with stripe. (first timer) However, it seems the path to the webhook is not found. Hoping someone might be able to bring a pair of fresh eyes and tell me what I am doing wrong. In my urls.py (project level) urlpatterns = [ path('my_app/', include('my_app.urls')), ... ] In urls.py app level: urlpatterns = [ .. path('stripe_webhook/', views.stripe_webhook, name='stripe_webhook') ] In my views.py (my_app level): @csrf_exempt def stripe_webhook(request): print("enter webhook") stripe.api_key = settings.STRIPE_SECRET_KEY_TEST payload = request.body signature_header = request.META.get('HTTP_STRIPE_SIGNATURE') webhook_secret = settings.STRIPE_WEBHOOK_SECRET_TEST ... In stripe, in local listenners I have regiestered: localhost:8000/stripe_webhook/ If I run stripe trigger customer.created. I get the following returned to me: A newer version of the Stripe CLI is available, please update to: v1.22.0 Setting up fixture for: customer Running fixture for: customer Trigger succeeded! Check dashboard for event details. However, running simultaneously stripe listen --forward-to localhost:8000/stripe_webhook/, I also get the following logs: > Ready! You are using Stripe API Version [2024-09-30.acacia]. Your webhook signing secret is XXXXX (^C to quit) 2024-12-05 22:27:54 --> customer.created [xxx] 2024-12-05 22:27:54 <-- [404] POST http://localhost:8000/stripe_webhook/ [xx] and my server logs will also return (whether in production or local): Not Found: /stripe_webhook/. This makes … -
django, how to use subquery values into outer query
I have a query that uses the values from a subquery. While I'm able to write the subquery in django, I can't write the main query. Here's a little example (the schema is department <-- person <-- device --> model): SELECT department.id, AVG(subquery.typeofdevices_count) AS avg_typeofdevice_count_per_department FROM department INNER JOIN person ON (department.id = person.department_id) INNER JOIN device ON (person.id = device.person_id) INNER JOIN ( SELECT model.id AS id, count(DISTINCT device.location_id) filter (WHERE device.type = 'something') AS typeofdevices_count, FROM model LEFT OUTER JOIN device ON (model.id = device.model_id) WHERE ('some-conditions...') GROUP BY model.id, ) AS subquery ON (subquery.id = device.model_id) As you can see the outer query uses the inner value typeofdevices_count while joining with the subquery id. About the inner query is quite simple: subquery = Model.objects.annotate(typeofdevices_count= Count('device__location_id', filter=Q(device__type='something'), distinct=True ) ).filter('some-conditions...').values('id', 'typeofdevices_count') What about the main query? I tried with the following: Department.objects.annotate(avg_typeofdevice_count_per_department= Avg('persons__devices__model__typeofdevices_count', filter=Q(persons__devices__model__in=subquery) ) ).values('id', 'avg_typeofdevice_count_per_department') But I got this error, it seems it doesn't recognize the subquery annotation typeofdevices_count FieldError: Cannot resolve keyword 'typeofdevices_count' into field. Choices are:... Can you help me? -
wsgi process not loading the correct python environment
Unfortunately no relevant help found so far - even if a lot of similar questions have been raised. I had an issue with configuring 2 separate django projects on the same server, where I can't use subdomains. This lead me to Multiple mod_wsgi apps on one virtual host directing to wrong app which helped by utilizing the <location> tag to get closer to a solution. Here's the remaining problem: I have configured 1 virutal host with ssl and 2 different "sites": <VirtualHost *:443> ServerName myserver.com SSLEngine on SSLCertificateFile /etc/httpd/ssl/myserver.com.crt SSLCertificateKeyFile /etc/httpd/ssl/myserver.com.key SSLCACertificateFile /etc/httpd/ssl/myserver.com.bundle # anspl4fd configuration Alias /anspl4fd/static/ /var/customers/webs/anspl4fd/static/ <Directory /var/customers/webs/anspl4fd/static> Require all granted </Directory> WSGIDaemonProcess anspl4fd python-home=/var/customers/python-env/anspl4fd python-path=/var/customers/webs/anspl4fd WSGIScriptAlias /anspl4fd /var/customers/webs/anspl4fd/Webseite/wsgi.py <Location /anspl4fd> WSGIProcessGroup anspl4fd </Location> <Directory /var/customers/webs/anspl4fd/Webseite> <Files wsgi.py> Require all granted </Files> </Directory> # anscrd configuration Alias /anscrd/static/ /var/customers/webs/anscrd/static/ <Directory /var/customers/webs/anscrd/static> Require all granted </Directory> WSGIScriptAlias /anscrd /var/customers/webs/anscrd/Webseite/wsgi.py WSGIDaemonProcess anscrd python-home=/var/customers/python-env/anscrd python-path=/var/customers/webs/anscrd <Location /ancrd> WSGIProcessGroup anscrd </Location> <Directory /var/customers/webs/anscrd/Webseite> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> But, the 2nd site configuration "anscrd" doesn't work off the correct python-environment. It uses the system default, verified by executing: sys.stderr.write(f"Python executable: {sys.executable}\n") sys.stderr.write(f"Python version: {sys.version}\n") sys.stderr.write(f"Python path: {sys.path}\n") in my "sites" wsgi.py Now, adding: sys.path.insert(0, '/var/customers/webs/anscrd') # Project directory … -
django ManyToMany field update
I have trouble with updating calculating_special_order_items, calculating_floor_special_order_items, order_total, ship_total, confirm_total, real_total and calculating_total. When I save a new instance with ship_special_order_items through a view it saves normally, calculating_special_order_items is updated and all totals are updated correctly and it is showed in django admin site correctly, but when I try to update calculating_special_order_items with saving confirm_special_order_items it is not updating correctly. class Order(models.Model): STATUS_CHOICES = [("naruceno","naruceno"), ("poslato","poslato"), ("stiglo","stiglo")] ordering_facility = models.ForeignKey(Facility, on_delete=models.PROTECT, related_name='order_create_facility') dispatching_facility = models.ForeignKey(Facility, on_delete=models.PROTECT, related_name='order_dispatch_facility') order_timestamp = models.DateTimeField(auto_now_add=True) ship_timestamp = models.DateTimeField(blank=True, null=True) confirm_timestamp = models.DateTimeField(blank=True, null=True) real_timestamp = models.DateTimeField(blank=True, null=True) order_user = models.CharField(max_length=100, blank=True) ship_user = models.CharField(max_length=100, blank=True) confirm_user = models.CharField(max_length=100, blank=True) real_user = models.CharField(max_length=100, blank=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=STATUS_CHOICES[0][0]) product_variations = models.ManyToManyField(ProductVariation, through='OrderItem') order_total = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True) ship_total = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True) confirm_total = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True) real_total = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True) calculating_total = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True) ship_special_order_items = models.ManyToManyField(SpecialOrderItem, blank=True, related_name='ship_special_order_items') ship_floor_special_order_items = models.ManyToManyField(FloorSpecialOrderItem, blank=True, related_name='ship_floor_special_order_items') confirm_special_order_items = models.ManyToManyField(SpecialOrderItem, blank=True, related_name='confirm_special_order_items') confirm_floor_special_order_items = models.ManyToManyField(FloorSpecialOrderItem, blank=True, related_name='confirm_floor_special_order_items') real_special_order_items = models.ManyToManyField(SpecialOrderItem, blank=True, related_name='real_special_order_items') real_floor_special_order_items = models.ManyToManyField(FloorSpecialOrderItem, blank=True, related_name='real_floor_special_order_items') calculating_special_order_items = models.ManyToManyField(SpecialOrderItem, blank=True, related_name='calculating_special_order_items') calculating_floor_special_order_items = models.ManyToManyField(FloorSpecialOrderItem, blank=True, related_name='calculating_floor_special_order_items') billed = models.BooleanField(default=False) def calculate_calculating_special_order_items(self): if self.real_special_order_items.exists(): return self.real_special_order_items.all() elif self.confirm_special_order_items.exists(): return self.confirm_special_order_items.all() … -
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(), …