Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Error "This field is required." only when trying to retrieve random objects
I get the form error "This field is required." only when trying to retrieve random objects like this: pks = list(QuizQuestion.objects.values_list('pk', flat=True)) random_pks = random.sample(pks, 2) questions = QuizQuestion.objects.filter(pk__in=random_pks) When I am using: questions = QuizQuestion.objects.all() everything works fine. This is the QuizForm: class QuizForm(forms.Form): """QuizForm used to display questions with their options.""" def __init__(self, *args, **kwargs): questions = kwargs.pop('questions') super(QuizForm, self).__init__(*args, **kwargs) for question in questions: choices = [ ('option1', question.option1), ('option2', question.option2), ('option3', question.option3), ('option4', question.option4), ] self.fields[str(question.id)] = forms.ChoiceField( label=question.question_text, choices=choices, widget=forms.RadioSelect(attrs={'class': 'form-check-input'}) ) And this is the html form: <form method="post"> {% csrf_token %} {% for field in form %} <div> <label class="question">{{ field.label }}</label> {% if field.errors %} <ul class="errors"> {% for error in field.errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} <div> {% for choice in field %} <label class="form-check-inline"> {{ choice }} </label> {% endfor %} </div> </div> {% endfor %} <button type="submit">Submit</button> </form> I also tried other methods for getting the random objects from here: Django get a random object and https://books.agiliq.com/projects/django-orm-cookbook/en/latest/random.html. I think the problem is within the QuizForm but i cannot figure out where. -
Is it worth studying django in 2024
I am a novice web developer and recently finished learning python, now I want to move on and try to make the first real project with a working backend. After reading about different frameworks, I liked Django. But recently, one of my friends told me that django is a big Clumsy machine, and if I really want to do backend, then it's better to study node.js or the same flask. I have not found any information from professionals on the Internet. And I decided to ask here, is django really so slow and outdated, and is it worth starting to study it now if I want to be competitive in the market? Tried to learn Django. Expecting good workplace. -
Django some URLs 301ing to home on Production only (NGINX, GUnicorn)
In production, some of my URLs work, some dont and redirect to home / the main site URL. So, I have a site up and running in Production. I use a NGINX load balancer with 3 x NGINX reverse proxy with GUnicorn VMs running the app. The app includes the following in its URL file: path("interest/", view=SDInterestView.as_view(template_name="sd/interest.jinja2"), name="sd_intresse"), path("interesta/", view=SDInterestViewA.as_view(template_name="sd/interest.jinja2"), name="sd_intressea"), path("interestcopy/", view=SDInterestView.as_view(template_name="sd/interest.jinja2"), name="sd_intresse_copy") These are base level URLs. so www.site.com/intresse/ etc... SDInterestView and SDInterestViewA are copy paste code - other than the class name. So - interest/ works. Neither interesta/ or interestcopy/ work in production. Everything works AOK with RunServer or runserver_plus locally in dev. If I access the back end python session of one of the VMs, I can resolve the URL and see for all three the correct attributes for which view they are going to execture. The three URLs all show in manage.py show_urls. I am at a loss as to how to track down what the issue is. At the moment I can not see to add in any base level URLs and get them to work. If I add urls to the apps individual URL files, these show and work AOK - but - … -
Django static files showing ONLY if debugger is started (with DEBUG=True)
I am using daphne as Django server with the integration from daphne to runserver in settings.py I have a strange error since yesterday with static files with DEBUG=True, (so, no, it's not another case of static files not found when DEBUG=False ! ;) They don't show up when I'm running python manage.py runserver but when I run the app using the debugger from VS Code, then they show up. So my setup is working in some way but only under debugging... In settings.py, I have: STATIC_ROOT = BASE_DIR / 'static' STATIC_URL = 'static/' INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ... ] my launch.json is: { "version": "0.2.0", "configurations": [ { "name": "Python Debugger: Django", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": ["runserver"], "django": true, "autoStartBrowser": false, "justMyCode": false, } ] } so it also runs the same command (runserver). The static files are stored in the static// directory of each app. Any idea? -
Django test views code:error database "test_postgres" already exists
I want to test my website and I created a tests folder inside my app and created files for testing models…, I ran the test URLs and it was successful but I faced a problem with views, models, and forms tests, “database "test_postgres" already exists Type 'yes' if you would like to try deleting the test database 'test_postgres', or 'no' to cancel”, I’m afraid to delete something important so how can fix the problem ( I used Supabase hosted my Postgres database). I tried to ran the views and models but I faced this problem what should I do to solve this problem -
Changes in html without refreshing(ajax problem)
I got problem or i kinda don't understand how ajax works. I want after clicking button to add user in likes column in datatable, and then pass variables in json again to ajax which one change elements in html file. All without refreshing. i'm stuck. Ajax works with adding, deleting user, but don't know how to return json and change elements in html. urls.py urlpatterns = [ path('',views.logout_view, name = 'logout'), path('like/<int:pk>', views.commLike, name="comm_like"), ] views.py @login_required def commLike(request, pk): comm_id = request.POST.get('comm_id') comm = Comment.objects.get(comment_id=comm_id) user_name = request.POST.get('user') user_email = request.POST.get('email') profile = User.objects.get(email=user_email ) if not User.objects.get(email=user_email): User.objects.create(email=user_email,name=user_name) if profile in comm.likes.all(): comm.likes.remove(profile) is_liked = False else: comm.likes.add(profile) is_liked = True response = {} response['is_liked'] = is_liked response['total_likes'] = comm.total_likes() # response_data[is_liked,comm.total_likes()] # return render(request, 'show_post.html', { 'is_liked': is_liked, 'total_likes': comm.total_likes()}) return JsonResponse(response) show.html <form action= "{% url 'comm_like' pk=cs.comment_id %}" id=like-butt class="like-button" method="post" > {% csrf_token %} <input type="hidden" name="user" value="{{user}}"> <input type="hidden" name="email" value="{{user.email}}"> <input type="hidden" name="comm_id" value="{{ cs.comment_id }}"> <button type="submit" id='comm_like' value="{{ cs.comment_id }}" class="comment-rating"> <img src="/static/img/thumb_up.png" style="height:2rem;width:2rem;"> </button> </form> script.js $('#like-butt').on('submit',function(e){ e.preventDefault(); console.log("form submitted!") comm_like(); }); function comm_like() { console.log("create post is working!"); const email = $('input[name="email"]').val(); const user = $('input[name="user"]').val(); const comm_id … -
How to merge different models in Django?
I have huge concern about merge two or more models in Django. First, there are 9 models in models.py. (just structure) model A (fields: user, AA(foreign key), created_at) model AA (fields: user, title, content) model AAA (fields: AA(foreign key), theme_name) model B (fields: user, BB(foreign key), created_at) model BB (fields: user, title, content) model BBB (fields: BB(foreign key), theme_name) model C (fields: user, CC(foreign key), created_at) model CC (fields: user, title, content) model CCC (fields: CC(foreign key), theme_name) And I want to merge model A, model B, model C, ordered by 'created_at' with Pagination and filter(with theme_name). I searched for how to merge, but there seemed to be no way other than using annotate to align and merge all types and quantities of fields. However, when additional models created later, if I use annotate at that time, it is expected that the annotated fields will increase too much and it will take more time. What should I do? -
CSS-Grid design choice
I am new to web development and I have a design choice question. I am developing a game where students can learn how to multiply. Now I run into a problem regarding displaying the multiplication. I am not sure on how to format the individual input cells for a multiplication since. The following picture might make my problem a little bit more clear. Since I don't know how many or if any fields(white boxes) and carrys(red boxes) occur I am not sure how to go from here. I am using Django and I have tried to create a grid(not a css grid) of all possible boxes for that calculation and set the display flag to true if that box is neccesary for my calculation. Doing this it did not feel right. There must be an easier way. Would css-grid be the right choice for this type of problem? So I just pass all my boxes to the view and the css will handle the rest. Thanks in advance -
How can I send data from server to frontend
I try to make a project with django and vue.js In vue.js I write this code <tbody v-if="!hrmsActive"> <tr v-for="(holiday, index) in personLeave" :key="index"> <th scope="row"> <!-- {{ index + 1 }} --> {{ personLeave.current_page * perPage - perPage + index + 1 }} </th> <td> {{ holiday.holidays_start_date .split("-") .reverse() .join("-") }} </td> <td> {{ holiday.holidays_end_date .split("-") .reverse() .join("-") }} </td> <td>{{ holiday.holiday_type_name }}</td> <td v-if="holiday.comments"> {{ holiday.comments }} </td> <td v-else> - </td> <td v-if="holiday.on_holidays" class="fas fa-check" style="color:green" ></td> <td v-else class="fas fa-times" style="color:red"></td> </tr> </tbody> and async fetchPersonHolidays() { const filterUrlParams = new URLSearchParams(); Object.entries(this.personLeave).forEach(([key, values]) => { if (values) { if (Array.isArray(values)) { values.forEach((value) => { filterUrlParams.append(key, value); }); } else { filterUrlParams.append(key, values); } } }); await session .get(`api/person/${this.$route.params.id}/holidays/?${filterUrlParams.toString()}`) .then((resp) => { this.personLeave = resp.data; console.log(resp.data) }).catch((e) => { console.log(e.response.data); }); and I try to send data from server in frontend and data don't appear and the error message in the page is TypeError: holiday.holidays_start_date is undefined. What can I do in order to solve this? -
login and my profile api binding in django template
this is my login api view. i am using adminlte for frontend to develop admin panel class LoginView(APIView): @extend_schema(request={'email', 'password'}) def post(self, request): email = request.data.get('email') password = request.data.get('password') remember_me = request.data.get('remember_me') user = authenticate(email=email, password=password) if user: # Set the token expiration based on remember_me option if remember_me: token_lifetime = timezone.now() + timezone.timedelta(days=30) # Long-lived token else: token_lifetime = timezone.now() + timezone.timedelta(minutes=24) # Short-lived token # Generate or retrieve token for the authenticated user token, _ = Token.objects.get_or_create(user=user) token.created = timezone.now() token.expires = token_lifetime user.token = token.key user.last_login = timezone.now() user.save(update_fields=['token', 'last_login']) token.save() return Response({ 'success': True, 'user_id': user.id, 'email': user.email, 'token': token.key}, status=status.HTTP_200_OK) else: return Response({ 'success': False, 'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) this is my frontend view in django. def login_view(request): if request.method == 'POST': data = { 'email': request.POST['email'], 'password': request.POST['password'] } csrf_token = request.COOKIES.get('csrftoken') headers = {'X-CSRFToken': csrf_token} response_content, status_code = Http.post(request, f"{settings.API_URL_V1}/login", data=data, headers=headers) if status_code == 200: token = response_content.get('token') if token: request.session['token'] = token messages.success(request, 'Logged in successfully') return redirect('dashboard') else: if not data['email'] and not data['password']: messages.error(request, 'Email and Password cannot be Empty!') elif not 'password' or len('password') < 8 or not re.search("[!@#$%^&*()-_=+{};:,<.>]", 'password') or not re.search("[0-9]", 'password'): messages.error(request, 'Password must be … -
Django: Add values from dict Queryset
I have this entry monitoring table that has multiple dates and time values. I wanted to get total number of entry every month, that has multiple entry every day per user. I used this line: stats=EntryMonitoring.objects.filter(student_id=user).annotate(month=TruncMonth('date')).values('month').annotate(total=Count('id')) The results is: <QuerySet [{'month': datetime.date(2024, 3, 1), 'total': 25}, {'month': datetime.date(2024, 4, 1), 'total': 1}]> I view the data by using this {% for obj in stats %}{{ obj.total }}{% endfor %} So I got 251. I want to add the total values like 25 and 1, that would be a total of 26 entry for the month. Or I can make the total entries per day. -
Can't log in in django adminstrator interface with my custom backend
I've replaced default backend system with my custom one #overriding authentication method to use email instead of an username. class EmailBackend(ModelBackend): def authenticate(self, request, email = None, password = None): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None if user.check_password(password): return user return None and edited settings.py according to the docs AUTH_USER_MODEL = "accounts.User" AUTHENTICATION_BACKENDS = ["accounts.backends.EmailBackend"] User model itself class User(AbstractUser): email = models.EmailField(max_length=64, unique=True) courses = models.ManyToManyField(Course, blank=True) The problem is that I can login with the email in my html login form, but can't do the same thing in django admin interface. What I've tried so far: Deleted migrations folder with the database itself and then making migrations and migration Restarting the server Creating new superuser -
how to get endpoints framework mobile api request with protorpc message in django restframe work or django view
my code writen in py2.7 in google app engine and i am using endpoint framework for mobile. now my mobile team has endpoint java create lib from py2.7 and they hit the api with the help of that lib I am using this code in py2.7 to get the request data @endpoints.method(UserDetail, UserDetail, http_method='POST', name = 'user.authenticate') def authenticate_user(self, request): print(request.user_detail) print(request.abc) now in django i try all APIView def post(self,request,*args, **kwargs): but in request i didnot get data i try this code also but did not get data class authenticate_user(View): def post(self, request, *args, **kwargs): data = request.body header = request.META # data = data.decode('utf-8') # post_data = json.loads(data) print('----------------') print('-request.GET-') print(request.GET) print('-request.GET-') print('-request.FILES-') print(request.FILES) print('-request.FILES-') print('-META-') print(header) print('-.META-') # print('-post_data-') # print(post_data) # print('-post_data-') print('-request.POST-') print(request.POST) print('-request.POST-') print('-request.headers-') print(request.headers) print('-request.headers-') print('----------------') return JsonResponse({'success':"hiiii"}) i am geting this. I don't want to change mobile code i want to convert my code in python3 with django could any one help me. Now endpoint does not sport py3 May be this request get IN RCP how to get RCp data in django -
Upgrading Django from 3.2 LTS to Django 5.04 causes typeerror: requires_system_checks must be a list or tuple
I just upgraded Django from 3.2 LTS to the latest Django 5.0.4 and updated all packages as on a need basis and I get the following trace after I attempt to run the docker-compose to start my api web server : my-api | File "/opt/my-api-core/manage.py", line 22, in <module> my-api | execute_from_command_line(sys.argv) my-api | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line my-api | utility.execute() my-api | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute my-api | self.fetch_command(subcommand).run_from_argv(self.argv) my-api | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 275, in fetch_command my-api | klass = load_command_class(app_name, subcommand) my-api | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 49, in load_command_class my-api | return module.Command() my-api | File "/usr/local/lib/python3.10/site-packages/django_media_fixtures/management/commands/collectmedia.py", line 35, in __init__ my-api | super(Command, self).__init__(*args, **kwargs) my-api | File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 285, in __init__ my-api | raise TypeError("requires_system_checks must be a list or tuple.") my-api | TypeError: requires_system_checks must be a list or tuple. The following is what I've attempted so far: The django-media-fixtures is what is seen in the trace so I used https://pypi.org/project/django-media-fixtures-next/ after changing it from https://pypi.org/project/django-media-fixtures/ Downgraded Django up until 4.2.11 and right up until 4.1 from the present 5.0.4 However , the error persists. I do not see the need to modify site-packages itself as it doesn't seem … -
How to redirect to homepage in Django if already logged in and then try to access /accounts/login/?
So I have "django.contrib.auth.urls" to implement login in my app called accounts. I also have set LOGIN_REDIRECT_URL = "home" LOGOUT_REDIRECT_URL = "home" in settings. When I log in it redirects me to the home page as I have set it up in a template below. The problem is when I am logged in and then try to go to /accounts/login/, it still redirects me to login page. I couldn't understand how to make it automatically redirect to homepage if user is authenticated and they try to access either 'accounts/login/' or 'accounts/signup/. I thought this behavior was included in "django.contrib.auth.urls". What do I get wrong? Here's my project.urls setup: from django.contrib import admin from django.views.generic.base import TemplateView from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='home.html'), name='home'), ] Here's my accounts.urls: from django.urls import path from accounts.views import SignUpView, log_out urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('logout/', log_out, name='logout'), ] These are my views: from django.urls import reverse_lazy from django.views.generic import CreateView from django.contrib.auth import logout from django.shortcuts import redirect from accounts.forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') … -
How to detect selected text from a PDF using Python in a Django application?
I have a Python script that successfully detects selected text from a PDF file using the xdotool and pyperclip libraries. Here's the script: import time import os import subprocess import pyperclip def get_selected_text(): subprocess.run(['xdotool', 'key', 'ctrl+c']) time.sleep(1) return pyperclip.paste() if __name__ == "__main__": pdf_filepath = 'class3english.pdf' subprocess.Popen(['xdg-open', pdf_filepath]) while True: selected_text = get_selected_text() if selected_text: print("Selected text:", selected_text) time.sleep(2) However, when I try to integrate this script into my Django application, it doesn't detect the selected text from the PDF. Instead, it captures text from the clipboard. I want to be able to detect text that the user has actively selected within the PDF viewer. Is there a way to achieve this within a Django application? How can I modify my approach to capture only the selected text from a PDF when running within a Django environment? -
Problem with Django form field styling upon error
I'm building my first website with Django and I have encountered what I think is a really weird problem. I have a form in the page, and I want that, if the user inputs invalid data in one of its fields, that field is marked with a specific CSS style. What I have done is write a validation method (a "clean()" method) that checks the input provided by the user. If it doesn't pass the validation, the class "error" is added to the widget of that input. Then, using CSS, I give that .error class some specific styling. Here is the problem: the error style is not applied correctly to the fields "name", "last name" and "email" of the form. For instance, when you input an invalid last name, both the field "last name" and "name" get highlighted in red, and when you input an invalid email address, both the "email" and the "name" fields get highlighted. I have gone over the "forms.py" file a thousand times and I can't figure out what's wrong. Here is the code of the "forms.py" file: from django import forms from .models import Appointment class AppointmentForm(forms.ModelForm): class Meta: model = Appointment fields = ['name', … -
client_is_modern return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' TypeError: 'NoneType' object is not subscriptable
{ "error": "Input nbnb.csv of type: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> is not supported." } if not self.origin_server or self.client_is_modern(): File "C:\Program Files (x86)\lib\wsgiref\handlers.py", line 358, in client_is_modern return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' TypeError: 'NoneType' object is not subscriptable tried spliting that code but still its not working -
Django / Websocket : How to get all actives `websockets`?
I would like get all websockets opened with a consumer like an .objects.all(). It is possible like this ? or with another method to "list" all actives websockets ? Thank you everyone in advance for answers ! I found nothing about that in the documentation or anything else, but if a thing like that exists, it can very useful. -
NSUrlErrorDomain -1004 on Django Backend hosted by AWS (Route 53 + ELB) on iOS
Noticed today that some users are getting NSUrlErrorDomain (code -1004) by accessing our website, which is managed by ECS + ELB (6 rules) + Route 53. Obviously, those domains have ssl, but accessing the website on Safari and Firefox (iOS), I'm automatically redirected to the "http" version, making me get the "NSUrlErrorDomain" error. If I type the website starting "https", it goes normally, and it only happens on iOS (didn't test Android, but on Chrome doesn't happens), and also don't happen on Desktop, and on MacOS only happens using Safari browser. Any clue of what is that? -
CSRF verification failed. Request aborted with JWT token in Django RestAPI
I am currently encountering a 403 Forbidden error due to CSRF verification failure when making a POST request to my Django app's API endpoint, even while using a JWT token for authentication. I've attempted to disable CSRF protection for the API while maintaining it for the admin panel using a custom middleware, but the error persists. Below is the relevant configuration in my settings.py and views.py. I've tried to disable CSRF checks for my API endpoints using custom middleware, as well as the decorators @method_decorator(csrf_exempt) and @csrf_exempt, but the CSRF requirement still seems to be enforced. Here's an overview of the steps I've taken: settings.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', "django.middleware.common.CommonMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "spBE.middlewares.disable_csrf.DisableCSRFOnAPI", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ALLOWED_HOSTS = ['*'] CSRF_TRUSTED_ORIGINS = ['http://localhost:1337','http://localhost:8000','http://10.126.2.27:8000','http://10.126.2.27:1337'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework.permissions import AllowAny from rest_framework_simplejwt.authentication import JWTAuthentication schema_view = get_schema_view( openapi.Info( title="Domocek API", default_version='v1.1', description="Breakpoints", terms_of_service="https://app.slack.com/client/T04RV3CLJ2W/C06KV8FSY3X", contact=openapi.Contact(email="nikita@gmail.com"), license=openapi.License(name="License"), ), public=True, permission_classes=(AllowAny,), authentication_classes=(JWTAuthentication,), url='http://10.126.2.27:1337/', ) urlpatterns = [ path("admin/", admin.site.urls), path('api/', include('api.urls')), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] if settings.DEBUG: urlpatterns … -
DigitalOcean Spaces and Django/Wagtail - SSL error on upload
I have a Django/Wagtail app running on DigitalOcean AppPlatform and am trying to enable Spaces for media storage. The app builds just fine, but image uploads from the app fail every time with the following error: [2024-04-17 21:40:33] botocore.exceptions.SSLError: SSL validation failed for https://mybucket.mybucket.nyc3.digitaloceanspaces.com/original_images/Screenshot_2024-04-01_at_2.10.53PM.png hostname 'mybucket.mybucket.nyc3.digitaloceanspaces.com' doesn't match either of '*.nyc3.digitaloceanspaces.com', 'nyc3.digitaloceanspaces.com' That URL shows my bucket name repeated twice (note "mybucket.mybucket"), but I can't tell where or why it's repeating. In my production.py settings file, I'm using env vars set on the DigitalOcean side, and have triple checked that those vars are correct. I've also tried hardcoding them instead just to be sure, with the same error. AWS_ACCESS_KEY_ID = os.getenv('SPACES_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('SPACES_SECRET_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('SPACES_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_ENDPOINT_URL = os.getenv('SPACES_ENDPOINT_URL') AWS_S3_REGION_NAME = os.getenv('SPACES_REGION') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_ADDRESSING_STYLE = 'virtual' AWS_LOCATION = os.getenv('SPACES_FOLDER') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_URL = '%s/' % (AWS_S3_ENDPOINT_URL) I've added & installed the following in the app (including storages under INSTALLED_APPS): boto3 (v1.34.84) botocore (v1.34.84) django-storages (v1.14.2) And have a storages_backends.py with the following: from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = 'static' class MediaStorage(S3Boto3Storage): location = '' Any ideas on what is causing that … -
Integrating Auth0 with the Django admin interface
I have a Django application and I am trying to change the authentication flow to use Auth0. Unfortunately, I haven't found any tutorials on how to implement this. Currently, users log in with username/password and receive a session token. I would like to change this so users are redirected to Auth0, login there, receive the session credential, and are then redirected to the admin UI. Does anyone have any experience with this? I am very stuck. -
Error when adding object using django admin "incorrect padding"
I was adding an Ad in the admin interface to use to test some template code. Previously, yesterday, I was able to add Ads no problem. I log into admin, select add a new Add, then enter text into the CharField and TextFields of the model. Worked always before today. Now, I get an error. Error at /admin/ads/ad/add/ Incorrect padding I am using pythonanywhere. Below is the traceback: Environment: Request Method: POST Request URL: https://chabnet.pythonanywhere.com/admin/ads/ad/add/ Django Version: 4.2.7 Python Version: 3.10.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django_extensions', 'crispy_forms', 'crispy_bootstrap5', 'rest_framework', 'social_django', 'taggit', 'home.apps.HomeConfig', 'ads.apps.AdsConfig', 'knightshirt.apps.KnightshirtConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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', 'social_django.middleware.SocialAuthExceptionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware'] Traceback (most recent call last): File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/contrib/admin/options.py", line 688, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1886, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/home/chabnet/.virtualenvs/django4/lib/python3.10/site-packages/django/utils/decorators.py", line 134, … -
Adding HTML Button to Editor Buttons in Wagtail
I am having an issue wrapping my head around adding a custom button in Wagtail to the RichTextEditor buttons, where when clicked, a user of the editor is able to add a link with an html button. The code I used for this in TinyMCE was originally provided here: https://dev.to/codeanddeploy/tinymce-add-custom-button-example-399m But I can't figure out how to register a hook in Wagtail to implement that type of functionality. There is a similar example here, but I can't figure out how to enable the actual button to be rendered with style we predefine like I had done in TinyMCE editor. Here is an example that works fine for this use case, but I am hoping there is a simple one with the idea to add buttons like I had done with TinyMCE: https://erev0s.com/blog/wagtail-list-tips-and-tricks/#add-a-code-button-in-the-rich-text-editor Here is the code from that post: from wagtail.core import hooks @hooks.register("register_rich_text_features") def register_code_styling(features): """Add the <code> to the richtext editor and page.""" # Step 1 feature_name = "code" type_ = "CODE" tag = "code" # Step 2 control = { "type": type_, "label": "</>", "description": "Code" } # Step 3 features.register_editor_plugin( "draftail", feature_name, draftail_features.InlineStyleFeature(control) ) # Step 4 db_conversion = { "from_database_format": {tag: InlineStyleElementHandler(type_)}, "to_database_format": {"style_map": {type_: …