Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue of database connection lost getting error 2013, 'Lost connection to MySQL server during query'
We are facing the database connection error 2013, ‘Lost connection to MySQL server during query’ in the UAT server(LAMBDA). This error is coming randomly like once or twice a week, for the solution I use to push any kind of code (no matter what it can be a comment also) or I restart the database then the problem instantly resolves. But I’m looking for a permanent solution, please help me to get over of it Thank you # SSH TUNNEL try: tunnel = SSHTunnelForwarder((config('ssh_address'), 22), ssh_pkey = config('tunnel'), ssh_username = config('ssh_username'), remote_bind_address=(config('remote_address'), 3306),local_bind_address=('127.0.0.1',4280)) tunnel.start() print("SSH Started....") except Exception as e: print("==============================================================\nSSH error: \n",e,"\n==============================================================") host = '127.0.0.1' dbSchema = config("schema") user = config('user') passwd = config('password') port = 4280 # port = tunnel.local_bind_port DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': dbSchema, 'USER': user, 'PASSWORD': passwd, 'HOST': host, 'PORT': port, 'OPTIONS': { 'init_command': 'SET max_execution_time=10000000' # In milliseconds } }, 'oldDB': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'eff_eb', 'USER': user, 'PASSWORD': passwd, 'HOST': host, 'PORT': port, 'OPTIONS': { 'init_command': 'SET max_execution_time=10000000' # In milliseconds } } } -
LIKE operation in CHARACTER_VARYING[] field with django postgresql
I have an ArrayField in django model. I wants to do substring search on ArrayField(or charactervarying[]). I am not able to figure out how to do this. I am trying to write a custom lookup as: @ArrayField.register_lookup class ArrayLike(Lookup): lookup_name = "like" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) rhs_params[0] = [f'%{rhs_params[0]}%'] params = lhs_params + rhs_params return '%s like %s::%s' % (lhs, rhs, 'character varying[]'), params Querying as objects = Model.objects.filter(ArrayField__like=value) I am expecting this behaviour Ex: obj1 < type=['django', 'postgres', 'python'] Model.objects.filter(ArrayField__like='djan') should result in [<obj1>] Can anyone help me on this. I am not able to figure this out even after a day of googling Thanks. I am trying to use icontains as a last resort -
Python / DJANGO / Venv
I want to run a django application that already exists in virtual enviremont.Someone can share me a youtube video that help ? Beacouse I just find out.how to create a django app and after run, but I have django app to test in my windows. run my app in virtual environment -
How to resolve in django AttributeError: module 'learning_logs.views' has no attribute 'new_entry'
This is my views.py: from django.shortcuts import render, redirect # Create your views here. from .models import Topic from .forms import TopicForm, EntryForm def index(request): """The home page for learning Log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) def new_topic(request): """Add a new topic""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topics') # Display a blank or invalid form. context = {'form: form'} return render(request, 'learning_logs/new_topic.html', context) def new_entry(request, topic_id): """Add a new entry for a particular topic.""" topic = Topic.objects.get(id=topic_id) if request.method != 'POST': # No data submitted; create a blank form. form = EntryForm() else: # POST data submitted; process data. form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('learning_logs:topic', topic_id=topic_id) # Display a blank or invalic form. context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) Here is my urls.py: … -
Django Decorator that refreshes on current page of request if condition is failed
So, I am trying to write a decorator that restricts access to some pages. But instead of redirecting to a new page, which I have done and I am okay with for some instances, in this case I simply want it to show an error on the current page. I am okay with it refreshing the current path but I keep running into errors regarding paths. Here is my current working code with redirect. How do I modify this? def member_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME, message=default_message): def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): member = ProfileMember.objects.get(user=request.user) print(member.first_name) if not test_func(member): print("failed the test") messages.add_message(request, messages.ERROR, message) print(messages) if test_func(member): print("pass the test") return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url) login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() return redirect_to_login( path, resolved_login_url, redirect_field_name) return _wrapped_view return decorator def user_preapproved(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, home_url='/', message=default_message): """ Decorator for views that checks that the user is an approved member, displaying a message if provided. """ actual_decorator = member_passes_test( lambda m: m.preapproved, login_url=home_url, redirect_field_name=redirect_field_name, message=message ) if view_func: return actual_decorator(view_func) return actual_decorator My attempt at simplify it works … -
How to manage dependencies in a shared git subtree?
Lets say I have four git repos named A,B,C, & D A,B, & C (customer repos): Each repo contains a Django project for customers 1, 2, & 3 respectively Each customer exists in an air gapped environment From a user perspective, each of the Django projects are, more or less, functionally the same The repos have similar dependencies, although, they may vary in their versions (Django 2.x vs Django 4.x, PostgreSQL 13 vs 14, PostgreSQL vs SQLite, python package versions, etc.) D (common repo): This repo contains the code (Django apps & utilities) that is common across the customer repos This repo has been added as a git subtree to each of the customer repos The problem occurs when their is a dependency clash between the code in the customer repos and the common repo. For instance, if there was a line of code in the common repo that relies on Django 4.x and repo A depends on Django 2.x, then there will be errors. This same type of problem may occur with other dependencies. I've thought of two "solutions": Converge towards a single set of dependencies for all repos. In order to get this to work, however, each customer … -
How to solve the problem django.db.utils.OperationalError: no such column
enter image description here I just wanna add other attribute to model class BookCardsModel(models.Model): class Meta: verbose_name = 'Card Books' verbose_name_plural = 'Card Books' book_cover = models.ImageField() book_name = models.CharField(max_length=100) book_subtitle = models.CharField(max_length=100) book_description = models.TextField(max_length=300) full_description = models.TextField(max_length=700) book_quantity = models.IntegerField(default=0) book_color = models.CharField(max_length=100, blank=True) book_size = models.CharField(max_length=100, blank=True) digital = models.BooleanField(default=False,null=True,blank=False) -
My dropdown menu that I created with django-mptt and bootstrap 5.3 is not showed up on my template , how can I fix it?
My dropdown menu that I created with django-mptt and bootstrap 5.3 is not showed up on my template , how can I fix it??? I tried a lot to fix this but I can't, can anyone help please ? This is my template code : div class="dropdown"> <ul class="dropdown-menu"> {% recursetree categories %} <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> {{ node.name }} </button> <li {% if not node.is_leaf_node %}class="dropdown-submenu"{% endif %}> <a class="dropdown-item {% if not node.is_leaf_node %}dropdown-toggle{% endif %}" href="{% if node.is_leaf_node %}{{ node.get_absolute_url }}{% endif %}" {% if not node.is_leaf_node %}role="button" data-bs-toggle="dropdown" aria-expanded="false"{% endif %}> {{ node.name }} {% if not node.is_leaf_node %}<span class="dropdown-caret"></span>{% endif %} </a> {% if not node.is_leaf_node %} <ul class="dropdown-menu"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> And this is my views.py class HomePage(View): def get(self, request, ): postss = Post.objects.all() categories = Category.objects.all() form = CategoryForm() return render(request, 'home/index.html', {'postss': postss, 'categories': categories, 'form': form}) And this is a js code for this dropdown document.addEventListener('DOMContentLoaded', function() { var dropdownSubmenus = [].slice.call(document.querySelectorAll('.dropdown-submenu')); dropdownSubmenus.forEach(function(submenu) { submenu.addEventListener('mouseenter', function() { this.querySelector('.dropdown-menu').classList.add('show'); }); submenu.addEventListener('mouseleave', function() { this.querySelector('.dropdown-menu').classList.remove('show'); }); }); }); It's just not work idk why It's showing up the dropdown codes … -
Cannot make a connection from django in docker container to other services in docker compose
I am trying to send a post request from my Django server in a docker container to another service in a container initiated by docker-compose which are both in the same network. The API I am trying to connect and the Django API are working fine in the development environment locally(not in Docker). The API service that I am trying to connect from the Django server is working fine in the docker container too when I try to access it separately through url. But when I try to call that API through my Django server I am getting this error. aipbpk_server_container | http://localhost/rapi/predkmaxcsv aipbpk_server_container | Internal Server Error: /v1/api/aipbpk/predKmaxRserver aipbpk_server_container | Traceback (most recent call last): aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/connection.py", line 174, in _new_conn aipbpk_server_container | conn = connection.create_connection( aipbpk-nginx-1 | 172.28.0.1 - - [21/Aug/2023:21:19:28 +0000] "POST /api/v1/api/aipbpk/predKmaxRserver HTTP/1.1" 500 193790 "-" "PostmanRuntime/7.32.3" "-" aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/util/connection.py", line 95, in create_connection aipbpk_server_container | raise err aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/util/connection.py", line 85, in create_connection aipbpk_server_container | sock.connect(sa) aipbpk_server_container | ConnectionRefusedError: [Errno 111] Connection refused aipbpk_server_container | aipbpk_server_container | During handling of the above exception, another exception occurred: aipbpk_server_container | aipbpk_server_container | Traceback (most recent call last): aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", … -
Display Derived Value in Django Form
Suppose I have a model: class MyModel(models): A = models.DecimalField() B = models.DecimalField() And a form in which I want to display A, B and the sum C=A+B: class MyForm(): C = forms.DecimalField() class Meta: model = MyModel fields = ['A', 'B'] How do I do this? I tried to do this using an init method but doesn't quite work. -
OpenCV opens camera at the first load, but if I refresh the page, it doesn't bring camera (can't open camera by index)
I have this Django project for Video-Streaming. So everything works perfectly fine on my system (MacOS). But here's what happens in Ubuntu 20.04: Works fine for the first loading If I refresh the page or go to other pages and come back again, the camera is not being opened by my app. This is the error: [ WARN:0] global /tmp/pip-req-build-ms668fyv/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video0): can't open camera by index This is Views.py import cv2 from django.http import HttpResponse, StreamingHttpResponse from django.shortcuts import render from django.views import View import threading class VideoStream(View): def __init__(self): cv2.destroyallwindows() self.camera = cv2.VideoCapture(0, cv2.CAP_V4L2) def __del__(self): self.camera.release() def get_frame(self): ret, frame = self.camera.read() if ret: _, jpeg = cv2.imencode(".jpg", frame) return jpeg.tobytes() else: # print('frame',frame) return None def generate(self): while True: frame = self.get_frame() if frame is not None: yield ( b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n\r\n" ) def get(self, request, *args, **kwargs): return StreamingHttpResponse( self.generate(), content_type="multipart/x-mixed-replace; boundary=frame" ) class StreamView(View): template_name = "stream.html" def get(self, request, *args, **kwargs): return render(request, self.template_name) This is video-stream.html <!DOCTYPE html> <html> <head> <title>Video</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <h1>Real-Time Video Stream</h1> <p>This is Paragraph</p> <img id="video-frame" src="" alt="Video Stream" /> <script> function updateFrame() { console.log("in update frame"); $('#video-frame').attr('src', '{% url … -
How to modify back button functionality in chrome in a website?
I have created a quiz website. So after submitting a quiz, it redirects me to the results page. But if i click back button it goes back to the last question. But I want it to take me back to the home page where all the list of available quizzes is seen. I am not getting any idea how to do it, so I could use some help. My project is a django project so I wanna know how can it be done using djnago? Anyways I am open to all answers -
KeyError in constance package used in Django
I am getting the following error when I try to run my debugger configuration on a Django project through a Docker container using Docker Compose. I can't find AUTO_END_TIMEDELTA_MINS anywhere on the web. Any idea what that might be? Traceback (most recent call last): 2023-08-21T18:03:17.443221106Z File "/usr/local/lib/python3.8/site-packages/constance/base.py", line 14, in __getattr__ 2023-08-21T18:03:17.443224978Z if not len(settings.CONFIG[key]) in (2, 3): 2023-08-21T18:03:17.443227740Z KeyError: 'AUTO_END_TIMEDELTA_MINS' -
Need to know if it is possible to develop log users in django?
I am developping a web application with django and want that admin should see all operations done by differents users in a log. Is it possible to do that please? i am trying to know the possibility if someone did that with django -
"ValueError: not enough image data" from Pillow when saving to a Django ImageField
I have a Django model like: class Website(models.Model): favicon = models.ImageField( null=False, blank=True, default="", width_field="favicon_width", height_field="favicon_height", ) favicon_width = models.PositiveSmallIntegerField(null=True, blank=True) favicon_height = models.PositiveSmallIntegerField(null=True, blank=True) I'm fetching a .ico file and saving it to the favicon field as a .png like this: import io import requests from django.core import files from .models import Website website = Website.objects.get(pk=1) response = requests.get("https://www.blogger.com/favicon.ico", stream=True) image_data = io.BytesIO(response.content) website.favicon.save("favicon.png", files.File(image_data)) Behind the scenes, Pillow successfully converts the ICO file to a PNG, and saves the file. But I then get an error. The traceback includes: # More here File /usr/local/lib/python3.10/site-packages/django/db/models/fields/files.py:491, in ImageField.update_dimension_fields(self, instance, force, *args, **kwargs) 489 # file should be an instance of ImageFieldFile or should be None. 490 if file: --> 491 width = file.width 492 height = file.height 493 else: 494 # No file, so clear dimensions fields. # Lots more here File /usr/local/lib/python3.10/site-packages/PIL/Image.py:804, in Image.frombytes(self, data, decoder_name, *args) 802 if s[0] >= 0: 803 msg = "not enough image data" --> 804 raise ValueError(msg) 805 if s[1] != 0: 806 msg = "cannot decode image data" ValueError: not enough image data So it can save the image but, I'm guessing, not get the width/height from the image to save. BUT, … -
Django "unable to open database file" after cleaning some stuff from my laptop
recently I've been cleaning up my laptop and I believe I have deletedsmth related to my database file in django, whenever I try to login/signup there is an error: OperationalError at /admin/login/ unable to open database file Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 4.2.2 Exception Type: OperationalError Exception Value: unable to open database file Exception Location: C:\Users\Mechta\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in execute Raised during: django.contrib.admin.sites.login Python Executable: C:\Users\Mechta\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.4 Python Path: ['C:\Users\Mechta\Documents\rasengan', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\Lib\site-packages'] I can provide info if u need more details I've read some other posts in here and watched some yt videos but nothing rly helped so I'm stuck -
Download file using DRF
I had written code to download file file_path = file_url FilePointer = open(file_path,"r") response = HttpResponse(FilePointer,content_type='application/msword') response['Content-Disposition'] = 'attachment; filename=NameOfFile' return response. How can I test this code using postman if actually a file gets download when i use this api While React JS code on the frontend is suitable for verifying file downloads, I'm interested in confirming the same using Postman. -
how to save data as null in database in Django forms
here is my problem "Do something in the input form so that the subject value does not need to be filled when sending and it is saved in the database without any input." it is an important task for me I'll be so grateful if you help me models.py from django.db import models # Create your models here. class Contact(models.Model): name = models.CharField(max_length=255) email = models.EmailField() subject = models.CharField(max_length=255) message = models.TextField() created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['created_date'] def __srt__(self): return self.name forms.py from django import forms from website.models import Contact class ContactForm(forms.ModelForm): subject = forms.CharField(required=False) class Meta: model = Contact fields = "__all__" views.py from django.shortcuts import render from django.http import HttpResponse from website.forms import ContactForm from django.contrib import messages def index_view(request): return render(request, "website/index.html") def about_view(request): return render(request, "website/about.html") def contact_view(request): if request.method == "POST": form = ContactForm(request.POST) request.POST._mutable = True request.POST['name'] = 'Anonymous' if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, "your ticket submited") else: messages.add_message(request, messages.ERROR, "your ticket did not submited") form = ContactForm() return render(request, "website/contact.html", {"form:form}) i try somethings in model but it didn't work -
Why am I getting a Bad Gateway Error sending bulk emails with Django
I have a need to send bulk emails, as much as 60 at a time, using an action in the Admin module. I do this by selecting certain cases and then running an admin action. Sometimes when I do this, not all 60 emails send. Sometimes they seem to go in batches of 20/30 and there could be a delay of a few hours between batches. This time I got an incomplete batch being sent and a 'Bad Gateway' error, with 8 emails not being sent. Those that what sent were sent twice. I can't see anything wrong with my code that would cause this. Any ideas would be greatly appreciated. I have the following Admin Action in my admin.py file: emailset=queryset.all().order_by('customer') for q in emailset: customer=q.customer email_to = q.customer.email html_content = render_to_string("accounts/email_template_staff_registration.html", {'q':q}) text_content = strip_tags(html_content) email = EmailMultiAlternatives( #subject "Staff Registration Email", #content text_content, #from settings.EMAIL_HOST_USER, # rec list [email_to], ['INSERT EMAIL ADDRESS FOR CC'] ) email.attach_alternative(html_content, "text/html") email.send() updated=len(queryset) self.message_user(request, ngettext( '%d Staff Registration Email was successfully sent.', '%d Staff Registration Emails were successfully sent.', updated, ) % updated, messages.SUCCESS) send_staff_reg_email.short_description="Send staff registration email" ``` -
Django docker container with nginx and extern database from azure
I have a django docker container. And I try to deploy it. I am using a database service from Azure. with url: db.postgres.database.azure.com" And I am using reverse proxy NGINX for the server. So I have folder named proxy within a docerfile: FROM nginxinc/nginx-unprivileged:1-alpine COPY ./default.conf.tpl /etc/nginx/default.conf.tpl COPY ./uwsgi_params /etc/nginx/uwsgi_params COPY ./run.sh /run.sh ENV LISTEN_PORT=8000 ENV APP_PORT=9000 USER root RUN mkdir -p /vol/static && \ chmod 755 /vol/static && \ touch /etc/nginx/conf.d/default.conf && \ chown nginx:nginx /etc/nginx/conf.d/default.conf && \ chmod +x /run.sh VOLUME /vol/static USER nginx CMD ["/run.sh"] and default.conf.tpl: server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass 8000:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } And in the root folder of the app I have a file: docker-compose-deploy.yml: version: "3.9" services: app: build: context: . dockerfile: Dockerfile.prod restart: always volumes: - static-data:/vol/web environment: - DJANGO_ALLOWED_HOSTS={DJANGO_ALLOWED_HOSTS} env_file: - ./.env.prod proxy: build: context: ./proxy restart: always depends_on: - app ports: - 8000:8000 volumes: - static-data:/vol/static volumes: static-data: and .env.prod file: DEBUG=0 SECRET_KEY="+)d)&d0^&0xda+s%1o(&r3+24)x#i^bk8p8r)@jl_q2=%usxw=" DB_NAME="name" DB_USER="user" DB_PASSWORD="pass" DB_HOST="db.postgres.database.azure.com" DJANGO_ALLOWED_HOSTS="127.0.0.1" and part of settings.py file: import os import dotenv dotenv.read_dotenv() from pathlib import Path from os import environ import dotenv # Build paths inside the project like this: BASE_DIR … -
Adding google fonts in django-quill-editor
I'm working with django-quill-editor and I want to add a custom google font. However I could not add it. I just want to know that is it possible to add custom google fonts in django-quill-editor. I tried like this but it didn't work. QUILL_CONFIGS = { 'default':{ 'theme': 'snow', 'modules': { 'syntax': True, 'toolbar': [ [ {'font': ['Montserrat']}, {'header': []}, {'align': []}, 'bold', 'italic', 'underline', 'strike', 'blockquote', {'color': []}, {'background': []}, ], ['code-block', 'link'], ['clean'], ] } } } -
Finding Duplications with Pandas Pivot Table Works The First Time, Fails Second Time Forward
We have an xlsx file that we process into a dataframe to gather duplications values and count of duplications def duplicationCount(table_file_path, targetColumns): dfTable = pd.read_excel(io=table_file_path, sheet_name='Sheet1', skiprows=0) dfTable.columns = dfTable.columns.str.strip("'") res = dfTable.pivot_table(index=targetColumns, aggfunc='size') res.reset_index() res.rename(columns={'Unnamed: 0': 'no of dups'}, inplace=True) res.index.name = 'index' res = res[res['no of dups'] >= 2] targetColumns.extend(['no of dups']) res = res.filter(targetColumns).values.tolist() return res This works well the first time with output containing for example: account year no of dups 10301 2022 2 42334 2022 2 but running the same code with the same file the second time we get: Traceback (most recent call last): File "E:\Programs\XX\backend\app\views.py", line 265, in app_process_text_file results['DuplicationReportResults'] = duplicationCount(tables_file_paths[0], dupsFindingTargets) File "E:\Programs\XX\backend\app\functions.py", line 92, in duplicationCount res = dfTable.pivot_table(index=targetColumns, aggfunc='size') File "E:\Programs\XX\venv\lib\site-packages\pandas\core\frame.py", line 8044, in pivot_table return pivot_table( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\reshape\pivot.py", line 95, in pivot_table table = __internal_pivot_table( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\reshape\pivot.py", line 164, in __internal_pivot_table grouped = data.groupby(keys, observed=observed, sort=sort) File "E:\Programs\XX\venv\lib\site-packages\pandas\core\frame.py", line 7718, in groupby return DataFrameGroupBy( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\groupby\groupby.py", line 882, in __init__ grouper, exclusions, obj = get_grouper( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\groupby\grouper.py", line 882, in get_grouper raise KeyError(gpr) KeyError: 'no of dups' -
What's the best way to implement JWT authentication with multiple clients?
We currently use Djoser (with simplejwt), which has served us well. The only OAuth clients we had so far have been frontend apps. However, we now have to add access to some external services. There is no appetite to have separate gatekeeper proxy. This will need longer token life, etc and the simple_jwt is no longer the best solution. DRF website has a long list of third party libraries, which is great to have the choice, but makes the choice harder. Which of these packages, or another one that's not listed there, is a fairly easy replacement for Djoser? Ideally, it would be something which doesn't require us to write new views, etc for everything. -
My ckeditor-uploaded image doesn't show up in the post unless I restart the django app from cpanel
`My ckeditor uploaded image doesn't show up unless I restart the django app from cpanel my ckeditor-imported post page works fine in local server, BUT in the production server after i upload an image to server **FIRST **image doesnt in appear post layout (it used to in local server) in local server image would show up here in editor i used to have the image here in the editor it doesn't appear in my post neither... ....unless i restart it from cpanel after i restarted the app from cpanel, it started to work fine i have the following settings.py code: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'x' DEBUG = False ALLOWED_HOSTS = ['cozumdefteri.com'] INSTALLED_APPS = [ 'gonderiyaz.apps.GonderiyazConfig', 'ckeditor', 'ckeditor_uploader', 'mebsci.apps.MebsciConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') CKEDITOR_UPLOAD_PATH = 'static/uploads/' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'cozumdefteri.urls' STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'cozumdefteri.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = … -
Ubuntu to windows django project
So I have developed several projects in Ubuntu. So I get the projects set up in Windows and run them; they are running properly, but I am facing a problem with the static files, that is, the CSS, showing up when I run the web applications. I have inspected the webapps, and it shows that the CSS and static files are being fetched and served (200 code). So what is the issue, and how can I solve it?