Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User authorization in django and the ways to achieve it if the default User model is extended to create custom User model
I am working on building a movie ticket booking website. I am told to implement authorization in the project so that only superuser can do certain actions on mongodb database(like adding movies and theatres). Please help me in understanding this process and the ways to achieve this. And also I am getting an error when creating superuser. I am attaching the code for the reference. models.py --> from .userManage import UserManager class User(AbstractBaseUser): id=models.AutoField(primary_key=True,null=False) name=models.CharField(max_length=100) email=models.CharField(max_length=60) password=models.CharField(max_length=16) username=models.CharField(max_length=20,unique=True) mobileNumber=models.IntegerField() USERNAME_FIELD = 'username' objects=UserManager() usermanage.py - this python file is in same directory path from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self,username,password,**extra_fields): if not username: return ValueError("Username should be provided") user=self.model(username=username,**extra_fields) user.set_password(password) user.save() return user def create_superuser(self,username,password,**extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) return self.create_user(username,password,**extra_fields) The error in creating superuser when I entered username and password: User() got unexpected keyword arguments: 'is_staff', 'is_superuser'. Please help! -
Django Python: AttributeError: 'NoneType' object has no attribute 'startswith'
I bumped into the error when running python3 manage.py runserver. I have mydb.py in the project's root directory (same as manage.py), in order to connect to MySQL and create a database (if it does not exist). mydb.py and settings.py share same database configuration which is loaded from environment variables in .env. .env: ENV=DEV SECRET_KEY='django-insecure-9#1j%osjd33e' DB_NAME=todolist DB_USER=user DB_PASSWORD=12345 DB_HOST=localhost DB_PORT=3306 settings.py: import os from os.path import join, dirname from dotenv import load_dotenv, find_dotenv # (1) ENV = os.environ.get('ENV') if ENV == 'PROD': env_filename = '.env.prod' elif ENV == 'TEST': env_filename = '.env.test' # elif ENV == 'DEV': # env_filename = '.env.dev' else: env_filename = '.env' dotenv_path = join(dirname(__file__), env_filename) load_dotenv(dotenv_path) ... # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), } } ... mydb.py: import mysql.connector import os from os.path import join, dirname from dotenv import load_dotenv, find_dotenv ENV = os.environ.get('ENV') if ENV == 'PROD': env_filename = '.env.prod' elif ENV == 'TEST': env_filename = '.env.test' # elif ENV == 'DEV': # env_filename = '.env.dev' else: env_filename = '.env' dotenv_path = join(dirname(__file__), env_filename) load_dotenv(dotenv_path) dataBase = mysql.connector.connect( host = os.environ.get('DB_HOST'), user = os.environ.get('DB_USER'), passwd = os.environ.get('DB_PASSWORD'), ) dataBase = mysql.connector.connect() ... Problem: … -
In Django, how do I generate a queryset containing the results of a many-to-many relationship in reverse direction?
I have the following model layout class Group(models.Model): group_name = models.CharField(max_length=100, default="New Group") group_created_date = models.DateField(default=date.today) class GroupMember(models.Model): groups_joined = models.ManyToManyField(Group) email = models.EmailField(max_length=100) name = models.CharField(max_length=100) I'm trying, in a class based view, to return a queryset of all group members for a given group. My attempt so far: def get_queryset(self): groupid = self.kwargs['groupid'] qs = Group.objects.filter(groupmember__groups_joined__id=groupid).order_by('-id') return qs However, this gives an error. Related Field got invalid lookup: groups_joined groups_joined is the column that has a relationship to the Group table, and I seem to be accessing it the right way using double underscores as I have. I want to return only group members that have en entry in groups_joined matching the current group with the ID matching groupid. What is the correct way to format a query that will accomplish this? -
Django built-in authentication form is not rendering inside the Bulma modal
I've created the template file "templates/registration/login.html." This file will be {%include '../registration/login.html' %} in the header of my navbar-menu in the header.html file. login.html <div x-data="{ modalopen: false }"> <a class="navbar-item " x-cloak href="" @click.stop.prevent="modalopen = !modalopen"> Login </a> <div class="modal" x-bind:class="modalopen ? 'is-active' : ''" > <div class="modal-background" ></div> <div class="modal-content has-background-white py-5 px-5" @click.stop.outside="modalopen = false"> <form method="post" action="/"> {% csrf_token %} {{ form.as_p }} <button class="button is-success" type="submit">Login</button> </form> <button class="modal-close is-large" aria-label="close" @click.stop="modalopen = false"></button> </div> </div> </div> In the future, I will use HTMX, but I need to address the form rendering problem first. The urls.py has path("accounts/", include("django.contrib.auth.urls")), and the forms and views are from the Django built-in authentication system. Without the modal, the login form appears. The modal closes (with the button and outside click), so Alpine.js is not the problem. The button is styled, so Bulma is working as well. However, the modal appears without the forms. "I don't think it's important, but this is the header.html file." <header> <nav x-data="{ open: false }" x-cloak class="navbar is-light" role="navigation" aria-label="main navigation"> <div class="navbar-brand"> <a class="navbar-item brand-text is-size-4 has-text-dark" href="/"> SITE </a> <div class="navbar-item"> <div class="control"> <input class="input is-rounded is-fullwidth" type="text" placeholder="Search..."> </div> </div> … -
Django Microsoft Authentication: Page not found (404)
I am developing a Django app and attempting to integrate Microsoft authentication using the django_microsoft_auth library by following the steps outlined in the documentation here. However, I'm encountering a "Page not found (404)" error when trying to access /microsoft/authenticate/. Here's the error message: Page not found (404) Request Method: GET Request URL: https://127.0.0.1:8000/microsoft/authenticate/?next=/validate/ I have added the necessary configurations in my settings.py: INSTALLED_APPS = [ # ... other apps ... 'django.contrib.sites', 'microsoft_auth', 'sslserver', ] SITE_ID = 2 # the id matches the record in the django_site table with the corporate email domain. # ... other settings ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], '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', 'microsoft_auth.context_processors.microsoft', ], }, }, ] AUTHENTICATION_BACKENDS = [ 'microsoft_auth.backends.MicrosoftAuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ] LOGIN_URL = '/microsoft/authenticate/' # Using Microsoft authentication LOGIN_REDIRECT_URL = '/dashboard/' LOGOUT_REDIRECT_URL = '/' MICROSOFT_AUTH_CLIENT_ID = 'your_client_id' MICROSOFT_AUTH_TENANT_ID = 'your_tenant_id' MICROSOFT_AUTH_CLIENT_SECRET = 'your_client_secret' MICROSOFT_AUTH_LOGIN_TYPE = 'ma' MICROSOFT_AUTH_LOGIN_REDIRECT = '/microsoft/auth-callback/' And my urls.py looks like this: from django.urls import path from . import views from django.contrib.auth import views as auth_views from django.conf.urls import include urlpatterns = [ # ... other paths ... path('microsoft/', include('microsoft_auth.urls', namespace='microsoft')), ] Additionally, I have registered my Django app in … -
Understanding TemplateResponseMixin class in django.views.generic.base module
Let's say we inherit TemplateView and till now we are not defining any methods. So the child class will somewhat look like this: class ChildClass(TemplateView): """ A default context mixin that passes the keyword arguments received by get_context_data() as the template context. """ extra_context = None def get_context_data(self, **kwargs): kwargs.setdefault("view", self) if self.extra_context is not None: kwargs.update(self.extra_context) return kwargs """ Intentionally simple parent class for all views. Only implements dispatch-by-method and simple sanity checking. """ http_method_names = [ "get", "post", "put", "patch", "delete", "head", "options", "trace", ] def __init__(self, **kwargs): """ Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. """ # Go through keyword arguments, and either save their values to our # instance, or raise an error. for key, value in kwargs.items(): setattr(self, key, value) @classproperty def view_is_async(cls): handlers = [ getattr(cls, method) for method in cls.http_method_names if (method != "options" and hasattr(cls, method)) ] if not handlers: return False is_async = iscoroutinefunction(handlers[0]) if not all(iscoroutinefunction(h) == is_async for h in handlers[1:]): raise ImproperlyConfigured( f"{cls.__qualname__} HTTP handlers must either be all sync or all " "async." ) return is_async @classonlymethod def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in … -
CSRF token not being set in Django leading to 403 on client-side
When making a POST request with axios from an endpoint in django, the CSRF token cookie seems to not be set, because of this it gives me a 403 status code. which i couldn't fix even after days trying to BACKEND: i've used cors-headers in django to set up in settings the CSRF_TRUSTED_ORIGINS,CSRF_COOKIE_DOMAIN and the CORS_ALLOWED_ORIGINS to all match the origin frontend's url but still didn't work. i also set CORS_ALLOW_CREDENTIALS = True, for context the middlewares config are on point too though. in the endpoint view i have already tried ensure_csrf_cookie with no success, because it is a class-based-view i have tried method_decorator too without success FRONTEND: i have defined default names for csrf header and token name in order for me to include them in my axios.post call and get the actual value of the csrftoken cookie with a getCookie function but it always returns null, which probably means the server-side isn't setting this csrf cookie at all :( : axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'; axios.defaults.xsrfCookieName = 'csrftoken';) the function is the getCookie(code at the end) that takes the defined name of the cookie as a param: const csrftoken = getCookie('csrftoken') for that to be later included into my axios … -
TypeError "Field 'id' expected a number but got <built-in function id>."
I am working on an auction application in Django. When I try to create a new listing I get a Type Error saying, Type Error at/create> "Field 'id' expected a number but got <built-in function id>". It also highlights views.py, line 81: "viewListing = Listing.objects.get.(pk=id)". What input should I pass to make this work properly? I expected to be redirected to the index view which would include the newly created listing. Here is the relevant view from views.py: @login_required def create(request): if request.method == "GET": categories = Category.objects.all() return render(request, "auctions/create.html", { "categories": categories }) else: title = request.POST\["title"\] description = request.POST\["description"\] image = request.POST\["image"\] price = request.POST\["price"\] category = request.POST\["category"\] categories = Category.objects.get(categoryType=category) sessionUser = request.user viewListing = Listing.objects.get(pk=id) viewListing.watchlist.add(sessionUser) bid = Bid(bid=float(price), user=sessionUser) bid.save() listing = Listing( title=title, description=description, image=image, price=bid, category=categories, owner=sessionUser ) listing.save() return HttpResponseRedirect(reverse(index)) Here is urls.py: from django.urls import path from . import views urlpatterns = \[ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create", views.create, name="create"), path("categories/", views.categories, name="categories"), path("filter/\<int:category_id\>", views.filter, name="filter"), path("listing/\<int:id\>", views.listing, name="listing"), path("remove/\<int:id\>", views.remove, name="remove"), path("add/\<int:id\>", views.add, name="add"), path("watchlist", views.watchlist, name="watchlist"), path("comment/\<int:id\>", views.comment, name="comment"), path("bid/\<int:id\>", views.bid, name="bid"), path("close/\<int:id\>", views.close, name="close") \] And just in case, … -
Angular v17 Error Forbidden (CSRF cookie not set.):
¿Alguien sabe como solucionar este problema Angular v17 Error Forbidden (CSRF cookie not set.):? Hola, hace muy poco me he comenzado a aventurar en Angular creando una web donde se use Angular como FrontEnd y Django como Backend, bueno resulta que quiero crear un formulario para registrarse y enviar los datos ingresados a Django, el problema es que cuando hago el POST sale el siguiente error, les dejo parte de la consola para que se vea donde se cae exactamente: Entrando a función get token [16/Jan/2024 21:47:49] "GET /obt_csrf_token/ HTTP/1.1" 200 82 Forbidden (CSRF cookie not set.): /procesar_registrarse/ [16/Jan/2024 21:47:51] "POST /procesar_registrarse/ HTTP/1.1" 403 2869 views.py from django.shortcuts import render from django.http import JsonResponse from django.middleware.csrf import get_token from django.views.decorators.csrf import csrf_protect # Create your views here. def inicio(request): return render(request, 'inicio/index.html') def obt_csrf_token(request): csrf_token = get_token(request) print("Entrando a función get token") return JsonResponse({'csrf_token': csrf_token}) @csrf_protect def procesar_registrarse(request): print("Entrando a función registrarseeeeeeee") if request.method == 'POST': print("Procesar registrarse") print(request) data = request.POST.get(request) print(data) return JsonResponse({'success': True}) else: print("ERROOOOOOOOOOOR") return JsonResponse({'mensaje': 'Metodo no permitido'}, status=405) settings.py from pathlib import Path import os DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'DjangoBackApp', 'corsheaders' ] MIDDLEWARE … -
Next JS 14 cookie management for Login with Django
So, I am using nextjs 14 with Django as my backend and so far, things have been quite difficult to get working but I like the combination. Now, I have to authenticate users and so far, I have a client form that has a function handler which calls a server action. I tried passing the server action directly, but I am not sure how to pass errors and show them in the form. I am using redux and rtk query for client-side requests as per the redux recommendations. My previous workflow before using nextjs was to send a request to the Django Api and if the credentials are valid the response would include necessary data like the access token and a http only cookie containing the refresh token. The access token would be put in the state and if it expires the refreshtoken api would be called to refresh both tokens. This approach works and you can tell me if its secure (all over https ofc). But, for experimentation now I have the form use a server-side action and inside it calls the login Api but now the refresh token is included in the response. When the action receives the … -
How to set up django-defender to work with django-two-factor-auth (django-otp)
I created a django app utilizing the django-two-factor-auth to enable two factor authorization using google authenticator. I also configured django-defender to protect my site from brute force attacks. It works correctly for the default django.contrib.auth. However it doesn't do anything for the custom otp authorization page. From my research I suppose the custom login method should be decorated with @watch_login from defender.decorators. But I have no clue which method should that be (possibly one from django-otp?) nor how to override this method with the decorator in my code. By the way - the django-two-factor-auth is already utilizing some kind of preventing brute force attacks - the screen where you submit google authorization code is correctly locking out after a few tries. However the first 'standard' login page does not utilize that feature. If django-defender is not the right method to do this I am open to any other suggestions. -
using django rest framework not able to save multiple items
I'm creating models and serializers for placing an order from a menu. The Order can have multiple MenuItem's: class MenuItem(models.Model): name = models.CharField(max_length=40) price = models.FloatField(default=0.0) class Order(models.Model): customer = models.CharField(max_length=50) order_time = models.DateTimeField(auto_now_add=True) items = models.ManyToManyField(MenuItem, through='OrderItem') class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class MenuItemSerializer(serializers.ModelSerializer): class Meta: model = MenuItem fields = "__all__" class OrderItemSerializer(serializers.ModelSerializer): menu_item = MenuItemSerializer() class Meta: model = OrderItem fields = "__all__" class OrderSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True, read_only=True) class Meta: model = Order fields = "__all__" When I drop into the django shell and test the serialiser: order_data = {'customer': 'John Doe', 'items': [{'menu_item': 5, 'quantity': 2}, {'menu_item': 8, 'quantity':3}]} order_serializer = OrderSerializer(data=order_data) order_serializer.is_valid() # TRUE order_serializer.save() It's not saving the items: {'id': 5, 'items': [], 'customer': 'John Doe', 'order_time': '2024-01-16T22:09:55.800262Z'} There is nothing being created in OrderItem. OrderItem.objects.all() gives an empty QuerySet. -
django-contact-form: using super().save(...) to save a an object field not working
I'm using django-contact-form package and it works well for what I need. But, with my use of super().save(fail_silently=fail_silently, *args, **kwargs), it does not appear to be saving the info from the form as a Contact object field. I had thought this was the way go about it but it doesn't appear to be working. I'd like to save the object in the form.save() method since we're directly using the package's ContactFormView defined in our urls.py path definition for /contact and don't require any customization there. My code: # model: class Contact(models.Model): name = models.CharField(max_length=100, default="") subject = models.CharField(max_length=255, default="") email = models.EmailField() body = models.TextField() def __str__(self): return self.subject[:100] class Meta: ordering = ("-created",) # form: class CustomContactForm(ContactForm): template_name = "core/django_contact_form/contact_form.txt" subject_template_name = "core/django_contact_form/contact_form_subject.txt" name = forms.CharField(label="Full Name") subject = forms.CharField(max_length=255, label="Subject") email = forms.EmailField(label="Email") recipient_list = ['admin@localhost',] class Meta: model = Contact fields = ["name", "subject", "email", "body"] def save(self, fail_silently=False, *args, **kwargs): try: super().save(fail_silently=fail_silently, *args, **kwargs) except Exception as e: print(f"Error saving Contact object: {str(e)}") send_mail(fail_silently=fail_silently, **self.get_message_dict()) There are no exception errors shown, so it looks like I am missing something that would get this to work as intended. What … -
In Django, how do I obtain a queryset of fields in a relate table, and return it along with context data from a class based view?
I have the following model layout class Group(models.Model): group_name = models.CharField(max_length=100, default="New Group") group_created_date = models.DateField(default=date.today) class GroupMember(models.Model): groups_joined = models.ManyToManyField(Group) email = models.EmailField(max_length=100) name = models.CharField(max_length=100) I'm trying, in a class based view, to return a queryset of all group members for a given group. I want to return this queryset, along with context data via a class based view. My attempt so far: class viewgroup(LoginRequiredMixin, SingleTableView): def get_queryset(self): groupid = self.kwargs['groupid'] qs = Group.objects.filter(groupmember__groups_joined__id=groupid).order_by('-id') return qs def get_context_data(self, **kwargs): groupid = self.kwargs['groupid'] group = Group.objects.get(id=groupid) context = { 'group': group, } return context def get_template_names(self): return ['myapp/viewgroup.html'] def get_table_class(self): return GroupTable If I have def_context_data there, I get an error in my template (which mainly just calls render table from django-tables2) that a queryset, not a string was expected. Somehow, the context data gets passed to render_table instead of the queryset. Without trying to pass context data, I get an error because of my query: Related Field got invalid lookup: groups_joined What is the correct way to construct a query to retrieve rows via a relationship, and to pass it as a queryset along with context data from a class based view? -
Django doesn't recognize the Pillow library
The installation was done correctly and appears in (venv). requirements: asgiref==3.7.2 Django==4.2.8 fontawesomefree==6.5.1 pillow==10.2.0 psycopg2==2.9.9 psycopg2-binary==2.9.9 sqlparse==0.4.4 typing_extensions==4.8.0 tzdata==2023.3 (venv) PS C:\Users\adminufpi\PycharmProjects\setorT> python -m pip show Pillow Name: pillow Version: 10.2.0 Summary: Python Imaging Library (Fork) Home-page: Author: Author-email: "Jeffrey A. Clark (Alex)" mailto:aclark@aclark.net License: HPND Location: c:\users\adminufpi\pycharmprojects\setort\venv\lib\site-packages Requires: Required-by: model: class Manutencao(models.Model): id = models.BigAutoField(primary_key=True) veiculo = models.ForeignKey(Veiculo, on_delete=models.CASCADE) data = models.DateField(null=False) descricao_manutencao = models.TextField(max_length=100, null=False) comprovante_manutencao = models.ImageField(upload_to='comprovantes/manutenções/', null=False) def __str__(self): return f"{self.veiculo} - Data: {self.data}" error: SystemCheckError: System check identified some issues: ERRORS: sistema_gerenciamento.Manutencao.comprovante_manutencao: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". Django doesn't find the pillow even though it was installed correctly, any tips on how I can solve this problem? -
msgpack.exceptions.ExtraData When Receiving Messages Deserialization Error in Django Channels on AWS:
I am developing a web application with Django and Django Channels, and I have encountered an issue while handling WebSocket consumer reception events. When receiving messages from the client, the application throws a deserialization error: msgpack.exceptions.ExtraData: unpack(b) received extra data. Context: Frameworks and Versions: I am using an environment deployed via AWS Beanstalk with Linux 2023, Django (version 4.2.6), Django Channels (version 4.0.0), Channels-redis (version 4.1.0). We have a load balancer to redirect traffic to a WSGI server (port 8000 where everything works as expected), and wss traffic to an ASGI server (Daphne) for asynchronous management. Security groups are configured correctly and allow traffic as expected. Elastic Redis cache service has been enabled and it works correctly (we persist and retrieve information without issues). Initially, for the CHANNEL_LAYERS backend, I had selected channels_redis.core.RedisChannelLayer, but the connection was not persistent (the client connected and disconnected within a second), which was resolved by selecting channels_redis.pubsub.RedisPubSubChannelLayer. Channels Backend: I have configured Django Channels to use Redis as the channels backend, CHANNEL_LAYERS in my settings.py I also include my current consumer code, asgi and complete traceback Expected Behavior: I expected the consumer to process incoming messages without issues, but there seems to be an … -
django get all values in many instances?
I have a problem. products = Producto.objects.all() data = products[per_page * page: per_page * (page + 1)] And I want to get all the data from the instance, con ForeignKey and "normal" values. Example: product = <Queryset[[prod_id: 1, name: "Ferrari 1"]. [prod_id: 12, name: "Playstation 5"] [prod_id: 5, name: "Soap"]]> and in the end, what I need is something like this to be parsed to JSON and send it: [[prod_id: "Car", name: "Ferrari 1"]. [prod_id: "Console", name: "Playstation 5"] [prod_id: "Clean Acc", name: "Soap"]] -
Error while using django_countries module
I have a model as below class Person1(models.Model): name = models.CharField(max_length = 20,null = True) country = CountryField() def __str__(self): return self.name while I'm trying to add value to the model fields it is showing the error AttributeError: 'BlankChoiceIterator' object has no attribute '__len__' Is there any issue with new version of django Here the problem is with the country field -
CSRF verification failed. Request aborted . im trying to send data from AJAX to views.py but it's showing this error
registration.html <form method="POST" id="someForm"> {% csrf_token %} <label for="name">Name:</label> <input type="text" id="name" name="name" required /> <label for="email">Email:</label> <input type="email" id="email" name="email" required /> <label for="password">Password:</label> <input type="password" id="password" name="password" required /> <input type="submit" value="Register" name="createuser" /> </form> </div> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> let URLd = "{% url 'defaultpg' %}"; let nameInput = document.getElementById("name"); let emailInput = document.getElementById("email"); let passwordInput = document.getElementById("password"); const someForm = document.getElementById("someForm"); someForm.addEventListener("submit", (e) => { e.preventDefault(); // prevent default behavior of the form var csrfToken = $("input[name='csrfmiddlewaretoken']").val(); let nameValue = nameInput.value; let emailValue = emailInput.value; let passwordValue = passwordInput.value; let isNameValid = /^[a-zA-Z]+$/.test(nameValue); let isEmailValid = /^\S+@\S+\.\S+$/.test(emailValue); let isPasswordValid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test( passwordValue ); if (isNameValid && isEmailValid && isPasswordValid) { alert("Successful"); $.ajax({ type: "POST", url: /defaultpg/, headers: { "X-CSRFToken": csrfToken }, data: { name: nameValue, email: emailValue, password: passwordValue, csrfmiddlewaretoken: csrfToken, }, dataType: "json", success: function (data) { // Handle success response alert("Successful msg"); }, error: function () { // Handle error response alert("Failure"); }, }); } else { // Handle validation errors if (!isNameValid) { alert("Please enter a valid Name"); } else if (!isEmailValid) { alert("Please enter a valid Email Address"); } else { alert( "Password must contain letters, capital letter, small letter, special character, … -
Add users to group based on OAuth2 Role - Microsoft Azure AD - social-auth-app-django
I'm trying to use Django-Social-Auth to login to Django. I have the OAuth workflow working and I can login, but I am not part of any groups and have no permissions.. My Azure AD app has various roles configured that are mapped to AD groups.. How can I map the users role to a Django group and in turn give permissions? If I need to create a custom pipeline function, thats fine, but I cant find any reference to access the roles. Thanks. -
Is there a production ready code template to deploy a django app to aws?
I'm looking for a production-ready approach to deploy django apps to aws. The approach must be in a automated fashion and needs minimal changes when deploying for a new app. For example, let's say I have a todo list app. Now I want to deploy it to aws. I will need terraform to create the required infrastructures, and then some way to configure these infrastructure and deploy the django app there. What I want is next time when I have another app - say a blog app, I just need to change a couple of things and use the same approach I used last time to have it deployed. I have checked out a few tutorial online but none of them quite captured what I'm looking for. Using terraform for infrastructure provisioning is the norm, however for deploying django on AWS I see there are a couple of approaches. I'm not an expert in AWS so I just want something with minimal overhead and maximum reproducibility Please help me find such a template. This would help me tremendously in deploying django apps. -
Docker image not working after rebuild with same dependencies
Docker image not working after rebuild with same dependencies. probably related to xmlsec. Same versions for python, nginx, gunicorn, python3saml, xmlsec etc. rebuild and checked that all dependencies are the same. they are the same. Container is running in azure, but problem is reproduced locally. -
Site Can't be reached while creating server on Flask
The VSC terminal says that the server is running on 127.0.0.1:5000 But when I Go there.. It says site couldn't be reached.. Please solve this problem.. Same problem persists while creating a server from Django I asked chatgpt but couldn't find any good solutions . -
Django multiple annotation for one Case-When
I'm currently trying to annotate multiple value with the same When in a Case for a Django QuerySet. Currently I have something like this: my_qs.annotate( dynamic_status_deadfish=Case( when_inactive, when_only_recently_published, when_no_published_ad, when_not_enough_booking, when_low_booking_cnt, default=default, output_field=HStoreField(), ) ) with one of those when looking like this: when_inactive = When( is_active=False, then={"status": stats_cts.INACTIVE, "reason": None}, ) when_only_recently_published = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then={ "status": stats_cts.PENDING, "reason": OwnerStatsStatusReason.RECENTLY_SUSPENDED, }, ) when_no_published_ad = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=False), then={ "status": stats_cts.PENDING, "reason": OwnerStatsStatusReason.NO_BOOKABLE_TO_MODERATE, }, ) As you can see my output is a dict, or more exactly an Hstore. Ideally, I'd like one distinct annotation for status and for reason so that I don't have to deal with serialization and have an easier access to the annotation than with this HSTore One way would be to duplicate the when for status and reason as the condition are the same, but I don't like it. Something like this: when_only_recently_published = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then=Value(stats_cts.PENDING), ) when_only_recently_published_reason = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then=Value(OwnerStatsStatusReason.RECENTLY_SUSPENDED), ) ... my_qs.annotate( dynamic_status_deadfish=Case( when_inactive, when_only_recently_published, when_no_published_ad, when_not_enough_booking, when_low_booking_cnt, default=default, ), dynamic_status_deadfish_reason=Case( when_inactive_reason, when_only_recently_published_reason, when_no_published_ad_reason, when_not_enough_booking_reason, when_low_booking_cnt_reason, default=default_reason, ) ) Any way to somehow set two annotations in a Case or something similar ? -
django search a value in multiple fields
There is a way to search a determinated value inside of N fields? (Without have to get all the db to filter it with for in) Something like this: db = id name age 1 Juan 10 2 Pedro 31 3 Laura 55 4 3_Manuel 11 search(3) => OUTPUT [[2 Pedro 31] , [4 3_Manuel 11]] search("au") => OUTPUT [[1 Juan 10]]