Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django "Pinax" magick ... unexplained form behavior
This legacy Django website uses "Pinax" for notification. I know for certain that the following "Signup" template is being used: {{ form.captcha.label }} {{ form.captcha }} {{ form.captcha.errors }} <br/> {{ form.email.label }} {{ form.email }} {{ form.email.errors }} <br/> {{ form.email2.label }} {{ form.email2 }} {{ form.email2.errors }} But here are my two problems. First of all, my "captcha" field is not appearing in the output. Second of all, I find no justification for the existence of "email2!" The "form" definition consists, in relevant part: email = forms.EmailField(widget=forms.TextInput()) confirmation_key = forms.CharField( max_length = 40, required = False, widget = forms.HiddenInput() ) # "Solve a math problem" challenge captcha = CaptchaField( label = "Solve A Simple Math Problem", widget = forms.TextInput() ) Notice that there is no "email-two." Yet, it appears with the label, "Email (again)." And, my "captcha" field does not appear in the template at all. I do not understand this "Django magick." I have searched the source code diligently for the phrase, "(again)." And I find no reference to it with regards to "email." (I have already, for other reasons, brought "pinax" directly into my project, because it appears to have been abandoned.) -
Add dynamic data to template
I need to put data into the sidebar. Haven't figured out any other sollution than context_processors. Is this the cleanest and optimal way to do this? Any help appreciated. I find it a bit strange that it has been so hard to find information re. this issue. So maybe this could be of help to others as well. # animals/context_processors.py from animals.models import Cows, Horses from django.shortcuts import render def allcows(request): cows = Cows.objects.all() return {"cows": cows} def lasthorses(request): horses = Horses.objects.all().order_by("-id")[:2] return {"horses": horses} Sidebar.html <h1>Sidebar</h1> <h3>All cows:</h3> {%for cow in cows%} <div> The name is {{ cow.name }}, and the age of {{ cow.name}} is {{ cow.age }}. </div> {%endfor%} <h3>last 2 horses:</h3> {%for horse in horses%} <div> The name is {{ horse.name }}, and the age of {{ horse.name}} is {{ horse.age }}. </div> {%endfor%} base.html <body> <div class="holy-grail-grid"> <header class="header">{% include 'animals/nav.html' %} </header> <main class="main-content"> <header id="main-header"> <h1>{% block main_heading %}Main Heading{% endblock %}</h1> <h3> {% block header_content %}Heading{% endblock %}</h3> </header> {% block content %} {% endblock %} </main> <section class="left-sidebar"> <p>My left sidebar{% include 'animals/sidebar.html' %} </p> </section> <aside class="right-sidebar"> <p>My right sidebar{% include 'animals/justinfo.html' %}</p> </aside> <footer class="footer"> <p>The footer</p> </footer> </div> … -
403 Forbidden Error for Django View Despite Permissions on Custom User Model (in userauths app)
I’m working on a Django project where I’ve implemented a custom user model (CustomUser) in the userauths app. The custom user model uses email as the unique identifier instead of the username. My goal is to allow certain users with specific permissions (change_product or delete_product) to edit or delete a product. However, even after assigning the appropriate permissions to the user, they’re still receiving a 403 Forbidden error. I’ve followed Django’s documentation for creating a custom user model, but I suspect there’s a misconfiguration or step I’ve overlooked. Here’s the detailed setup: Custom User Model and Manager (in userauths app): Below is the code for my custom user model and its manager: # userauths/models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext_lazy as _ class CustomUserManager(BaseUserManager): def _create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if not extra_fields.get('is_staff'): raise ValueError('Superuser must have is_staff=True.') if not extra_fields.get('is_superuser'): raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class … -
ManyToManyField lookup which Django seems doesn't support yet
I want to do something which it seems Django doesn't officially supports it yet. Here goes the models.py class Report(models.Model): # using default `AutoField`, `id` / `pk` pass class BulkOfReports(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid7, editable=False, verbose_name="ID", ) reports = models.ManyToManyField( Report, verbose_name=_("laporan-laporan"), related_name="bulk_of_reports", ) And for example if those BulkOfReports can be represented like this: BulkOfReports = [Reports_ids] Then with data like this: A = [1, 2, 3] B = [1, 2] C = [1] D = [2] E = [3] How could I get the A option only with Django's QuerySet API? I have tried this: self.reports.filter(id__in=[1, 2, 3]) But what I have is all of those QuerySet mentioned above: A, B, C, D, E -
SMTP ERROR using Django in Railway Production
I am getting error while trying the same end point locally so it's working properly fine but in production it dosen't work and always throwing this error. The code of my settings.py file is as EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True # or False depending on your setup EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') I am using my gmail (codingwithhasnin@gmail.com) and the password which I got from gmail app password which works fine locally and also on AWS EC2 instance but not in railway production. What can be the issue? -
Included App URLs not showing in DRF browsable API
I'm using the Django Rest Framework to provide an API, which works great. All needed URLs for routers and others too are hold in the root urls.py To better handle the growing number of routes I tried to move routes from Apps to their related app folders - as one would do with pure Django. # urls.py from django.contrib import admin from django.urls import include, path from rest_framework.routers import DefaultRouter import core.views router = DefaultRouter() router.register(r'core/settings', core.views.SettingsViewSet, basename='settings') router.register(r'core/organization', core.views.OrgViewSet, basename='org') urlpatterns = [ path('api/', include(router.urls)), path('api/een/', include('een.urls')), path('admin/', admin.site.urls), path('', include('rest_framework.urls', namespace='rest_framework')), path('api/tokenauth/', authviews.obtain_auth_token), ] # een/urls.py from django.urls import path, include from rest_framework import routers from . import views app_name = 'een' router = routers.DefaultRouter() router.register( r'cvs', views.EENSettingsViewSet, basename='een-cvs', ) urlpatterns = [ path('', include(router.urls)), ] Everything shown here is working as expected, but the included URLs are not shown in the browsable API. They are reachable and working, but they are not listed. I do use drf-spectacular, which correctly picks up even the included app urls. I've tried several different combinations, different url order, etc - with no luck. What do I overlook? Or is this a general thing with DRF and I should really keep everything … -
How to architect the external evnets and Django models?
I'm building a django backend app and I have a few different models in my app. One of these models is a Driver and I want to do the following when calling the create-driver endpoint: create the driver in database create a user account for the driver in my B2C directory send an email to the driver on successfull creation send a notification to admins on succesfull creation Operation 1 and 2 should either be succesfull or fail together (an atomic transaction). I was initially handling 1 and 2 in the Driver model's save method like this: Class Driver(models.Model): ... def save(self, *args, **kwargs): if self.pk is None: # Creating a new driver if self.b2c_id is None: graph_client = MicrosoftGraph() try: with transaction.atomic(): user_info = B2CUserInfoSchema( display_name=f"{self.first_name} {self.last_name}", first_name=self.first_name, last_name=self.last_name, email=self.email, phone_number=self.phone, custom_attributes={ "Role": UserRole.DRIVER.value, }, ) res = graph_client.create_user(user_info) # create B2C user self.b2c_id = res.id super().save(*args, **kwargs) # create driver in database except Exception as e: raise e else: # Updating an existing driver super().save(*args, **kwargs)``` This was working perfectly fine but I didn't like mixing responsibilites here and adding the B2C user creation logic to my Driver's save method. I like to keep the save method simple … -
Django with MSSQL Server – GUID Type is maped as char(32) not uniqueidentifier
I would like an app that can easily use different databases. Currently, I’m using SQLite and MSSQL, switching between them via a config file. I noticed that the following field could be quite important from a performance standpoint: user_guid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True, null=False, blank=False, db_index=True ) In MSSQL, the field is mapped as char(32), and I have mixed feelings about that. Over time, I might switch to PostgreSQL, but as I mentioned before, I’m not entirely comfortable using char(32) instead of uniqueidentifier. -
Celery chord, execute code after callback
I am working on a Django application that uses celery tasks for complex and time intensive calculations. I have a task in which subtasks are used to process a large number of combinations of values and determine the best combination based on predefined parameters. The subtasks are created like this: combinations = itertools.product(*bm) # setup for multicore processing using celery tasks static_args = (nt, mp, f, levels) chunk_size = 10000 tasks = _chunked(combinations, chunk_size) chunk_tasks = group(evaluate_combination_chunk.s(list(chunk), static_args) for chunk in tasks) final_task = compare_chunk_results.s() best_result = chord(chunk_tasks)(final_task) # do some stuff with this result return best_result the subtask methods like this: def evaluate_combination_chunk(chunk, static_args): # evaluate a chunk of combinations best_result = None highest_power = -1 for comb in chunk: result = evaluate_combination(comb, *static_args) if result[0] and result[1] > highest_power: best_result = result highest_power = result[1] return best_result and def compare_chunk_results(results): best_result = None highest_power = -1 for result in results: if result: if result[1] > highest_power: best_result = result highest_power = result[1] return best_result both marked with @shared_task(). so i am finding the best result in each chunk (that works just fine based on what i see in the console) and then compare those to find the best … -
Django Serializer - `methodViewSet(viewsets.ViewSet)` is not displayed in url list
I am trying to combine multiple serializers into a single API call, and as a result, I am using viewsets.ViewSet. I am aware that viewsets.ModelViewSet automatically generates the routes, but with viewsets.ViewSet, I am not seeing the expected route for my API. When I switch to viewsets.ModelViewSet, the route becomes available. This makes me think my issue is specific to how viewsets.ViewSet handles routing. According to the documentation (https://www.django-rest-framework.org/api-guide/viewsets/), I should be able to register the URL like I would with ModelViewSet. However, the route doesn't appear when using viewsets.ViewSet. Any suggestions on what might be going wrong? views.py class MethodViewSet(viewsets.ViewSet): permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] @action(detail=False, methods=['get'], url_path='method-path') def list(self, request): ... urls.py from rest_framework.routers import DefaultRouter from .views import ( MethodViewSet, ) from rest_framework.authtoken.views import obtain_auth_token router = DefaultRouter() ... router.register(r'method-path', MethodViewSet, basename='methodbasename') -
Twilio Return gathering after client press star
I'm trying to create a fallback gathering if the interpreter hangup from the conference while the client is still on the line, I have to return the gathering to the client to ask him if he wants another interpreter or disconnect everything work perfect but, when the client pressed star, the gather said the first part of the word only, and then the call disconnected def handle_incoming_call(self, call_sid, from_number, language_code): try: with transaction.atomic(): next_interpreter = CallSelector.get_next_interpreter(language_code) conference_name = f"conferenceـ{call_sid}" conference = CallSelector.create_conference( language=next_interpreter.language, interpreter=next_interpreter.interpreter, conference_name=conference_name, ) response = VoiceResponse() response.say("Please wait while we connect you with an interpreter") dial = Dial( hangup_on_star=True, action=f"{settings.BASE_URL}/api/calls/webhook/interpreter_leave/{conference.conference_id}/", timeout=30, ) dial.conference( conference_name, start_conference_on_enter=True, end_conference_on_exit=False, # record=True, # recording_status_callback=f"{settings.BASE_URL}/api/calls/webhook/recording/{conference.conference_id}/", status_callback=f"{settings.BASE_URL}/api/calls/webhook/conference-status/{conference.conference_id}/", status_callback_event="start end join leave announcement", status_callback_method="POST", beep=True, participant_label="client", ) response.append(dial) self._add_client_to_conference(conference, from_number, call_sid), self._call_interpreter(conference, next_interpreter.interpreter), return response except Exception as e: logger.error(f"Call handling failed: {str(e)}", exc_info=True) return self._generate_no_interpreter_twiml() And here is the callback interpreter_leave def handel_interpreter_leave(self, conference_id: str): try: print("Interpreter leave handling started") conference = CallSelector.get_conference_by_conference_id(conference_id) response = VoiceResponse() gather = Gather( num_digits=1, action=f"{settings.BASE_URL}/api/calls/webhook/client_choice/{conference_id}/", method="POST", timeout=10, input="dtmf", ) gather.say("Press 1 to connect with a new interpreter, or press 2 to end the call.") response.append(gather) return response except Exception as e: logger.error(f"Interpreter leave handling failed: {str(e)}", exc_info=True) … -
Show Data of Customer and License from database according to the click on dropdown list of financial year
dropdown financial year show data from database as per the financial year in all pages enter image description here dropdown that i created def get_financial_year(date): year = date.year if date.month < 4: # before April, in the previous financial year year -= 1 return f'{year}-{year + 1}' financial_years = {} for license in licenses: financial_year = get_financial_year(license.Subscription_End_Date) if financial_year not in financial_years: financial_years[financial_year] = 0 financial_years[financial_year] += 1 print(financial_years.keys()) financial_years_list = sorted(financial_years) how show data -
SMTP Error in Django on Production using Railway
I am getting error while trying the same end point locally so it's working properly fine but in production it dosen't work and always throwing this error. The code of my settings.py file is as EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True # or False depending on your setup EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') -
Django view is rendering 404 page instead of given html template
I'm working on a wiki project with django. I'm trying to render 'add.html' with the view add, but it sends me to 404 instead. All the other views are working fine. How should I fix add? views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django import forms import re from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def detail(request, entry): #if search based on title returns result if util.get_entry(entry): content = util.get_entry(entry) return render(request, "encyclopedia/details.html", { "title": entry, "content": content }) else: return render(request, "encyclopedia/404.html", { 'entry': entry }) def add(request): return render(request, "encyclopedia/add.html") urls.py: from django.urls import path from . import views app_name = "wiki" urlpatterns = [ path("", views.index, name="index"), path("<str:entry>/", views.detail, name="entry"), path("add/", views.add, name="add"), ] -
How fix redirect after registration? Django
today I faced such a problem that after registration the form does not go anywhere. The catch is that the form does not send a request to the database, but I can create a user through the Django admin panel. views.py def registration(request): if request.method == 'POST': form = UserRegistrationForm(data=request.POST) if form.is_valid(): form.save() user = form.instance auth.login(request, user) messages.success( request, f'{user.username}, Successful Registration' ) return HttpResponseRedirect(reverse('user:login')) else: form = UserRegistrationForm() return render(request, 'users/registration.html') forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm, \ UserCreationForm, UserChangeForm from .models import User class UserLoginForm(AuthenticationForm): username = forms.CharField() password = forms.CharField() class Meta: model = User fields = ['username', 'password'] class UserRegistrationForm(UserCreationForm): class Meta: model = User fields = ( 'first_name', 'last_name', 'username', 'email', 'password1', 'password2', ) first_name = forms.CharField() last_name = forms.CharField() username = forms.CharField() email = forms.CharField() password1 = forms.CharField() password2 = forms.CharField() class ProfileForm(UserChangeForm): class Meta: model = User fields = ( 'image', 'first_name', 'last_name', 'username', 'email', ) image = forms.ImageField(required=False) first_name = forms.CharField() last_name = forms.CharField() username = forms.CharField() email = forms.CharField() registration.html {% extends 'main/base.html' %} {% load static %} {% block title %}Registration{% endblock title %} {% block content %} <section class="login-reg d-flex"> <div class="login-title"> <h2>Registration</h2> <form action="{% … -
Django Template Override Works Locally but Not on Azure
I’m working on a Django project where I’m overriding the submit_line.html template. This override works perfectly in my local development environment, but when I deploy the application to Azure, the override doesn’t seem to take effect. Here’s the custom submit_line.html override in my templates directory: {% extends 'admin/submit_line.html' %} {% load i18n admin_urls %} {% block submit-row %} {{ block.super }} {% for obj in transitions %} <input type="submit" value="{{ obj }}" name="{{ obj }}"> {% endfor %} <!--{{ perms.ForecastResponse }}--> {%if perms.ForecastResponse.add_project%} <input type="submit" value="{% translate 'Clone project from source'%}" name="_cloneproject"> {%endif%} {% endblock %} File structure: myproject/ ├── ForecastResponse/ │ ├── migrations/ │ ├── templates/ │ │ └── admin/ForecastResponse/project │ │ | └── submit_line.html # Overridden template │ │ ├── ForecastResponse/ │ │ │ ├── base.html # Global base template │ │ │ ├── other_template.html │ │ ├── static/ │ │ ├── views.py │ │ ├── models.py │ │ └── admin.py │ ├── manage.py │ ├── settings.py │ ├── urls.py │ └── other_project_files/ What I've tried: Verified that the custom submit_line.html file exists in the correct location on Azure by inspecting the deployed files. Updated the settings.py to include the TEMPLATES section: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
Can not get group permissions by custom User and Group
I create my custom user and group as below: models.py (myusers app) ` from django.db import models from django.contrib.auth.models import AbstractUser, GroupManager, Permission class AbstractGroup(models.Model): name = models.CharField(_("name"), max_length=150, unique=True) permissions = models.ManyToManyField( Permission, verbose_name=_("permissions"), blank=True, related_name="fk_group_permission", ) objects = GroupManager() def __str__(self): return self.name def natural_key(self): return (self.name,) class Meta: verbose_name = _("group") verbose_name_plural = _("groups") abstract = True class Group(AbstractGroup): is_active = models.BooleanField(_("Is Active"), default=True) class User(AbstractUser): groups = models.ManyToManyField( Group, verbose_name=_("groups"), blank=True, help_text=_( "The groups this user belongs to. A user will get all permissions " "granted to each of their groups." ), related_name="user_set", related_query_name="user", ) ` and point in settings.py: AUTH_USER_MODEL=myusers.User AUTH_GROUP_MODEL=myusers.Group All is ok but when get group permissions (a_user.get_all_permissions() or a_user.get_group_permissions()) raise error: ValueError: Cannot query “a_user”: Must be “Group” instance. (a_user here is the user user instance) what is wrong? The get_group_permissions() return error. -
retrieving media files on render with django
Hopefully a simple issue that I cannot find any answer to online so far. Background : I have an django web app that is hosted on render.com. Everything is working apart from the media files that are hosted on a bought disk (mounted at /var/data) for my project. I have followed the documentation and added the following to settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = '/var/data' media context is set: "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.template.context_processors.media", ], I have urlpatterns configured for media: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) whitenoise is configured: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' requirements.txt asgiref==3.8.1 click==8.1.8 dj-database-url==2.3.0 Django==5.1.4 django-crispy-forms==2.3 gunicorn==23.0.0 h11==0.14.0 packaging==24.2 pillow==11.0.0 psycopg2-binary==2.9.10 sqlparse==0.5.3 typing_extensions==4.12.2 uvicorn==0.34.0 whitenoise==6.8.2 index.html {% extends "airfryer_app/base.html" %} {% block body %} <div class="product-container flex flex-wrap justify-content-center"> {% for recipe in recipes %} <div class="product shadow-lg w-1/5 rounded-lg m-10"> <div class="product-image"> <img src="{{ recipe.image.url }}" alt=""> </div> <div class="p-5"> <div class="font-bold"> {{ recipe.name }} </div> <div> {{ recipe.description }} </div> <div class="text-orange-700 font-bold text-orange"> {{ recipe.time }} minutes </div> <div class="mt-5"> <a class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded" href="{% url 'recipe' recipe.id %}">View Details</a> </div> </div> </div> {% if forloop.counter|divisibleby:3 %} <div class="w-full"></div> {% endif %} {% endfor %} </div> {% endblock %} Using … -
How to reuse mysql persistant connection in uwsgi + django + multi threading?
My Env: DJANGO 4.1 UWSGI 2.0.26 processes + gevent mode And I Use concurrent.futures.ThreadPoolExecutor as my thread pool I know that django mysql connecition is thread local. If I create thread pool in request thread, then pool thread id is different in each request so mysql connection is not reused.But if I create thread pool in uwsgi processes,the connection cannot be recycled after request finished and it will throw "Mysql server has gone away" afeter a few time. So how to reuse mysql connection correctly in my run env? -
Django REST + API Gateway CORS Issue with Cognito Authentication
I have issues with CORS, most likely due to Frontend (Amplify) being https and backend (ElasticBeanstalk) being http. Tried to fix unsuccessfully with API Gateway. Frontend: React app hosted on AWS Amplify Backend: Django REST framework on Elastic Beanstalk Authentication: AWS Cognito API Gateway as proxy between frontend and backend Issue: Getting CORS error when frontend tries to access backend through API Gateway. With Chrome CORS disabled, the request reaches backend but fails with Django auth error. Frontend (React/TypeScript): const fetchVideos = async () => { const session = await fetchAuthSession(); const token = session.tokens?.idToken?.toString(); // Token looks valid: eyJraWQiOiJxTHpReFZa... const fullUrl = `${BASE_URL}/api/premium-content`; const response = await fetch(fullUrl, { method: 'GET', credentials: 'include', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', } }); } Django Settings (base.py): CORS_ALLOWED_ORIGINS = [ "https://my-frontend.amplifyapp.com", "http://localhost:5173", "http://localhost:3000" ] CORS_ALLOW_CREDENTIALS = True API Gateway Configuration ANY method: HTTP Proxy integration to EB endpoint OPTIONS method: Mock integration with headers: Access-Control-Allow-Origin: 'https://my-frontend.amplifyapp.com' Access-Control-Allow-Methods: 'GET,OPTIONS' Access-Control-Allow-Headers: 'Content-Type,Authorization' Access-Control-Allow-Credentials: 'true' Gateway responses: 4XX and 5XX enabled for CORS Seeing the error message in the console log: Access to fetch at 'https://[api-gateway-url]/prod/api/premium-content' from origin 'https://my-frontend.amplifyapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control … -
font Tag issue in summer note
<font style="background-color: rgb(255, 255, 0);" color="#ff0000">Write something</font> Above tag generated by Summernote; the color property came outside of the style attribute. How can I fix this issue?" anyone found same problem that iam facing if you found let me know it will help me lot -
Why does Auth0 use /login/callback instead of my configured callback URL in the redirect to Azure AD?
I am implementing Okta - Auth0 with Azure Active Directory (Azure AD) as the identity provider (IdP) in my Django project. Here's a breakdown of my setup: Django OAuth Configuration: Callback URL in Django: https://mydomain/api/auth/callback/. My Django app redirects users to the Auth0 /authorize endpoint with the correct redirect_uri. Auth0 Application Settings: Allowed Login URLs: https://mydomain/api/auth/login/. Allowed Callback URLs: https://mydomain/api/auth/callback/. Allowed Logout URLs: https://mydomain/api/auth/logout/. Azure AD Application Settings: Redirect URI: https://mydomain/api/auth/callback/. Problem: When I delete the default callback (https://dev-xxxxx.ca.auth0.com/login/callback) from Azure AD, the login process fails with the following error from Azure AD: AADSTS50011: The redirect URI 'https://xxxxxxca.auth0.com/login/callback' specified in the request does not match the redirect URIs configured for the application. However, I have not included the okta default /login/callback in my Auth0 configuration. I only use /api/auth/callback/. The flow seems to depend on this default callback URL, even though I expect Auth0 to use my configured callback (/api/auth/callback/) throughout the login flow. Questions: Why does Auth0 internally use https://dev-xxxxxx.ca.auth0.com/login/callback instead of the configured callback URL (/api/auth/callback/) when redirecting to Azure AD? How can I eliminate the dependency on the default callback (/login/callback) and ensure the entire flow uses my custom callback (/api/auth/callback/)? Steps I’ve Tried: Ensured https://mydomain/api/auth/callback/ is … -
Switching Django USE_TZ to True
I have a site which is pretty old (started at Django 1.6) but has been upgraded over time and is now at Django 4.2. It has always had USE_TZ=False and TIME_ZONE='America/Chicago'. We have a lot of critical dates (subscriptions, purchase records, etc), many of which are fed from external webhooks from our payment processor. I'm looking at adding another Django app, but it requires USE_TZ=True. Anyone have any insight into what might happen if I turn it on? I've turned it on in my development environment and I don't see any obvious issues, but can't easily replicate the webhooks I receive and daily tasks that extensively use date calculations. Where should I be looking for issues? -
убрать надпись в регистрации This field is required [closed]
Я использую встроенную в джанго форму UserCreationForm для создания формы регистрации, но есть лишние предписания 'This field is required.' о том что эти поля обязательны, я хочу убрать их, помогите пожалуйста, ну или хотя бы перевести на русский что-б надпись была на русском, если так же сможете помочь исправить clean_email в формах так что б он не всегда выкидывал эту надпись после 1 тестового ввода существующего email вот скрин результата enter image description here views.py: class RegisterUser(CreateView): form_class = RegisterUserForm template_name = 'users/register.html' extra_context = {'title': 'Регистрация'} success_url = reverse_lazy('users:login') forms.py: class RegisterUserForm(UserCreationForm): username = forms.CharField(label="Логин:", widget=forms.TextInput(attrs={'class': "form-input"})) password1 = forms.CharField(label="Пароль:", widget=forms.PasswordInput(attrs={'class': "form-input"})) password2 = forms.CharField(label="Повтор пароля:", widget=forms.PasswordInput(attrs={'class': "form-input"})) class Meta: model = get_user_model() fields = {'username', 'email', 'first_name', 'last_name', 'password1', 'password2'} labels = { 'username': 'Логин', 'email': 'E-mail', 'first_name': 'Имя', 'last_name': 'Фамилия', 'password1': 'Пароль', 'password2': 'Повторить пароль', } widgets = { 'username': forms.TextInput(attrs={'class': "form-input"}), 'first_name': forms.TextInput(attrs={'class': "form-input"}), 'last_name': forms.TextInput(attrs={'class': "form-input"}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.order_fields(['username', 'email', 'first_name', 'last_name', 'password1', 'password2']) def clean_email(self): email = self.cleaned_data['email'] if get_user_model().objects.filter(email=email).exists(): raise forms.ValidationError("Такой E-mail уже существует") return email users/register.html: {% extends 'users/base.html' %} {% block title %}Регистрация{% endblock %} {% block content %} <h1>Регистрация</h1> <form method="post"> {% csrf_token %} {{ … -
Wagtail - add custom link option
I would like to customize External link type in Wagtail links in admin RichText field - I need to change (or at least disable) the link validation (e.g., to my custom regex) in admin frontend, as my links have different format to https://<something>. Does anybody know how to do that without forking wagtail and making own addition in this and this file? Any help would be appreciated.