Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST framework gives me csrf token missing when i am logged in for POST requests
i am making an API with django rest framework and django 5.2 when i send a POST request, if i be logged in it gives me an CSRF token missing error. but if i be logged out it gives me response with no error. here are my views for handling user creation and authentication: @api_view(['POST']) def signup_view(request): if not request.user.is_authenticated: serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({"detail": "The user is already logged in."}, status=status.HTTP_403_FORBIDDEN) @api_view(['POST']) def login_view(request): if not request.user.is_authenticated: user = authenticate(**request.data) print(request.POST) if not user: return Response({"detail": "User authentication failed."}, status=status.HTTP_400_BAD_REQUEST) login(request, user) return Response({"detail": "Login was succesful."}) return Response({"detail": "The user is already logged in."}, status=status.HTTP_403_FORBIDDEN) and here are my views for handling get and post method for the model: class NoteListView(APIView): def get(self, request): notes = Note.objects.filter(author=request.user) serializer = NoteSerializer(notes, many=True) data = [] for note in serializer.data: data.append({'title': note['title']}) return Response(data) def post(self, request): serializer = NoteSerializer(data=request.data) serializer.initial_data['author'] = request.user print("1") if serializer.is_valid(): print("2") serializer.save() print("3") return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) now i want to know what i have to do for fixing the csrf missing error in this situation. -
error: "get" is not a known attribute of "None" (reportOptionalMemberAccess)
I use PyRight to check my Django code. It complains about that class FooForm(ModelForm): def clean(self): cleaned_data = super().clean() start = cleaned_data.get("start_date") # <------- here error: "get" is not a known attribute of "None" (reportOptionalMemberAccess) I installed django-stubs. How to make PyRight aware that cleaned_data is a dictionary? Or is something wrong with my setup? -
Django 1.5.1: diagnose and fix Report
I've been handed a rather old Django installation to support, with the specific request to re-enable a report that used to go out every week or so, but stopped showing up a few months ago. Django v 1.5.1 Python 2.7.3 Ubuntu 12.04 (yikes) Problem is - I'm totally new to Django. I'm not sure where this report might be coming from, or how to troubleshoot it, or how to configure it. I was going to try the Admin pages; I finally was able to get my IP on the allow-list, and can bring up the login for that page, but I'm not sure what a valid user/PW is for this system. Where are the Django 'Admin' users kept? I'm able to access the MySQL DB backend itself - but the user-table for MySQL itself doesn't appear to be the source for the Django Admin users. So I would guess they are stored in a table in the Django eco-system... I'd like to just add a new user for myself, so I can log in and poke around in Admin. I have reviewed some Django documentation, but not seeming to find the answers to my questions, for either setting/administering users, nor … -
How to handle feature and permission-based authorization in Next.js without delaying initial render?
I’m building a multi-tenant SaaS application with Django Ninja as the backend and Next.js as the frontend. I’m running into a problem around handling RBAC permissions and org-level feature entitlements without causing bad UI behaviour. Current setup The app has a pre-defined set of permissions and features. Each organization can: Create their own RBAC roles for members. Define their own plans (feature bundles) for members. Hierarchy looks like: Platform → Org → Members. Problem For RBAC, I first tried fetching permissions/features from an API after login. But in Next.js, this caused a UX issue: On initial render, the UI displayed all components/features. Only after the API call resolved (or a manual refresh), the UI updated to hide restricted components. This led to a flicker effect where users briefly saw components they shouldn’t. To avoid this for RBAC, I moved the permissions into the JWT, so the frontend can instantly check them at page load. This works well, but I’m unsure if I should do the same for feature entitlements (since those are org-level and can change dynamically). Question Is it acceptable to also put feature entitlements in the JWT (and refresh the token on org/plan changes)? Or is there a … -
Patterns for testing web API permissions
I am working on a cookie cutter JSON web API. Think /items/<id> with your typical CRUD of delete, patch, get, and post. Recently, we started rolling out a new permissions model for the API, where certain operations are forbidden based on a combination of user and object properties. For example: We have two types of items - normal items and locked items, and we have two type of users - regular users and admin users. Users belong to a company. Regular users can mutate any normal item that belongs to their company, but not locked items Admin users can mutate any item (normal or locked) in their company. So the matrix for testing looks something like this: Test that regular users can do full CRUD on normal items in their company Test that regular users can get but not mutate locked items in their company Test that regular users can not do any CRUD on items not in their company Test that admin users can do full CRUD on normal items in their company Test that admin users can do full CRUD on locked items in their company Test that admin users can not do any CRUD on items not … -
Django 'join' tabels
I have 3 Tabels in Django class Transactions(models.Model): public_key = models.ForeignKey(Keys, on_delete=models.CASCADE) txid = models.CharField(max_length=30) timestamp = models.DateTimeField() hash = models.CharField(max_length=64) block = models.IntegerField() amount = models.IntegerField() saldo = models.IntegerField() fee = models.IntegerField() fiat_CHF = models.FloatField(default=0) fiat_USD = models.FloatField(default=0) fiat_EUR = models.FloatField(default=0) position = models.IntegerField(default=0) class Price(models.Model): date = models.DateTimeField() price = models.FloatField() fiat = models.ForeignKey(Currencies, on_delete=models.DO_NOTHING) class PriceTextBackup(models.Model): date = models.CharField(max_length=20) price = models.FloatField() fiat = models.ForeignKey(Currencies, on_delete=models.DO_NOTHING) This is from a Bitcoin App, the Transaction Table contains the exact time when transaction was mined. Now I want to load the stored bitcoin price for that day for example the transaction may have a timestamp of 2000-01-01 12:10:10 and the price 2000-01-01 so i want to join or link them. It doesn't have to be in database. I did something similar in a diffrent page to calculate the average price, i load both tables and 'join' them. In the end I want to display the transaction with a price. this price can come from price, pricetextbackup or be 0. Can this be achived and how? -
Django join where values not null
I have 3 Tabels in Django class Transactions(models.Model): public_key = models.ForeignKey(Keys, on_delete=models.CASCADE) txid = models.CharField(max_length=30) timestamp = models.DateTimeField() hash = models.CharField(max_length=64) block = models.IntegerField() amount = models.IntegerField() saldo = models.IntegerField() fee = models.IntegerField() fiat_CHF = models.FloatField(default=0) fiat_USD = models.FloatField(default=0) fiat_EUR = models.FloatField(default=0) position = models.IntegerField(default=0) class Price(models.Model): date = models.DateTimeField() price = models.FloatField() fiat = models.ForeignKey(Currencies, on_delete=models.DO_NOTHING) class PriceTextBackup(models.Model): date = models.CharField(max_length=20) price = models.FloatField() fiat = models.ForeignKey(Currencies, on_delete=models.DO_NOTHING) Now i want to 'join' transactions with price on the date, if it is null i want to check the text backup, if it is still null, i want it to be 0. Is that possible? and how? -
so many terminal messages when starting django runserver
when I start python manage.py runserver I get many messages similar to the following. File C:\Users\PC\OneDrive\Documents\DoseSaaS\DoseV3MasterSaaS\templates\admin\dose\tenant\change_list.html first seen with mtime 1754471094.0 to the point it fills the terminal window. How do I stop this? Could not find anything in the project and co-pilot could not help. checked settings.py and found nothing I could find. I looked for external services like watchdog but didn't find anything obvious. -
Django: How to customize the reset password URL with a custom email template?
I am stuck with somewhat similar situation. It sends default email and not the custom email. Hence the in reset password the URL is the API endpoint url and not the url to the UI. I am using React.js in the frontend. Sending: http://localhost:8000/api/auth/password/reset/confirm/{uidb64}/{token} Correct url: https://my-domain.com/password-reset/confirm/{uidb64}/{token} .env BASE_URL=https://my-domain.com settings.py REST_AUTH = { 'PASSWORD_RESET_CONFIRM_URL': env('BASE_URL')+'/password-reset/confirm/{uidb64}/{token}', 'PASSWORD_RESET_SERIALIZER': 'users.serializers.CustomPasswordResetSerializer', } urls.py from django.urls import path, re_path from .views import ( CustomPasswordResetView ) from dj_rest_auth.views import LogoutView, PasswordResetConfirmView, PasswordResetView urlpatterns = [ path('password/reset/', CustomPasswordResetView.as_view(), name='rest_password_reset'), path('password/reset/confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] views.py class CustomPasswordResetView(PasswordResetView): serializer_class = CustomPasswordResetSerializer serializers.py class CustomPasswordResetSerializer(DjRestAuthPasswordResetSerializer): def get_email_options(self): return { 'email_template_name': 'registration/password_reset_email.html', 'extra_email_context': { 'password_reset_url': settings.REST_AUTH['PASSWORD_RESET_CONFIRM_URL'], } } password_reset_email.html # failed to test both styles of URL <a href="{{ password_reset_url }}">{{ password_reset_url }}</a> <a href="{{ base_url }}/password-reset/confirm/{{ uid }}/{{ token }}">{{ base_url }}/password-reset/confirm/{{ uid }}/{{ token }}</a> Python 3.11.2 django-sslserver 0.22 djangorestframework 3.15.2 dnspython 2.7.0 ipython 8.12.3 mysql-connector-python 9.1.0 opencv-python 4.10.0.84 python-dateutil 2.9.0.post0 python-dotenv 1.0.1 python-jose 3.5.0 python-multipart 0.0.20 I am unable to specify a custom url. How can I achieve the following: when user receives an email to reset password, they should have the React.js UI opened upon clicking the desired correct url with custom email template as described above. … -
Show the text from a Json file in Django template
I am starting learn django,I have made some basic templates/views and want to show the text from a json file located in the assets/jsons folder.The file is called "quotes.json" The content of the json file: { "emp_details": [ { "emp_name": "johnny", "email": "example1.mail@gmail.com", "job_profile": "intern" }, { "emp_name": "gustav", "email": "gustav.empl@gmail.com", "job_profile": "developer" }, { "emp_name": "emily", "email": "emily@gmail.com", "job_profile": "Full Time" } ] } here is the views.py: from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth import get_user_model #from . import models def homepage(request): ##here is where I want to have the json data ##and return it in the render along with the request and 'homepage.html' return render(request,'homepage.html') def about(request): return render(request,'about.html') def users(request): User = get_user_model() users = User.objects.all() return render(request,'users.html',{'users':users}) here is the homepage.html ,the layout.html has css and some navigation buttons it is irrelevant. I literally only want the contents of the json to be shown as text in the homepage. {% extends 'layout.html' %} {% block title %} Home {% endblock %} {% block content %} {% load static %} {% load static %} <script type="text/javascript"> console.log(json1_data); </script> <h1>Home</h1> <h1><p>Welcome {{request.user}}</p></h1> <p>Check out my <a href="/about">About</a> page.</p> <p id="demo"> </p> {% endblock %} … -
Django cannot register oauth2_provider and rest_framework to INSTALLED_APPS
I am working on this weekend project, to learn Django and I am stuck. Before adding the REST framework (one to last commit in the repo), everything was working just alright. Once I added the djangorestframework library, everything fell apart. Now, whether you run the app on a venv or on DOcker, you will get the same result: RuntimeError: Model class oauth2_provider.models.Application doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. ... or a similar one related to rest_framework's Token. Both libraries are installed. I understand the problem is that something is wrong with INSTALLED_APPS. But... WHAT?! The docs make me think I am not doing anything wrong. If you look at the imports, from rest_framework etc etc and from oauth2_provider etc etc seem to be the problem. Error logs and stack traces are quite useless, there is not useful info in there. Your help will be much appreciated. -
Managing Django groups and permissions for custom users
For my Django projects, I am used to creating a custom user model and managing what my user can do for a specific route using a roles field like this: class User(AbstractBaseUser, PermissionsMixin): name = models.CharField("full name", max_length=255, blank=True) email = models.EmailField("email address", unique=True) createdAt = models.DateField(auto_now_add=True) photo = models.ImageField( "profile photo", blank=True, null=True, validators=[ FileExtensionValidator(allowed_extensions=["jpg", "png", "jpeg"]) ], ) # by default retrieves file from media root role = models.CharField( max_length=50, choices=[(role.value, role.name) for role in USER_ROLES], ) is_active = models.BooleanField(default=True) USERNAME_FIELD = "email" objects: CustomUserManager = CustomUserManager() def has_perm(self, perm, obj=None): if self.role == USER_ROLES.ADMIN.value: return True return super().has_perm(perm, obj) def has_module_perms(self, app_label): if self.role == USER_ROLES.ADMIN.value: return True return super().has_module_perms(app_label) @property def is_staff(self): return self.role == USER_ROLES.ADMIN.value @property def is_superuser(self): return self.role == USER_ROLES.ADMIN.value def __str__(self) -> str: return f"{self.pk}-{self.email}" But I realize that it’s best to shift to a multi-role approach for flexibility and I was hoping to use the built-in Group and Permissions model for this. However, I was confused as to how to handle the groups and permissions for each user inside a view/API route and sync any changes in groups and permissions later on if needed. Can anyone suggest an efficient way of … -
Stripe webhooks not firing in Django app during normal checkout flow
I'm integrating Stripe with my Django app (using Django REST Framework). I've set it up to accept POSTs, and when I use the Stripe CLI to trigger events, everything works perfectly. Example Stripe CLI command: stripe listen --forward-to localhost:8000/webhooks/api/v1/stripe-webhook/ When I run commands like stripe trigger checkout.session.completed I see the events in my server logs and my Django view is hit as expected: [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ price.created [evt_1R] [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ charge.succeeded [evt_1R] [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ payment_intent.succeeded [evt_1R] [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ checkout.session.completed [evt_1R] [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ payment_intent.created [evt_1R] [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ But when I go through my actual frontend flow (create a Checkout Session from my app, complete the payment in test mode, etc.), no webhooks are received at all. I see nothing in my Django logs. Nothing is received on my webhook endpoint. I also see no attempts or errors in the Stripe Dashboard's "Webhooks" section. Things I have tried: Registering both URLs in the Stripe Dashboard webhook settings. I am using test mode and test credentials. Stripe CLI and triggers work perfectly. Summary: Stripe CLI triggers work, real Stripe events from live app flow do not. No webhooks reach my server in normal payment flow, but do when … -
Django connection_created signal is causing problems when testing
In my django application I have a list of notification types and I want to allow customers to subscribe to one or more notification types. Each notification type has somewhat of a custom logic so the code of each notification has to be in a different class but I have created a singleton class that gathers all the notification type names and other metadata like description etc. I want to have a list in the database of all the supported notification types so that the relationship between customers and notification types can be stored in the database while customers subscribe to notification types. I want to have a notification type table so that I can store the metadata and a separate table to store the many-to-many relationship between customers and notifications. That is where connection_created signal comes in. I have created the following signal that creates the notification type items in the database when the connection_created signal is received so they get auto-updated when I am changing the code: from django.db.backends.signals import connection_created from django.db.backends.postgresql.base import DatabaseWrapper from django.dispatch import receiver from notification_type_singleton import NotificationTypeSingleton from models import NotificationType @receiver(connection_created, sender=DatabaseWrapper) def create_or_update_notification_type(sender, **kwargs): exiting_ids = [] for _, notification_type … -
535, b'5.7.139 Authentication unsuccessful, basic authentication is disabled
I have a website that uses an email contact form. Recently been told it does not work. When I recreated the error in development I got the error 535, b'5.7.139 Authentication unsuccessful, basic authentication is disabled. I read online that basic authentication has been switched off by Microsoft. I am unsure how to resolve this. Is there a new way to authenticate? I cannot find anything that will allow a user to provide these simple details to send an email to our inbox. I am using Django and the following code that did work before. html = render_to_string('emails/contact_form.html', { 'first_name': first_name, 'last_name': last_name, 'email': email, 'content': content }) send_mail('Message', content, EMAIL_HOST_USER, [EMAIL_HOST_USER], html_message=html) -
Stripe: "No signatures found matching the expected signature for payload" using Django Rest Framework and request.body
I'm integrating Stripe webhooks into my API, which is built with Django Rest Framework (DRF). Here’s my webhook view: class StripeWebhookView(APIView): permission_classes = [AllowAny] # Public webhook def post(self, request, *args, **kwargs): payload = request.body sig_header = request.headers.get('stripe-signature') try: event = stripe.Webhook.construct_event( payload=payload, sig_header=sig_header, secret=settings.STRIPE_SIGNING_SECRET ) except ValueError as e: print(f"Invalid payload: {e}") return Response(status=status.HTTP_400_BAD_REQUEST) except stripe.error.SignatureVerificationError as e: print(f"Signature verification failed: {e}") return Response(status=status.HTTP_400_BAD_REQUEST) # ... webhook logic ... return Response(status=200) I get: [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 Invalid signature: No signatures found matching the expected signature for payload Bad Request: /webhooks/stripe-webhook/ [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 400 0 I’ve already double-checked that my STRIPE_SIGNING_SECRET is correct, and my endpoint is set up correctly in the Stripe dashboard. I am using request.body directly (not request.data), as suggested in other answers, but the error persists. Has anyone successfully used Stripe webhooks with Django Rest Framework and managed to pass signature verification? I have carefully read and tried all the solutions mentioned in this post I am using request.body (not request.data) … -
Using list which depends on another list in excel using python
I have a requirement to create dependent dropdowns in excel using python. import os import openpyxl from openpyxl.styles import Border, Side, PatternFill, Font, Alignment, numbers from openpyxl.worksheet.datavalidation import DataValidation from openpyxl.workbook.defined_name import DefinedName def create_dynamic_excel_bytes(sheets_config, file_name): wb = openpyxl.Workbook() ws_hidden = wb.create_sheet("Hidden") hidden_col = 1 path_url = "/home/downloads/dravoka-downloadexcel/" file_path = os.path.join(path_url, file_name) # ✅ Add global EmptyRange placeholder empty_col_letter = openpyxl.utils.get_column_letter(hidden_col + 100) ws_hidden.cell(row=1, column=hidden_col + 100, value="") wb.defined_names.add( DefinedName("EmptyRange", attr_text=f"Hidden!${empty_col_letter}$1") ) for sheet_idx, sheet_conf in enumerate(sheets_config): if sheet_idx == 0: ws = wb.active ws.title = sheet_conf["sheet_name"] else: ws = wb.create_sheet(sheet_conf["sheet_name"]) columns = sheet_conf["columns"] num_rows = sheet_conf.get("num_rows", 100) # Create border style border = Border( left=Side(border_style="thin"), right=Side(border_style="thin"), top=Side(border_style="thin"), bottom=Side(border_style="thin"), ) # Create header style header_fill = PatternFill(start_color="475E75", end_color="475E75", fill_type="solid") header_font = Font(bold=True, color="FFFFFF") # White color header_alignment = Alignment(horizontal="center", vertical="center") for col_idx, col in enumerate(columns, start=1): cell = ws.cell(row=1, column=col_idx, value=col["header"]) cell.fill = header_fill cell.font = header_font cell.alignment = header_alignment cell.border = border for col_idx, col in enumerate(columns, start=1): col_letter = openpyxl.utils.get_column_letter(col_idx) if col["type"] == "dropdown": for i, val in enumerate(col["dropdown_values"], start=1): ws_hidden.cell(row=i, column=hidden_col, value=val) range_name = f"{sheet_conf['sheet_name']}_{col['header']}".replace(" ", "_") range_ref = ( f"Hidden!${openpyxl.utils.get_column_letter(hidden_col)}$1:" f"${openpyxl.utils.get_column_letter(hidden_col)}${len(col['dropdown_values'])}" ) wb.defined_names.add(DefinedName(name=range_name, attr_text=range_ref)) dv = DataValidation(type="list", formula1=f"={range_name}", allow_blank=True) ws.add_data_validation(dv) for row in range(2, num_rows + … -
JsonField in Django Admin as Inline
I have a JsonField in my Model, its structure is a dict. class MyModel: final_result = models.JSONField() But it's pretty big, and it's hard to edit it with any JSON widget. So I thought, that maybe I need to parse/split it to several 'custom' fields. jsonfield = { "key1": "value1", "key2": "value2", "key3": [ {"inner_key_1": "inner_value_1", "inner_key_2": "inner_value_2", etc} ] } Given this JSON data, I would like to have fields: key1, key2 (which is easy), and here's the problem - key3, which is list of dicts. Can I somehow display them like Inlines? With fields - inner_key_1, inner_key_2 (etc) So I can edit each element of list delete element with button add another element with preset fields When I try to use inlines - it says it needs a model, but I don't have a model for this json. Proxy models and abstract models give errors. Forms, formsets (AI recommendations) don't work too. I tried using inlines, forms, formsets, with a help from AI)) -
Trying to do Selenium testing in Django in Docker getting ERR_CONNECTION_REFUSED
I am trying to get Selenium testing going in Docker with Django. But I keep getting ERR_CONNECTION_REFUSED when using the live_server_url. I have tried to use django's container with f"http://django:{self.port}{reverse('account_login')}" I have also tried to use the ip address of the django container, but that doesn't work either. The selenium portion of the docker compose file is from https://github.com/SeleniumHQ/docker-selenium/blob/trunk/docker-compose-v3.yml docker compose file services: django: container_name: django_dev env_file: - ../environments/example.env image: &django django build: context: .. dockerfile: docker_development/Dockerfile command: python manage.py runserver 0.0.0.0:8006 volumes: - ../site:/code ports: - "8006:8006" depends_on: - db celery: container_name: celery_dev image: *django restart: 'no' entrypoint: celery -A project worker --beat --scheduler django --loglevel=info volumes: - ../site:/code env_file: - ../environments/example.env depends_on: - db - rabbitmq3 - django db: command: postgres container_name: devdb image: postgres:17 restart: 'no' #always env_file: - ../environments/example.env ports: - "5432:5432" volumes: - postgres-data:/var/lib/postgresql/data rabbitmq3: container_name: "rabbitmq_dev" image: rabbitmq:3-management-alpine env_file: - ../environments/example.env ports: - "5672:5672" - "15672:15672" chrome: image: selenium/node-chrome:4.35.0-20250808 platform: linux/amd64 shm_size: 2gb depends_on: - selenium-hub environment: - SE_EVENT_BUS_HOST=selenium-hub edge: image: selenium/node-edge:4.35.0-20250808 platform: linux/amd64 shm_size: 2gb depends_on: - selenium-hub environment: - SE_EVENT_BUS_HOST=selenium-hub firefox: image: selenium/node-firefox:4.35.0-20250808 shm_size: 2gb depends_on: - selenium-hub environment: - SE_EVENT_BUS_HOST=selenium-hub selenium-hub: image: selenium/hub:4.35.0-20250808 container_name: selenium-hub ports: - "4442:4442" - "4443:4443" - … -
'RegisterSerializer' object has no attribute '_has_phone_field'
dj-rest-auth library has been returning this error when I send a request into the /registration endpoint from rest_framework import serializers from dj_rest_auth.registration.serializers import RegisterSerializer class RegSerializer(RegisterSerializer): phone = serializers.CharField(required = False) def get_cleaned_data(self): data= super().get_cleaned_data() data['phone']=self.validated_data.get("phone","") return data Error message: AttributeError at /auth/dj-rest-auth/registration/ 'RegisterSerializer' object has no attribute '_has_phone_field' Error location: C:\...\site-packages\allauth\account\adapter.py, line 338, in save_user which points to this.. def save_user(self, request, user, form, commit=True): from .utils import user_email, user_field, user_username data = form.cleaned_data first_name = data.get("first_name") last_name = data.get("last_name") email = data.get("email") username = data.get("username") user_email(user, email) user_username(user, username) if first_name: user_field(user, "first_name", first_name) if last_name: user_field(user, "last_name", last_name) if "password1" in data: user.set_password(data["password1"]) elif "password" in data: user.set_password(data["password"]) else: user.set_unusable_password() self.populate_username(request, user) if commit: user.save() if form._has_phone_field: phone = form.cleaned_data.get("phone") if phone: self.set_phone(user, phone, False) return user Tried to extend the RegisterSerializer that exists in the package, still didn't work, I followed the docs thoroughly but the issue persists, I don't see where the problem lies. -
Django REST API endpoints URL paths
I have a Django 4.2 app with Postgres DB and REST API. My urls.py contains this path in urlpatterns: path('create/<int:pk>/<str:name>/', ComponentCreate.as_view(), name='create-component') ComponentCreate in views.py relates to a simple DB table (component) with id as integer primary key and name as the only other column. views.py has: class ComponentCreate(generics.CreateAPIView): queryset = Component.objects.all(), serializer_class = ComponentSerializer lookup_field = "id" models.py has: class Component(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = True db_table = 'component' serializers.py has: class ComponentSerializer(serializers.ModelSerializer): id = serializers.IntegerField() name = serializers.CharField() class Meta: model = Component fields = ('id', 'name') I am trying to use the API to add a row to the component table using e.g. as below (where app is called SystemTestDB): curl -X POST http://127.0.0.1:8000/SystemTestDB/create/2/whatever/ However this fails with response: {"id":["This field is required."],"name":["This field is required."]} I have other endpoints which do work correctly e.g. with path: path('delete/<int:pk>/', ComponentDelete.as_view(), name='delete-component') In that case evidently id is being passed via int:pk, whilst in the failing case neither id nor name are set in the Request. Have I set the URL path incorrectly, or is there something wrong with model/view/serializer ? -
Deploy a dockerized monorepo to Railway
I'm trying to deploy my dockerized monorepo (Django & Next.js) project to Railway but I keep failing. My folder structure railway.tom [build] builder = "dockerfile" # Frontend service [services.frontend] builder = "dockerfile" rootDirectory = "client" # Backend service [services.backend] builder = "dockerfile" rootDirectory = "services/properties" I keep getting this error from Railway: Dockerfile Dockerfile does not exist -
DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread
I'm having the following issue, when I try to execute my Django tests: /Users/myUser/Desktop/myProject-py/src/project/project/billing_v2/tests/test_accounting_integration_heading.py::AccountingIntegrationHeadingAPITests::test_create_accounting_integration_heading failed with error: Test failed with exception request = <SubRequest '_django_setup_unittest' for <TestCaseFunction test_makemigrations_command>> django_db_blocker = <pytest_django.plugin._DatabaseBlocker object at 0x10602ae80> @pytest.fixture(autouse=True, scope="class") def _django_setup_unittest( request, django_db_blocker: "_DatabaseBlocker", ) -> Generator[None, None, None]: """Setup a django unittest, internal to pytest-django.""" if not django_settings_is_configured() or not is_django_unittest(request): yield return # Fix/patch pytest. # Before pytest 5.4: https://github.com/pytest-dev/pytest/issues/5991 # After pytest 5.4: https://github.com/pytest-dev/pytest-django/issues/824 from _pytest.unittest import TestCaseFunction original_runtest = TestCaseFunction.runtest def non_debugging_runtest(self) -> None: self._testcase(result=self) try: TestCaseFunction.runtest = non_debugging_runtest # type: ignore[assignment] > request.getfixturevalue("django_db_setup") .venv/lib/python3.8/site-packages/pytest_django/plugin.py:490: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.8/site-packages/pytest_django/fixtures.py:122: in django_db_setup db_cfg = setup_databases( .venv/lib/python3.8/site-packages/django/test/utils.py:179: in setup_databases connection.creation.create_test_db( .venv/lib/python3.8/site-packages/django/db/backends/base/creation.py:59: in create_test_db self.connection.close() .venv/lib/python3.8/site-packages/django/utils/asyncio.py:33: in inner return func(*args, **kwargs) .venv/lib/python3.8/site-packages/django/db/backends/base/base.py:285: in close self.validate_thread_sharing() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
How to execute a multi-statement Snowflake SQL script (DECLARE, DDL, DML, CASE) from Python with parameters and fetch SELECT results?
I’m new to Python and Snowflake’s scripting blocks. I want to keep a multi-statement Snowflake SQL script in a .sql file and execute it from Python with parameters. The script may include DECLARE, DDL, DML, CASE logic — basically SP-like behavior — and I want to capture any SELECT result sets if present. Example script (simplified): BEGIN -- Declare a variable using Snowflake scripting DECLARE v_admin STRING DEFAULT :admin_user; -- Create a temporary table CREATE TEMP TABLE temp_data ( tenant STRING, client STRING, user_id STRING, use_mm STRING, access_level STRING ); -- Two inserts INSERT INTO temp_data (tenant, client, user_id, use_mm, access_level) VALUES ('101', '202', 'admin_user', 'true', NULL), ('102', '203', 'guest_user', 'false', NULL); -- CASE update using the declared variable UPDATE temp_data SET access_level = CASE WHEN use_mm = 'true' AND user_id = v_admin THEN 'full' WHEN use_mm = 'true' THEN 'limited' ELSE 'none' END; -- Return results SELECT * FROM temp_data; END; What I need: Execute the file from Python, bind parameters (e.g., admin_user), and support multiple statements. If the script contains one or more SELECTs, fetch results (ideally the last SELECT); otherwise just execute. Keep temp tables ephemeral (session-scoped). Questions: Can I achieve stored-procedure-like behavior by keeping the SQL … -
InlineKeyboardButton with callback_data doesn't work
InlineKeyboardButton with callback_data doesn't work. When I click on it, nothing happens. Here is how I create the button: from django.apps import apps from asgiref.sync import sync_to_async from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo from telegram.ext import CommandHandler, ApplicationBuilder, MessageHandler, filters, CallbackQueryHandler async def start(self, update: Update, context): keyboard = InlineKeyboardMarkup([ [InlineKeyboardButton("Already registred", callback_data="already_registered")], [InlineKeyboardButton("Register", web_app=WebAppInfo(url=WEB_APP_URL))] ]) await update.message.reply_text( "Welcome", reply_markup=keyboard ) return This is the callback query handler: async def button(self, update: Update, context): query = update.callback_query if not query: return await query.answer() if query.data == "already_registered": await context.bot.send_message( chat_id=update.message.chat_id, text='Good' ) return and this is how I run: def run(self): TOKEN = apps.get_model('app.Config').objects.get_mailing_tg_bot_token() app = ApplicationBuilder().token(TOKEN).build() app.add_handler(CommandHandler('start', self.start)) app.add_handler(CallbackQueryHandler(self.button))