Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get id of current object
how to get current id instead of static id (7) to add image to flat ''' class CreateFlat(CreateAPIView): serializer_class = CreateFlat queryset = Flat.objects.all() permission_classes = [AllowAny] def post(self, request, *args, **kwargs): print(request.data) my_img = request.data['id_image'] ima = Images.objects.get(id=my_img) print(self.id) print(self) flat = Flat.objects.get(id=7) flat.images.add(ima); serializer = FlatSerializer(flat, many=True) return Response("done") ''' -
Open external website from a Django website and login user to that external website
I have a button on my Django website with the label 'Open Website' which opens up a website login page in the next tab. I have the username and password for the website and I want to log in the user to the next website programmatically (like I have to enter password and username and click on the login button). What I have tried is: I used selenium but it's opening the browser on my side and entering username and password and clicking on the login button but it's not opening the browser on the client side. -
Inherit multiple Django choices classes in one choices class
Let's say we have two choices classes in Django like: from django.db import models class C1(models.TextChoices): attr1 = "ATTR1", "Attr 1" attr2 = "ATTR2", "Attr 2" class C2(models.TextChoices): attr3 = "ATTR3", "Attr 3" attr4 = "ATTR4", "Attr 4" And we need to inherit these two classes in one choices class like this: class C(C1, C2): pass It throws an error like this: TypeError: C: cannot extend enumeration 'C1' -
Use two different views in the same url path in django
I got two views. First one list some reports per user in a sidebar Second one shows the report in Power BI using embedded code The thing how can I use both views in one template. THe problem is if I put the path of the first view I can't see the report slected (second view), and vice versa. Here I'll show images I'll add some code below views.py #List reeports per user in the sidebar def insertar(request): usuario = Usuario.objects.get(username=request.session['username']) reportes = Reporte.objects.filter(id_usuario=usuario.id_usuario) return render(request, 'base.html', {'reportes': reportes}) #Shows the report selected using Powe BI def reportes(request, titulo): usuario = Usuario.objects.get(username=request.session['username']) reporte = Reporte.objects.get(titulo=titulo, id_usuario=usuario.id_usuario) return render(request, 'reporte.html', {'reporte': reporte}) urls.py urlpatterns = [ path('home', views.insertar, name='index'), re_path(r'^home/.*$', views.insertar, name='index'), path('home/<titulo>', views.reportes, name='reporte'), ] base.html <body> <div class="sidenav"> {% include "sidebar.html" %} </div> <div class="main"> {% block content %} {% endblock %} </div> </body> reporte.html {% extends "base.html" %} {% block title %} Listado de Reportes {% endblock %} {% block content %} <iframe title="{{reporte.titulo}}" width="1024" height="612" src="{{reporte.link}}" frameborder="0" allowFullScreen="true"> </iframe> {% endblock %} sidebar.html {% for i in reportes %} <a href="/home/{{i.titulo}}" class="d-block text-light p-3">{{ i.titulo }}</a> {% endfor %} -
Django case insensitive search in multilevel jsonb field using ORM methods
here is my sample jsonb field: { "name": "XXXXX", "duedate": "Wed Aug 31 2022 17:23:13 GMT+0530", "structure": { "sections": [ { "id": "0", "temp_id": 9, "expanded": true, "requests": [ { "title": "entity onboarding form", # I need to lookup at this level (or key) "agents": [ { "email": "ak@xxx.com", "user_name": "Akhild", "review_status": 0 } ], "req_id": "XXXXXXXX", "status": "Requested" }, { "title": "onboarding", # I need to lookup at this level (or key) "agents": [ { "email": "adak@xxx.com", "user_name": "gaajj", "review_status": 0 } ], "req_id": "XXXXXXXX", "status": "Requested" } ], "labelText": "Pan Card" } ] }, "Agentnames": "", "clientowners": "Admin", "collectionname": "Bank_duplicate" } In this json i need to do case insensitive match for structure->section->request(array)-> title inside each object of request array I have tried this query filter (Q(requests__structure__sections__contains=[{'requests':[{"title": query}]}])) but it becomes case sensitive. Also i have tried self.get_queryset().annotate(search=SearchVector(Cast('requests__structure__sections', TextField())) which does gives case insensitive result but also lookup among the keys other than title. also i tried raw sql where i cannot go beyond the request array. Im expecting any other method or any other approach in django orm that can be used to achieve the require result. -
Multiple htmx hx-target
I have 3 select fields CATEGORY—-->SUBCATEGORY_1 > | > —>SUBCATEGORY_2 Is it possible to update both subcategories when I change CATEGORY value? . I know how to make simple category to subcategory relation , but can’t figure out how to expand it for 2 and more subcategories What I should use to achieve this functionality? -
Django Chat App - Can't automatically scroll down live chat box when new messages are added
So I'm making a chat app with Django Channels, Javascript, and HTML/CSS. I am really not that familiar at all with front-end but so far everything seems to be working fine with my chat app except for the chat box itself not moving downwards when new messages are added. I set my CSS .chatbox class to have an overflow: scroll, but adding that won't make the box auto-scroll when new messages are inserted. I assume based on research I need to alter my javascript script but I honestly don't know where to start. Again, please go slow with me lol I'm not really familiar with frontend. Current Javascript: <script> const chatLog = document.querySelector('#chat-log'); const chatSocket = new WebSocket("ws://" + window.location.host + "/"); if (!chatLog.hasChildNodes()) { const emptyText = document.createElement('h3') emptyText.id = 'emptyText' emptyText.innerText = 'No Messages' emptyText.className = 'empty Text' chatLog.appendChild(emptyText) }; chatSocket.onopen = function (e) { console.log("The connection was setup successfully !"); }; chatSocket.onclose = function (e) { console.log("Something unexpected happened !"); }; document.querySelector("#id_message_send_input").focus(); document.querySelector("#id_message_send_input").onkeyup = function (e) { if (e.keyCode == 13) { document.querySelector("#id_message_send_button").click(); } }; document.querySelector("#id_message_send_button").onclick = function (e) { var messageInput = document.querySelector("#id_message_send_input"); message = messageInput.value; chatSocket.send(JSON.stringify({ message: message, username : "{{request.user.username}}"})); messageInput.value = ""; }; … -
django admin automatic rtl for some languages
I'm trying to add multi language support for a django project using Django i18n official documentaion: https://docs.djangoproject.com/en/4.1/topics/i18n/translation/ When I change the LANGUAGE_CODE to something like 'fa', by default the admin panel changes to RTL. But the problem is when I use other RTL languages like 'ku' (kurdish) the page remains in ltr. I know we can change the css manualy, but wonder what is the problem here and how some languages like Arabic or persian does the RTL part automaticaly but others dont. Thanks in advance # settings.py LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True TIME_ZONE = 'UTC' USE_TZ = True LANGUAGES = ( ('en', _('English')), ('ku', _('Kurdish')), ('fa', _('Persian')), ) LOCALE_PATHS = [ Path(BASE_DIR, 'django_i18n', 'locale'), ] # url.py urlpatterns = i18n_patterns( path('admin/', admin.site.urls), ) +static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) -
Update view in Django WITHOUT using generic classes
I think I don't understand something fundamental here, but every single tutorial on the topic proposes a solution using either a function or a generic class, and both of them work for me, but I can't figure out how to deal with the issue using just View. So to illustrate where I am at, I am building a very simple blog and want to update data on a single post based on it's id. So what I have is: models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.CharField(max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' urls.py urlpatterns = [ path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update') ] update_post.html <form method="post"> {% csrf_token %} {{ isolated_post.as_p }} <input type="submit" value="Update"> </form> and finally views.py class PostUpdateView(View): form_class = PostForm initial = {'key': 'value'} template_name = "blog/update_post.html" def get(self, request, pk): isolated_post = Post.objects.get(pk=pk) form = self.form_class(instance=isolated_post) return render(request, self.template_name, {'form': form}) def post(self, request, pk, form): updated_post = self.form_class(request.POST, instance=form) if updated_post.is_valid(): updated_post.save() return HttpResponseRedirect("/post/" + f'{pk}/') return render(request, self.template_name, {'updated_post': updated_post}) I've tried a lot of things, this time it says that form has not been passed … -
Reverse for 'download' with arguments '({'qualities': [(0, '360p'), "Also have issue with stream" not found. 1 pattern(s) tried: ['download/\\Z'])';
It happens when I try to pass the dictionary from view to html in django View.py from django.shortcuts import render,redirect from pytube import YouTube import os def Yt(request): if request.method == 'POST': # url of the youtube video video_url = request.POST.get('url') # get the video yt = YouTube(video_url) # get all available streams streams = yt.streams.filter(progressive=True, file_extension='mp4') # Get the qualities qualities = [(i,stream.resolution) for i, stream in enumerate(streams)] context = { 'qualities' : qualities, 'streams' : streams, } return redirect('download', context) return render(request, 'yt.html') def Yt_det(request): if request.method == 'POST': streams = request.session.get('streams') # get the quality of video selected_quality = int(request.POST.get('selected_quality')) # download the video stream = streams[selected_quality] # name of the video custom_name = request.POST.get('custom_name') # download the video stream.download(filename=custom_name) return render(request, 'yt-det.html', {'message': 'Video downloaded successfully'}) Yt.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> /* Import Google Font - Poppins */ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap'); * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body { display: flex; padding: 0 10px; min-height: 100vh; align-items: center; background: #3498DB; justify-content: center; } ::selection { color: #fff; background: #3498DB; } .wrapper { height: 265px; max-width: 410px; background: #fff; border-radius: … -
javascript download docx file from ajax response
I have a django function with return: ... return FileResponse(open('demo.docx', 'rb')) I use ajax to get it on client side. Now I need to download it on client side. I use this code: ... success:function(response){ var blob = new Blob([response]); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = "file.docx"; link.click(); }, ... Edited: function func(){ var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $.ajax({ type: 'POST', url: '/myapp/func/', headers:{ "X-CSRFToken": csrftoken }, data: {name:"",'image1': Data1}, success:function(response){ var blob = new Blob([response]); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.setAttribute('target', '_blank'); link.download = "file.docx"; link.click(); }, error : function(xhr,errmsg,err) { alert("ajax error: func"); } }); } However it downloads a corrupt something, probably not a docx file. How can I get on client side what I read as a docx? -
Django Views not getting POST Data from api call
I am not using django rest frame work but in normal views.py I have a simple views #views.py def api_post_operations(request): pdb.set_trace() if request.POST: print(request.POST["name"]) print(request.POST["address"]) now I call it import requests url = "http://localhost:8000/api_post_operations" payload = {"name":"raj", "address": "asasass" } rees = requests.post(url, data=payload, headers={}) it is comming (Pdb) request.POST <QueryDict: {}> Any reason why it is comming {} balnk request.body also comming blank -
Custom rendered input for django-formtools wizard field
New to Django. I've created some bootstrap card UI widgets that function as radio buttons and this works ok in plain old html, but I'm trying to integrate it into a Django wizard. How would I go about telling the form the data field is associated with? I just have a bunch of widgets included for each option like this <div class="col-6"> {% include "./domain_type_widget.html" with radio_group="domain_type" title="People" description="For a URL with your name" left="name" mid="people" type_id="name" checked=True %} </div> <div class="col-6"> {% include "./domain_type_widget.html" with radio_group="domain_type" title="Event" description="For events" left="eventname" mid="event" type_id="event" %} </div> And domain_type_widget.html looks like so <label class="card m-1 {% if checked %}selected_type{% endif %}" id="{{ type_id }}_card"> <div class="card-body" onclick="selectDomainType({{type_id}})"> <div class="row"> <div class="col-sm-12 col-md-10"> <h5 class="card-title">{{ title }}</h5> <p class="card-text">{{ description }}</p> {% if left %} <p class="domain-example" class="domain-example"> <span class="left">{{ left }}</span> <span>.</span> <span class="mid">{{ mid }}</span> <span>.</span> <span class="right">site.com</span> </p> {% endif %} </div> <div class="col-sm-12 col-md-2 d-flex align-items-center justify-content-center"> <input type="radio" class="radio" name="{{ radio_group }}" id="{{ type_id }}" {% if checked %}checked{% endif %} onchange="selectDomainType(this)"> </div> </div> </div> -
How do you use the Django timezone.override(utc) to create datetimes with tzinfo?
I can use timezone.now() to get a UTC timestamp in Django. I can use timezone.make_aware(datetime(2012,1,1)) to add UTC as the TZ for the datetime. Last one is cumbersome and a lot of extra typing. Meanwhile I find these docs: https://docs.djangoproject.com/en/4.1/topics/i18n/timezones/ But activating the TZ doesn't seem to affect datetime creation (still no tzinfo included) I also found these docs inside python: >>> from django.utils import timezone >>> help(timezone) Help on module django.utils.timezone in django.utils: NAME django.utils.timezone - Timezone-related classes and functions. CLASSES contextlib.ContextDecorator(builtins.object) override class override(contextlib.ContextDecorator) | override(timezone) | | Temporarily set the time zone for the current thread. | | This is a context manager that uses django.utils.timezone.activate() | to set the timezone on entry and restores the previously active timezone | on exit. | | The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a | time zone name, or ``None``. If it is ``None``, Django enables the default | time zone. | | Method resolution order: | override | contextlib.ContextDecorator | builtins.object | | Methods defined here: | | __enter__(self) | | __exit__(self, exc_type, exc_value, traceback) | | __init__(self, timezone) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from … -
Show another static content as part of Django page
Collaborator is giving me static content that I'd like to display as a component of a page in a Django app. I'd like to do this without styling interruptions. Specifically: I have a Django template templates/page.html that extends templates/base.html. The base.html includes header/footer/navbar/etc. In the middle of page.html, I'd like to insert external HTML (with its own CSS) exactly as being imported, so that external CSS styling in templates/base.html doesn't get applied. (But I also don't want the CSS I am importing to affect stuff in base.html either.) Is there a Django-native, or HTML/CSS-native way to accomplish this? -
The json formatted response from django API with serializers
i have been trying to get the response as given below but am a little stuck as to how to achieve it.. I tried other ways without serializers but then my pagination does not work as expected.. the question for the pagination issue is Pagination does not seem to be working using get method and APIView below is my dataset: data = [['1','2023-01-04 12:39','{"kpiThreshold": 23, "kpiValue": 25, "kpiDiff": 2}'], ['2','2023-01-03 12:39','{"kpiThreshold": 23, "kpiValue": 26, "kpiDiff": 3}'], ['1','2023-01-02 12:39','{"kpiThreshold": 23, "kpiValue": 27, "kpiDiff": 4}']] df_new = pd.DataFrame(data, columns=['id', 'date','kpi']) df_new serializer.py from rest_framework import serializers from pegaapi.models import PegaAlerts class AlertsSerializer(serializers.ModelSerializer): class Meta: model = PegaAlerts fields = ('id','generateddatetime','kpiValues') views.py class FullLogsAPI(GenericAPIView): pagination_class=CustomPagination serializer_class = AlertsSerializer def get(self,request, *args, **kwargs): envid = self.kwargs.get('envid') nodeid = self.kwargs.get('nodeid') startdatetime = self.request.GET.get('startdatetime') enddatetime = self.request.GET.get('enddatetime') filter_list=PegaAlerts.objects.filter(envId=envid, serverId=nodeid, generateddatetime__lte=enddatetime, generateddatetime__gte=startdatetime,).order_by('generateddatetime') page = self.paginate_queryset(filter_list) serializer = AlertsSerializer(page, many=True) return Response(serializer.data, status=status.HTTP_200_OK) Response : [ { "id": 1, "generateddatetime": "2023-01-04 12:39", "kpiValues": "{\"kpiThreshold\": 23, \"kpiValue\": 25, \"kpiDiff\": 2}" }, { "id": 2, "generateddatetime": "2023-01-03 12:39", "kpiValues": "{\"kpiThreshold\": 23, \"kpiValue\": 26, \"kpiDiff\": 3}" }, { "id": 3, "generateddatetime": "2023-01-02 12:39", "kpiValues": "{\"kpiThreshold\": 23, \"kpiValue\": 27, \"kpiDiff\": 4}" } ] But the response i'm looking for is [ { … -
Facing problems when I try to deploy drf + angular to digitalocean droplet
I am trying to deploy my django + angular application to a digitalocean droplet. Here is all the relevant information: File structure: home/ USER_NAME/ projectdir/ env/ test_project/ several_django_apps/... dist/ frontend/ assets/ images/... index.html favicon.ico some_relevant_js_files.js test_project/ __init__.py asgi.py urls.py settings.py wsgi.py In the above structure, the dist folder has a frontend folder which contains the angular build data. When I try to access my domain, I get a 500 Internal Server error. Now, here is my nginx configuration: server { listen 80; server_name IP_ADDRESS www.DOMAIN_NAME DOMAIN_NAME; location = /favicon.ico { access_log off; log_not_found off; } location /api/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location / { root /home/USER_NAME/projectdir/test_project/dist/frontend; try_files /index.html $uri $uri/; } } When I run sudo tail -f /var/log/nginx/error.log, I get the following errors: [crit] 2446#2446: *9 stat() "/home/USER_NAME/projectdir/test_project/dist/frontend/index.html" failed (13: Permission denied) [crit] 2446#2446: *9 stat() "/home/USER_NAME/projectdir/test_project/dist/frontend///////////" failed (13: Permission denied) [error] 2446#2446: 2446#2446: *9 rewrite or internal redirection cycle while internally redirecting to "////////////" I am extremely new to all of this stuff so I apologize for any silly errors on my end. If you require any other information please let me know. Thanks! I also tried increasing the memory of my droplet if that were … -
How to install mysqlclient python package?
I now learn django. On database learn mysql. But dont install mysqlclient. Initially get Microsoft C++ 14.0 or greater than required error. I solve this. I install build tools. But now get another error: running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-cpython-38 creating build\temp.win32-cpython-38\Release creating build\temp.win32-cpython-38\Release\MySQLdb "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\bin\HostX86\x86\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -Dversion_info=(2,1,1,'final',0) -D__version__=2.1.1 "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include\mariadb" "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include" -IC:\Users\Feruz\.virtualenvs\storefront-GD3EPR4W\include -Ic:\users\feruz\appdata\local\programs\python\python38-32\include -Ic:\users\feruz\appdata\local\programs\python\python38-32\Include "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\ATLMFC\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\cppwinrt" /TcMySQLdb/_mysql.c /Fobuild\temp.win32-cpython-38\Release\MySQLdb/_mysql.obj _mysql.c MySQLdb/_mysql.c(29): fatal error C1083: ЌҐ г¤ Ґвбп ®вЄалвм д ©« ўЄ«о票Ґ: mysql.h: No such file or directory, error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x86\\cl.exe' failed with exit code 2 note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> mysqlclient note: This is an issue with the package mentioned above, not pip. hint: See above for output from the failure. [0m Installation Failed How to solve this? Please help me. I use windows -
Iterate over page data stored in a settings Orderable
I have created a Wagtail settings page that allows me to select 1-5 pages which I'd like to display in my site footer as 'Most popular pages'. I've done this using an Orderable and PageChooserPanel, see below: @register_setting class MostPopularPosts(BaseSetting, ClusterableModel): display_most_popular_posts_in_sidebar = models.BooleanField("Display most popular posts in sidebar", default=True, help_text='Untick to hide the most popular posts widget') panels = [ FieldPanel('display_most_popular_posts_in_sidebar'), InlinePanel('popular_pages', max_num=5, min_num=1, label="Most popular pages"), ] class MostPopularPostPages(Orderable): settings_page = ParentalKey(MostPopularPosts, related_name="popular_pages") popular_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', verbose_name="Page Link" ) panels = [ PageChooserPanel('popular_page') ] The above works fine, but I'm struggling to get the content of the individual pages selected to appear in my templates. {% for popular_page in settings.home.MostPopularPosts.popular_pages.all %} <li> {{ popular_page.title }} </li> {% endfor %} The above loop iterates the expected number of times, but {{ popular_page.title }} doesn't output the page titles. I've tried {{ popular_page.specific.title }} but this also doesn't work. If someone could explain how I should be structuring my template tags to access the individual pages data within my for loop here I'd be eternally grateful. -
Why i can choose only decimal multiple 0,5 in admin panel?
I created a model in Django with multiple choice of numbers from 0 to 14 with steps 0,1. I can see them all in the admin panel, but can choose only numbers multiple 0,5. My model: class SoilPh(models.Model): SOIL_PH_CHOICES = ( (i / 10, str(i / 10)) for i in range(MAX_PH_LEVEL * 10 + 1) ) name = models.DecimalField( max_digits=2, decimal_places=1, validators=[ MinValueValidator(0, '0'), MaxValueValidator(MAX_PH_LEVEL, f'{MAX_PH_LEVEL}') ], choices=SOIL_PH_CHOICES, unique=True, null=True, ) class Deciduous(Plant): soil_ph = models.ManyToManyField( SoilPh, related_name='soil_ph', ) Error: Select a valid choice. 0.3 is not one of the available choices. Where is my mistake? -
how to override _default manager used by ModelSerializer
Given below snippet, class CustomManager(models.Manager): def create(**kwargs): super().create(external_id='xyz', **kwargs) class Person(models.Model): internal_id = models.AutoField(db_column='id', primary_key=True) f_name=models.CharField(db_column='f_name', max_length=15, blank=True, null=True) external_id = models.CharField(db_column='ext_id', null=True, blank=True, max_length=20) objects = models.Manager() custom = CustomManager() class PersonSerializer(serializer.ModelSerializer): class Meta: model=Person fields='__all__' Here, when .save() method gets called on the serializer, the default manager used by the the create function in serializer is objects. I would like this to be changed to custom so that when save call happens, create function inside CustomManager gets invoked. I can achieve this by overriding the super class method create in the serializer. But is there any better workaround for this without overriding base class method? -
Can I use only one redis connection for my django app?
Introduction: django 3.2.16 django-redis 4.12.1 Problem: I use redis as a cache storage. I put the data to redis manually using the next code: from django_redis import get_redis_connection def redis_handler() -> None: redis = get_redis_connection() ... # some business logic ... redis.close() I call redis_handler() often and every time a new connection to redis created. Idea/Solution: Can I create a "global" redis connection once for a project and then import and use it everywhere? Where I can do it? What problems can be? Because I will not close it while the project works. I was inspired FastApi - it has hooks when the project starts and stops. -
django unit test database connection error
I am trying to run the Django rest framework unit test and at the beginning, it works well but after a while, I start getting this error : error I have no idea why I keep getting this error or what change caused this error in my unit test my unit test: image my setting.josn : image my local.py settings: image -
Github Webhook Verification within Django-Ninja
I have the following end-point inside a Django-Ninja application that I am using to verify incoming GitHub Webhooks. I'm not sure what I'm doing wrong but the hmac.compare_digest() keeps returning False even when I know it is GitHub sending the post request from ninja import NinjaAPI import hmac import hashlib import os import requests api = NinjaAPI() class GitHubVerify: my_secret = os.getenv('GITHUB_SECRET_KEY') def verify(self, request) -> bool: return self._verify_signature(request=request) # and self._verify_ip(request=request) def _verify_signature(self, request): incoming_signature = request.headers.get('X-Hub-Signature-256', None) if incoming_signature is None: return False sha_name, incoming_signature = incoming_signature.split('=') if sha_name != "sha256": return False print(sha_name, incoming_signature) calculated_signature = hmac.HMAC( key=self.my_secret.encode('utf-8'), msg=request.body, digestmod=hashlib.sha256 ).hexdigest() print(calculated_signature) print(request.headers) return hmac.compare_digest(calculated_signature, incoming_signature) def _verify_ip(self, request): """ TODO: figure out why the IP being parsed here doesn't seem to match GitHub's API """ webhook_ips = self._get_hook_ips() print(webhook_ips) print(request.headers) return request.headers.get('X-Forwarded-For') in self._get_hook_ips() def _get_hook_ips(self): return requests.get('https://api.github.com/meta').json()['hooks'] @api.post("/webhook") def github_webhook(request): github_verify = GitHubVerify() return github_verify.verify(request=request) I've copy-pasta'd the secret key from my environment to GitHub Webhook. I parse the incoming headers to make sure a 256SHA signature exists. Then I calculate my own signature using hmac, passing in my secret, request.body and SHA256 Am I missing something glaringly obvious? Another thing I noticed is that … -
Using PageChooserPanel as an Orderable in Settings, getting "'list' object has no attribute 'bind_to'" Attribute error
I'm trying to create a settings page within Wagtail that will allow me to manually choose 1-5 pages that will be displayed as 'Most popular pages' on my site. I'm using a PageChooserPanel within an Orderable, but I'm getting an Attribute error that I don't know how to fix - "'list' object has no attribute 'bind_to'" Code used is below: from django.db import models from wagtail.core.models import Page, Orderable from wagtail.admin.edit_handlers import PageChooserPanel, FieldPanel, MultiFieldPanel, InlinePanel from wagtail.contrib.settings.models import BaseSetting, register_setting from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel @register_setting class MostPopularPosts(BaseSetting, ClusterableModel): display_most_popular_posts_in_sidebar = models.BooleanField("Display most popular posts in sidebar", default=True, help_text='Untick to hide the most popular posts widget') panels = [ FieldPanel('display_most_popular_posts_in_sidebar'), InlinePanel('popular_page', max_num=5, min_num=1, label="Post"), ], class MostPopularPostPages(Orderable): settings_page = ParentalKey(MostPopularPosts) popular_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', verbose_name="Page Link" ) panels = [ PageChooserPanel('popular_page'), ] Error message in full: Internal Server Error: /admin/settings/home/mostpopularposts/2/ Traceback (most recent call last): File "C:\Users\willr\repos\mapbox\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\willr\repos\mapbox\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\willr\repos\mapbox\env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\willr\repos\mapbox\env\lib\site-packages\wagtail\admin\urls\__init__.py", line 127, in wrapper return view_func(request, *args, **kwargs) File "C:\Users\willr\repos\mapbox\env\lib\site-packages\wagtail\admin\auth.py", line 172, in decorated_view …