Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter some data in one column in table
In a Django project, I want to display values from a table in the database, provided that a filter is applied to some data in one of the columns. For example, the gender column. I want to display only female data with the rest of the columns in the table. -
How to handle constraint errors like unique or not null from DB in Django
I have a write operation which adds a record in rider model. The rider_code is unique in this. Now 1 way is to first check if any record with that rider_code exists then return error else create rider. But it requires 2 db calls when the db can return constraint error on create which would be a single call. But how to catch these constraint errors correctly in Django. This is 1 of the solutions I got but it does not seem right: def create_rider(request): serializer = RiderSerializer(data=request.data, context={"request": request}) if serializer.is_valid(): try: rider = serializer.save() return True, rider except IntegrityError as e: error_msg = str(e) if "ds_riders.ds_riders_rider_code_d4b087a9_uniq" in error_msg: return False, {"details": "Rider Code already exists."} if "application_users.username" in error_msg: return False, {"details": "Username already exists."} return False, {"details": error_msg} return False, serializer.errors` -
Django application deployement with Docker
I am trying to deploy my django app with docker. But when it come to excute my script to be sure that the databse (postgres) is ready, I allways get this error : chmod: /app/scripts/wait-for-it.sh: Permission denied and then the container stop running. This is my dockerfile : # Stage 1: Base build stage FROM python:3.13-slim AS builder # Create the app directory RUN mkdir /api # Set the working directory WORKDIR /api # Set environment variables to optimize Python ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ libpcre3-dev \ libssl-dev \ python3-dev \ libpango1.0-dev \ libcairo2-dev \ libpq-dev \ bash \ fontconfig \ fonts-dejavu-core \ fonts-droid-fallback \ fonts-freefont-ttf \ fonts-liberation \ && rm -rf /var/lib/apt/lists/* # Install dependencies first for caching benefit RUN pip install --upgrade pip RUN mkdir /requirements COPY ./requirements/. ./requirements/. RUN set -e; \ pip3 install --upgrade pip && \ pip3 install uwsgi && \ pip3 install --default-timeout=100 --no-cache-dir -r ./requirements/stage.txt # Stage 2: Production stage FROM python:3.13-slim RUN useradd -m -r -g www-data app_user && \ mkdir /api && \ chown -R app_user /api # Copy the Python dependencies from the builder stage COPY --from=builder /usr/local/lib/python3.13/site-packages/ /usr/local/lib/python3.13/site-packages/ COPY … -
Celery is not running despite correct configuration - using Django, Celery 5+, and Python 3.12+
Despite what appears to be a correct initial configuration, Celery tasks are not running. The logging system does not show any errors. This is a new setup of Celery version 5+ running on Python 3.12+. Full server-side configuration has been added. All required packages and dependencies have been installed, and the application itself does not raise any errors. What could be the reason the test Celery task is not executing every minute as scheduled, according to the interval specified in settings.py? tasks.py from celery import shared_task from datetime import datetime from .models import CeleLog @shared_task def get_all_weather_data(): now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') CeleLog.objects.create(content=f"Current time: {now}") print(f"Logged time: {now}") settings.py CELERY_BROKER_URL = 'amqp://localhost' from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'log-every-minute': { 'task': 'company_dashboard.tasks.get_all_weather_data', # <- ścieżka do funkcji 'schedule': crontab(minute='*/1'), }, } celery.py - project import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_rama.settings') app = Celery('app_rama') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) init.py - project from .celery import app as celery_app app-celery-worker.conf [program:app-celery-worker] command=/home/app/bin/celery -A app_rama worker -l INFO directory=/home/app/app user=app numprocs=1 stdout_logfile=/home/app/logs/app-rama-worker.log stderr_logfile=/home/app/logs/app-rama-worker.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 killasgroup=true priority=998 app-celery-beat.conf [program:app-celery-beat] command=/home/app/bin/celery -A app_rama beat -l INFO directory=/home/app/app user=app numprocs=1 stdout_logfile=/home/app/logs/app-rama-worker.log stderr_logfile=/home/app/logs/app-rama-worker.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 killasgroup=true priority=998 And … -
How to make DRF use url path as empty and base path?
I am trying to omit the URL path for an action in a ViewSet like @action(detail=False, methods=['patch'], url_path='') def update_current_user(self, request): But when I give url_path as an empty string, DRF defaults to the function name and looks for the route at /api/current-user/update_current_user. I want it to look at /api/current-user. How to drop the whole path for the function and use the base path? -
ImportError: Module "django_comments_xtd" does not define a "XtdComment" attribute/class
When I installed django-comments-xtd according the documention I got this error: ImportError: Module "django_comments_xtd" does not define a "XtdComment" attribute/class Configs in settings.py are: INSTALLED_APPS += [ 'django_comments_xtd', 'django_comments', 'django.contrib.sites', ] SITE_ID = 1 COMMENTS_APP = "django_comments_xtd" COMMENTS_XTD_MODEL = 'django_comments_xtd.XtdComment' COMMENTS_XTD_MAX_THREAD_LEVEL = 3 COMMENTS_XTD_CONFIRM_EMAIL = False COMMENTS_XTD_ALLOW_ANONYMOUS = True COMMENTS_XTD_ALLOW_PUBLICATION_MODERATION = True -
Django forloop in template
Forloop is overriding the other, how do I use two different forloop in one template without interrupting each other. The 'include template" do not display its contents if 'for users in all_users' is the parents. How do I make 'for users in all_users' not to override 'for post in posts'. What I tired: I tried using same context key but still not working, also tried using 'with' inside the include.html still no problem solved. def ForYouView(request): #All account users all_users = Profile.objects.exclude( Q(user=request.user)| Q(friends__user=request.user)).order_by("?") posts = Post.objects.all().order_by("?") context = { 'posts': posts, 'all_users': all_users, } #Home template {% for users in all_users %} <div>{{ users.user }}</div> {% include 'index_hover_card.html' %} <div>{{ users.user.username }}</div> {% endfor %} #Include template {% for post in posts %} <div>{{ post.poster_profile.profile.user }}</div> {% endfor %} -
ERROR: Failed to build installable wheels for some pyproject.toml based projects (mysqlclient)
Building wheel for mysqlclient (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mysqlclient (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [91 lines of output] C:\Users\Acer\AppData\Local\Temp\pip-build-env-qm2za2yg\overlay\Lib\site-packages\setuptools\config_apply_pyprojecttoml.py:82: SetuptoolsDeprecationWarning: project.license as a TOML table is deprecated !! ******************************************************************************** Please use a simple string containing a SPDX expression for `project.license`. You can also use `project.license-files`. (Both options available on setuptools>=77.0.0). By 2026-Feb-18, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license for details. ******************************************************************************** !! corresp(dist, value, root_dir) C:\Users\Acer\AppData\Local\Temp\pip-build-env-qm2za2yg\overlay\Lib\site-packages\setuptools\config\_apply_pyprojecttoml.py:61: SetuptoolsDeprecationWarning: License classifiers are deprecated. !! ******************************************************************************** Please consider removing the following classifiers in favor of a SPDX license expression: License :: OSI Approved :: GNU General Public License (GPL) See https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license for details. ******************************************************************************** !! dist._finalize_license_expression() C:\Users\Acer\AppData\Local\Temp\pip-build-env-qm2za2yg\overlay\Lib\site-packages\setuptools\dist.py:759: SetuptoolsDeprecationWarning: License classifiers are deprecated. !! ******************************************************************************** Please consider removing the following classifiers in favor of a SPDX license expression: License :: OSI Approved :: GNU General Public License (GPL) See https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license for details. ******************************************************************************** !! self._finalize_license_expression() # Options for building extension module: library_dirs: ['C:/mariadb-connector\\lib\\mariadb', 'C:/mariadb-connector\\lib'] libraries: ['kernel32', 'advapi32', 'wsock32', 'shlwapi', 'Ws2_32', 'crypt32', 'secur32', 'bcrypt', 'mariadbclient'] extra_link_args: ['/MANIFEST'] include_dirs: ['C:/mariadb-connector\\include\\mariadb', 'C:/mariadb-connector\\include'] extra_objects: [] define_macros: [('version_info', (2, 2, 4, 'final', 0)), ('__version__', '2.2.4')] … -
How can I filter values from one model and insert the result into the form as choices?
Good day! I have two tables - models. I fill them gradually. First I have the first table. First I enter data into the first table. And there - in the first table I have - repeating data. Field - (name_object) - is repeated and can have the same rows. Also even more repeated field - name_working. I plan to include filtered values (name_working) in the second form. How can I filter values in the model table - CreateNewGPR by - (name_object) - which is like pk . And insert the received data into the form as select or choices . models.py class CreateNewGPR (models.Model): name_object = models.IntegerField(verbose_name="Наименование объекта") name_working = models.CharField(verbose_name="Наименование работы") type_izm = models.CharField(choices=TYPE_IZMERENIYA, verbose_name="Единицы измерения") value_work = models.FloatField(verbose_name="Объём работ") lyudi_norma = models.IntegerField(verbose_name="Нормативные затраты персонала") technik_norma = models.IntegerField(verbose_name="Нормативные затраты техники") date_begin = models.DateField(verbose_name="Дата начала работ") date_end = models.DateField(verbose_name="Дата окончания работ") class CreateNewWorkDay (models.Model): name_object = models.IntegerField(verbose_name="Наименование объекта") name_working = models.CharField(verbose_name="Наименование работы по ГПР") second_name_working = models.CharField(verbose_name="Фактическое наименование работы") third_name_working = models.TextField(verbose_name="Описание работы") type_izm = models.CharField(choices=TYPE_IZMERENIYA, verbose_name="Единицы измерения") value_work_fact = models.FloatField(verbose_name="Объём работ фактический") lyudi_norma = models.IntegerField(verbose_name="Нормативные затраты персонала") technik_norma = models.IntegerField(verbose_name="Нормативные затраты техники") lyudi_fact = models.IntegerField(verbose_name="Фактические затраты персонала") technik_fact = models.IntegerField(verbose_name="Фактические затраты техники") date_day = models.DateField(verbose_name="Дата") forms.py class FormOne … -
Elasticsearch search only by one field
I have app on drf and i added elasticsearch(django_elasticsearch_dsl) for searching. But i faced with problem, when i want to search on two or more fields, elastic searching only by one field. I'm trying to search by both 'title' and 'description', but it only searches in the 'title' field. Django model class Product(TimestampMixin, HistoricalModel, models.Model): class Status(models.TextChoices): NEW = 'new', _('New') USED = 'used', _('Used') class PublicationStatus(models.TextChoices): ACTIVE = 'active', _('Active') INACTIVE = 'inactive', _('Inactive') DRAFT = 'draft', _('Draft') # Очікуючі REJECTED = 'rejected', _('Rejected') # Відхилені SOLD = 'sold', _('Sold') DELETED = 'deleted', _('Deleted') title = models.CharField(_('Product name'), max_length=255) description = models.TextField( verbose_name=_('Product description'), validators=[ MinLengthValidator(settings.MIN_LENGTH_DESCRIPTION, message=_('Product description is too short')), MaxLengthValidator(settings.MAX_LENGTH_DESCRIPTION, message=_('Product description is too long')), ], ) ... Document @registry.register_document class ProductDocument(Document): title = fields.TextField(analyzer="multilang_analyzer") description = fields.TextField(analyzer="multilang_analyzer") class Index: name = "products" settings = { 'number_of_shards': 1, 'number_of_replicas': 1, 'analysis': { 'analyzer': { 'multilang_analyzer': { 'type': 'custom', 'tokenizer': 'standard', 'char_filter': ['html_strip'], 'filter': [ 'lowercase', 'russian_stop', 'ukrainian_stop', 'english_stop', 'russian_stemmer', 'english_stemmer' ] } }, 'filter': { 'russian_stop': {'type': 'stop', 'stopwords': '_russian_'}, 'ukrainian_stop': {'type': 'stop', 'stopwords': '_ukrainian_'}, 'english_stop': {'type': 'stop', 'stopwords': '_english_'}, 'russian_stemmer': {'type': 'stemmer', 'language': 'russian'}, 'english_stemmer': {'type': 'stemmer', 'language': 'english'} } } } class Django: model = … -
Javascript-Django: add atribute to signup form
I am working on a signup form in Javascript within a Django project. I have the following script: <div class="form-row"> <div class="col-md-6"> <div class="form-group"> <label class="large mb-1">First Name</label> {{ form.first_name }} </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="large mb-1">Last Name</label> {{ form.last_name }} </div> </div> </div> At this point I would like to add another input, e.g. phone number. So I was trying a wild guess such as: <div class="form-group"> <label class="large mb-1">Phone</label> {{ form.phone }} </div> But obviously it doesn't work. Any suggestion? Thank you! -
Why are we seeing incorrect timings in Datadog APM tracing for simple actions like a Redis GET?
We have Python Django application deployed to AWS EKS on EC2 instances. We use Gunicorn as our web server, although we recently ran Apache + wsgi and saw the same issues. The EC2 instances are m6a.xlarges, the containers themselves have 1500m CPU and 2048MB memory. We use Datadog APM tracing and we're tracking Redis calls. Occasionally we'll see a slow request, and when we look deeper we'll see in the trace a simple Redis GET query take 2.8 seconds! I've used Redis for years and I've never had a problem with it. It's lightening fast. And our platform produces very little load (CPU is around 2% on a small instance). I enabled slow logging in ElastiCache and we're seeing no results, so I know it isn't the Redis instance itself. What could be causing this? I know the timings in APM are based on ddtrace's own in-Python timings, so maybe our Python processes are getting bogged down somehow? CPU usage on the EC2 instances in general is very low, 10% tops. Memory usage is also low. I'm at a loss. We don't have over allocation, so I don't think it's that. -
Deploying Django + xlwings library
I'm trying to deploy a Django app which uses the xlwings dependency (windows only) on a server. Tried on Linux, but it does not support xlwings. So, now looking out for an easy way to set up the Deployment with Windows instead. Until now, I've really only been using PaaS offerings for deployment which did the work for me. Would appreciate it if somebody could describe the general approach (preferably on Azure) for making such a deployment as easy as possible. I've tried looking around various threads and google, but I fear this is not a common requirement. Thank you! -
How can I create a table or form with the addition of values from another table based on the selected values?
Good day! I have several model tables. And each subsequent table in the conditional hierarchy is one step lower than the previous one. I have one model that is planned to be filled from the form in the database. And I plan to create another table that will be filled based on the data from the first model. I plan to select an element from the form in the list - the first field and based on the selected value in the first field --->>> --->>> accordingly copy some values of the corresponding fields from the corresponding row of the model table. When selecting a certain field, take values from other fields of the same row and send them to another table of the model. Send them to another table of the model with the addition of other data. Conventionally speaking, this is like reproducing the first table into several. The second table can have 20 times more rows than the first. How can I create a table or form with the addition of values from another table based on the selected values? class CreateNewGPR (models.Model): name_object = models.IntegerField(verbose_name="Наименование объекта") name_working = models.CharField(verbose_name="Наименование работы") type_izm = models.CharField(choices=TYPE_IZMERENIYA, verbose_name="Единицы измерения") value_work … -
Can I use my DjangoCMS template in my AppHook application?
Context: I am trying to integrate an application in my djangocms website. As i want it seems totally integrated, i want my appHooked application to use the same template as my main DjangoCMS template (I am using an extends of djangocms-frontend/bootstrap5) Everything seemed OK, until my first POST. Problem: When i just go to an URL of my AppHook everything is fine. But if, inside a view, i try to redirect to another page of this same AppHook, the response is put inside an iframe, so i get my header, footer and menu doubled. You can see it on the screenshot.As it does not happen if i click on a link, this problems seems to be only on POST response. Am i wronf trying to use the same template ? Can we make an actual app, with post and response, to looks like it is a content on the CMS page ? To be clear : I would hope to continue to see the menu and footer when i am on my AppHooked application. Here is a bit of my code : ---- main_app(djangocms)/template/base.html --- {% extends "bootstrap5/base.html" %} [...] {% block content %} {% placeholder "Page Content" %} {% … -
Cloudinary image upload isssu with python, Django and DRF
I am trying to upload my produts image to cloudinay, I setting all thing correctly adding middleware but always my image saevd in locally -
How to update removed model choices in Django without breaking existing database values?
I'm working on a Django project where we use models.TextChoices for fields like current_status. Our client requested wording updates — for example, renaming "Contacted" to "Contacted for assessment", "Booked" to "Assessment booked", and so on. Previous Enum: class ClientStatus(models.TextChoices): CONTACTED = "Contacted" BOOKED = "Booked" Updated Enum: class ClientStatus(models.TextChoices): CONTACTED_FOR_ASSESSMENT = "Contacted for assessment", "Contacted for assessment" ASSESSMENT_BOOKED = "Assessment booked", "Assessment booked" Problem We already have hundreds of users in the database with: current_status = 'Contacted' Since "Contacted" no longer exists in the model choices: Will migrations fail or behave unexpectedly? Will the Django Admin or API views break when encountering these legacy values? What is the correct way to rename choice values without leaving inconsistent data? Constraints We want to avoid creating unnecessary migrations. We want this to work for all environments (dev/staging/production). We'd prefer not to break the Admin panel or serializers. Question What is the safest and most Django-idiomatic way to rename or remove enum values when old data already exists in the database? Is it okay to do manual SQL updates? Or is there a recommended Django migration approach? What I've Tried Ran python manage.py makemigrations and migrate. Migration did not fail. Admin view throws … -
React doesn’t receive API tokens after Google OAuth redirect via social_django/drf-social-oauth2
I'm implementing Google OAuth2 for my Django REST API with a React frontend. The basic flow is set up correctly. I have routes for: urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/", include((v1_patterns, "v1"))), path("api/v1/auth/", include("social_django.urls", namespace="social")), path("api/v1/auth/token/", include("drf_social_oauth2.urls", namespace="oauth2")), ] Also I have: INSTALLED_APPS = [ ... "drf_yasg", "social_django", "oauth2_provider", "drf_social_oauth2", ... ] SOCIAL_AUTH_URL_NAMESPACE = "social" AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "social_core.backends.google.GoogleOAuth2", "drf_social_oauth2.backends.DjangoOAuth2", ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config("GOOGLE_OAUTH_CLIENT_ID") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config("GOOGLE_OAUTH_CLIENT_SECRET") SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ["email", "profile"] SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_DATA = [ "email", "first_name", "last_name", "picture", ] LOGIN_REDIRECT_URL = "http://127.0.0.1:5173" # REST Framework general settings REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "drf_social_oauth2.authentication.SocialAuthentication", ) } For login, I sent a GET request from browser to http://localhost:8000/api/v1/auth/login/google-oauth2/ After sending the request, in the console I get: api_container | [24/Jun/2025 13:04:19] "GET /api/v1/auth/login/google-oauth2/ HTTP/1.1" 302 0 api_container | [24/Jun/2025 13:04:20] "GET /api/v1/auth/complete/google-oauth2/?state=KYTUm5yi1NheUmc095zaRqIc3mZjsOLp&code=4%2F0AUJR-x4dcWMTghJHjPc1QbiPrCFo5lo2u9l1cYJ47F61fB0kIkQe4I0DFAt33UZOPBBI8g&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&authuser=0&prompt=none HTTP/1.1" 302 0 After a successful login, I get redirected to my React app (127.0.0.1:5173) — but the problem is, no tokens (access or refresh) are passed to the client. I don’t know how to retrieve or send them so that React can authenticate future API calls. I can confirm that after login, the database records email, picture, first_name, last_name, and an access token (from Google), but React … -
How can I load values into the form from the desired table row by clicking?
Good day! I plan to build a mini application. Which consists of one page (the main one) - a template. And also one secondary page - on the second page I fill in information into the model table through a form. On the other page (the main one) - I display information in the form of a table. I plan to place the form next to the table. The most difficult thing is that in this form I would like to receive data and write/send data from a specific table row. For example, I click on an element in a table row and information appears in the form - the contents of this row that I clicked or pressed. Information appears loaded in the form, values from the table row - which can then be edited and the data can be written back into the table model. Can you think of something about this? I would be very grateful for any tips and help. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>title</title> </head> <body> <div> <h4>Мероприятия</h4> </div> <br/> <div> <form method="GET" action="{% url 'table' %}"> {{ form.as_p }} <input type="submit" value="Submit" class="button" /> </form> </div> <br/> <div> <table style="font-family: Arial, … -
How to display a friend request button on each post?
I'm trying to make each post from all users have a friend request button for each specific user who uploaded post on homepage. This code below is what I have tried but friend request button is not displayed on each post. I have also tried using a boolean field but still same problem. What could I have been doing wrong? class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True) caption = models.TextField(blank=True, null=True) class FriendRequest(models.Model): from_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='from_user') to_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='to_user') def ForYouView(request): page_title = "For You" poster_profile = Post.objects.all() all_profile_users = [] button_status_list = [] for user_obj in p: u = user_obj.user all_profile_users.append(u) # sent_friend_requests = FriendRequest.objects.filter(from_user=u) # rec_friend_requests = FriendRequest.objects.filter(to_user=u) friends = Profile.objects.filter(user=request.user, friends__id=user_obj.id).exists() button_status = 'none' if not friends: button_status = 'not_friend' if len(FriendRequest.objects.filter( from_user=request.user).filter(to_user=u)) == 1: button_status = 'cancel_request_sent' if len(FriendRequest.objects.filter( from_user=u).filter(to_user=request.user)) == 1: button_status = 'follow_back_request' button_status_list.append(button_status) context = { 'page_title': page_title, 'poster_profile': poster_profile, 'profile_and_button_status': zip(p,button_status_list), 'u': all_profile_users, } return render(request, 'foryou.html', context) {% if poster_profile %} {% for user in poster_profile %} <div>{{ user.poster_profile }}</div> {% if not user == request.user %} {% for user in profile_and_button_status %} {% if user.1 == 'not_friend' %} <a href="" class="friend-request"> <button type="button" class="btn"> … -
I have this while running django
error faced (venv) PS C:\Users\Personal\Desktop\Onblu_VW1_API\api_vw1> python manage.py makemigrations Traceback (most recent call last): File "C:\Users\Personal\Desktop\Onblu_VW1_API\api_vw1\manage.py", line 22, in <module> main() File "C:\Users\Personal\Desktop\Onblu_VW1_API\api_vw1\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Personal\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 991, in exec_module File "<frozen importlib._bootstrap_external>", line 1129, in get_code File "<frozen importlib._bootstrap_external>", line 1059, in source_to_code File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed SyntaxError: source code string cannot contain null bytes -
How to send OTP to Gmail using Django Rest Framework? [closed]
I'm trying to implement an OTP verification system using Django Rest Framework (DRF). The goal is to send a 6-digit OTP to the user's Gmail address during registration or login. Here's what I've done so far: Generated a random 6-digit OTP using Python. -
How to pass pk to form (ForeignKey) and views - from template when following link?
How to pass pk to the form (ForeignKey) and views - from the template when clicking on a link? Good day! I have a model. Which is displayed in the template. And the transition to another template is configured by a link. But my form is not displayed there. I also wanted to ask how I can pass (pk) to the form in order to enter data only for the object by which the transition was made by the link? I click on the link and get to a specific object. I wanted to fill in its properties through the form. How can I fill in specifically for the object by (pk) that I clicked on the link to the view and form? For some reason, my form is not displayed. class ArkiObject_1 (models.Model): city = models.CharField(choices=TYPE_CITY, verbose_name="Городской округ") nameobject = models.TextField(verbose_name="Наименование объекта") typeobject = models.CharField(choices=TYPE_OBJECT, verbose_name="Тип объекта") param_1 = models.FloatField(verbose_name="Мощность котельной, МВт") param_2 = models.FloatField(verbose_name="Диаметры трубопроводов, мм") def __str__(self): return self.nameobject class ArkiGpr (models.Model): name = models.ForeignKey(ArkiObject_1, on_delete=models.CASCADE) work = models.TextField(verbose_name="Наименование работы") peoples = models.IntegerField(verbose_name="Количество людей") --- class FormOne (forms.ModelForm): class Meta: model = ArkiObject_1 fields = "__all__" class Form_GPR (forms.ModelForm): class Meta: model = ArkiGpr fields = "__all__" … -
Best practice to create a django user connected to a stripe customer
I'm trying to create a simple website for selling a digital good. Frontend is html/js, backend is django (using allauth, with simple email registration and a Custom User model) and I'm using stripe to handle payments. I've implemented a checkout workflow where a (anonymous) user can order via the hosted stripe checkout. However in order to properly handle the user's access to the digital goods, I need to somehow sync the stripe customer to a django user. The workflow, respectively best practice for this is unclear to me. Should I create a checkout session for the anonymous user and then use the stripe webhook confirmation to create a user (maybe sending the user a login link)? (What if the email has a typo?) Should I create a local user first, then via strip API a stripe customer (mapping the id as meta-data) and include the customer_id in the checkout? (seems clunky with multiple steps for the user, when they don't have an account yet) Something else from the stripe API (PaymentIntent)? ...? What are best practices for this? What are advantages / disadvantages of the respective approaches? I'm aware that this is a bit vague and will depend on the … -
Routing Problem from sign in page to a users account
The Issues is routing a user after creating an account on the webapp platform to the users dashboard created for the user. I can provide with the sign in and authcontext.js page which helps with this. signin.js import React, { useState, useEffect } from 'react'; import { Link, useNavigate, useLocation } from 'react-router-dom'; import { useAuth } from '../../../contexts/AuthContext'; import './Login.css'; const Login = () => { const [formData, setFormData] = useState({ email: '', password: '' }); const [error, setError] = useState(''); const [loading, setLoading] = useState(false); const { login, isAuthenticated } = useAuth(); const navigate = useNavigate(); const location = useLocation(); // Redirect if already logged in useEffect(() => { if (isAuthenticated) { const from = location.state?.from?.pathname || '/'; navigate(from, { replace: true }); } }, [isAuthenticated, navigate, location]); const handleChange = (e) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); // Clear error when user starts typing if (error) setError(''); }; const handleSubmit = async (e) => { e.preventDefault(); setError(''); setLoading(true); try { const { email, password } = formData; const result = await login(email, password); if (result.success) { // Redirect to the dashboard or previous page const from = …