Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to retrieve Authjs (NextAuth 5) access token server-side in Next.js 15 with Django backend
I'm trying to set up authentication in my Next.js application using NextAuth.js with a Django backend. As Oauth provider i'm use django-oauth-toolkit. The goal is to pass the access token in the Authorization header when making requests to the Django API. I have successfully set up the OAuth2 provider in Auth.js, and I'm able to log in through the Django authentication system. However, when I try to retrieve the access token server-side in my Next.js app (in a server component), I am unable to find it. I try to follow the official tutorial for thirdy parts backends: https://github.com/nextauthjs/next-auth-example I'm using NextJS 15.1.7 and Authjs (NextAuth.js v5) Here’s the relevant code: src\auth.ts import NextAuth from "next-auth" import "next-auth/jwt" declare module "next-auth" { interface Session { accessToken?: string } } declare module "next-auth/jwt" { interface JWT { accessToken?: string } } const DJANGO_URL = process.env.NEXT_PUBLIC_DJANGO_URL; const NEXTJS_URL = process.env.NEXT_PUBLIC_NEXTJS_URL; export const { handlers, auth, signIn, signOut } = NextAuth({ providers: [{ id: "django", // signIn("my-provider") and will be part of the callback URL name: "Django", // optional, used on the default login page as the button text. type: "oauth", // or "oauth" for OAuth 2 providers userinfo: `${DJANGO_URL}/api/o/userinfo/`, token: `${DJANGO_URL}/api/o/token/`, wellKnown: `${DJANGO_URL}/api/o/.well-known/openid-configuration/`, … -
django-allauth MFA cannot add Webauthn security key
Im trying to setup django-allauth's MFA for my system and successfully got the authenticator app to work. I am using the default templates and when I tried adding a security key, it is not working and outputs "(Hidden field credential) This field is required." in the form. here is my settings.py setup: ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False MFA_ADAPTER = "allauth.mfa.adapter.DefaultMFAAdapter" MFA_PASSKEY_SIGNUP_ENABLED = True MFA_SUPPORTED_TYPES = ["recovery_codes", "totp", "webauthn"] MFA_WEBAUTHN_ALLOW_INSECURE_ORIGIN = True MFA_PASSKEY_LOGIN_ENABLED = True -
if condition with field value don't work in Django template
In models I have: class Book(models.Model): status = models.ForeignKey( 'BookStatus', verbose_name='Status', on_delete=models.RESTRICT, null=True, blank=True, ) and class BookStatus(models.Model): name = models.CharField( max_length=50, unique=True, ) def __str__(self): """String for representing the Model object.""" return self.name In views I have a normal Model DetailView: class BookDetailView(LoginRequiredMixin, generic.DetailView): login_url = '/accounts/login/' model = Book In the template for this detail view I want to display a button only, if book.status is not "vorhanden". I try with this: {% if book.status != 'vorhanden' %} ... {% endif %} but this is also true, if the displayed book has status = vorhanden. I tried the reverse: {% if book.status == 'vorhanden' %} ... {% endif %} but this is not true, even if the displayed book has status = vorhanden What is my mistake? Thanks in advance Matthias -
Get table changes details without using triggers in postgres
I am working on a live dashboard which records changes in database and shows details related to it on the dashboard. Currently to get these live changes I am using a combination of triggers, functions and pg_notify to generate notifications from postgres when some tables have CRUD operations in them. All of this is working okay for now, but based on some suggestions I read online many people do not recommend to use triggers if it is possible, as they are hard to maintain and don't sit best with rest of our code base. So for this reason I want to try updating my trigger based approach with something which fits with my code better and easier to maintain. But I don't know what I can use instead of triggers to get live changes from database. Most triggers in my database are just used to send postgres notification back to my backend where I am handling the changes directly, so if I can get the changes from the database without using triggers I think I can make it work, but I can't figure out how to do so. Also, if you think that trigger based approach is better for my … -
How to fix CSRFToken headers and CORS issues in React + Django website
I have an application running with react as the frontend and django as the backend. When I use an online hosting service, I get the following issues: TypeError: NetworkError when attempting to fetch resource. AuthContext.js:37:14 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/\_allauth/browser/v1/auth/session. (Reason: header ‘x-csrftoken’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/\_allauth/browser/v1/auth/session. (Reason: CORS request did not succeed). Status code: (null). and, Access to fetch at 'http://localhost/_allauth/browser/v1/auth/session' from origin 'https://privatevoti.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.Understand this errorAI allauth.js:128 GET http://localhost/_allauth/browser/v1/auth/session net::ERR_FAILED f @ allauth.js:128 (anonymous) @ allauth.js:259 (anonymous) @ AuthContext.js:32 rs @ react-dom.production.min.js:243 ku @ react-dom.production.min.js:285 (anonymous) @ react-dom.production.min.js:281 k @ scheduler.production.min.js:13 R @ scheduler.production.min.js:14Understand this errorAI AuthContext.js:33 TypeError: Failed to fetch at f (allauth.js:128:22) at allauth.js:259:16 at AuthContext.js:32:5 at rs (react-dom.production.min.js:243:332) at ku (react-dom.production.min.js:285:111) at react-dom.production.min.js:281:391 at k (scheduler.production.min.js:13:203) at MessagePort.R (scheduler.production.min.js:14:128) (anonymous) @ AuthContext.js:33 Promise.catch (anonymous) @ AuthContext.js:32 rs @ react-dom.production.min.js:243 … -
Buffer channels when there are no consumers
When a channel has no consumers, can I get django to buffer all the messages sent on the channel instead, then after a consumer subscribes can I get it to send all the buffered messages again (to that consumer)? I think I can do it manually with very ugly solutions, involving four global variables and bespoke consumers, but does django provide an easier way to do it? -
Django Bokeh Stacked Bar Chart
I have the following queryset: <QuerySet [ {'Order_Type': 'Phone', 'Order_Priority': 'NA', 'Order_total': 2}, {'Order_Type': 'Web', 'Order_Priority': 'High', 'Order_total': 3}, {'Order_Type': 'Web', 'Order_Priority': 'Med', 'Order_total': 9}]> I want to create a stacked bar chart using Bokeh that shows the total number of orders for each order type; each bar will also show the breakdown order priority (see image). enter image description here I'm getting an error because the axis categorical factors (Order Type in this case) is not unique. can someone help me with this? -
How to log all errors related to an API request in Django Rest Framework along with multiple fields in a CSV file?
I want to log any type of error that occurs during an API request in Django Rest Framework into a CSV file, including the error message along with additional details like username, user ip, url, etc. I also want to capture errors that occur before reaching the view (e.g., errors related to JWT). I tried using middleware for this, but the issue was that some responses were not rendered correctly, and even after manually rendering, they still resulted in errors. I would appreciate it if you could suggest a solution. The code below is the middleware I tried to use. I don't have an issue with logging errors that occur inside the view because if I only wanted to log errors within the view, I could use decorators or create a custom APIView. However, what I'm looking for is a way to log any type of error, even those that occur outside the view. class ErrorLogMiddleware: def __init__(self, get_response): self.get_response = get_response self.filename = settings.ERROR_LOG_PATH self.fieldnames = ["Username", "IP", "User Agent", "Date/Time", "Time Interval", "Query", "Message", "URL"] def __call__(self, request): if not exists(self.filename): with open(self.filename, "a", newline="", encoding="utf-8") as csvfile: writer = DictWriter(csvfile, fieldnames=self.fieldnames) writer.writeheader() before = time() try: response … -
How to add a function result from a model to a list?
How to add a function result from a model to a list 'subdom()' models.py class Hromady(models.Model): ... def subdom(self): if self.alias: sub = self.alias else: sub = self.code.lower() return sub views.py def index(request): hromads = Hromady.objects.all() for hr in hromads: print(hr.subdom()) # ok hrom = hromads.annotate(obj_count=Count('object', filter=Q(object__state=1))) map_hrom = list(hrom.values('region', 'district', 'locality', 'type', *****subdom()*****???, 'obj_count')) -
Django re_path to catch all URLs except /admin/ not working properly
I'm trying to define a re_path in Django that catches all URLs except those that start with /admin/. My goal is to redirect unknown URLs to a custom view (RedirectView), while ensuring that all admin URLs (including subpaths like /admin/mymodel/something/) are excluded. from django.urls import re_path, path from django.contrib import admin from . import views urlpatterns = [ path('admin/', admin.site.urls), # Ensure Django admin URLs are handled ] # Catch-all pattern that should exclude /admin/ URLs urlpatterns += [ re_path(r"^.*/(?!admin/$)[^/]+/$", views.RedirectView.as_view(), name="my-view"), ] Issue: URLs like localhost:8000/admin/mymodel/something/ are correctly ignored, which is good. However, single-segment URLs like localhost:8000/something/ are not being matched, even though they should be redirected. -
Django 5 translate route with param
I have troubles to translate properly a route that needs a param. this works fine if the uri has /fr/ or /en/: urlpatterns = [ path(_('CATEGORY'), views.category, name='app-category'), ] But as long as I need to add a param like: urlpatterns = [ path(f"{_('CATEGORY')}/<slug:uuid>", views.category, name='app-category'), ] or urlpatterns = [ path(_('CATEGORY') + "/<slug:uuid>", views.category, name='app-category'), ] The translation stuck with 'category' so the route /fr/categorie/ is not working. _('CATEGORY') = 'categorie' for fr or 'category' for en. Any idea about how to bypass the issue? Thanks -
How to reset specific container child tags from tailwind styles
I am using tailwindcss in django project. Tailwind css by default reset all tags default styles. I am creating a blog page. The blog content is created with ckeditor. I am using {{content|safe}} to load the content as html. The issue arise here. The content default tag styles are not showing so the content is not showing as expected. I have tried with row css to unset the tailwind resets. .reset-default * { all: unset; box-sizing: border-box; } .reset-default p, .reset-default a, .reset-default button { all: unset; } .reset-default a { text-decoration: initial; color: initial; } .reset-default button { background: initial; border: initial; } .btn-custom { padding: 10px 20px; background-color: #3490dc; color: white; border-radius: 5px; } But it didn't work, so I tried with a tailwind css plugin, @tailwindcss/typography. I added prose class in the parent and the styles are added. But for the newlines it also taking margins for blank lines. Is there any way to reset the tags to default. -
Traceback not provided after upgrading to Django 5
I upgraded my django 4.1 to django 5.1.3, and sometimes the admin error emails are coming without traceback. Here is part of the email: Internal Server Error: /go Report at /go Internal Server Error: /go Request Method: GET Request URL: https://[domain]/whatever Django Version: 5.1.3 Python Executable: /usr/local/bin/python3.11 Python Version: 3.11.10 Python Path: ['/app', '/app', '/usr/local/bin', '/usr/local/lib/python311.zip', '/usr/local/lib/python3.11', '/usr/local/lib/python3.11/lib-dynload', '/usr/local/lib/python3.11/site-packages'] Server time: Tue, 11 Feb 2025 08:04:21 -0500 Installed Applications: [long list] Traceback (most recent call last): None Request information: USER: demo GET: POST: No POST data FILES: No FILES data The server doesnt show anything special, just a Internal Server Error. Memory is good and cpu also. -
ModuleNotFoundError: No module named ‘mysite’
I’m working on a python virtual environment: Python 3.13.1 Django 5.1.6 At this moment without apps, just the project. I’m trying to start the project with “runserver”, or I try to run makemigrations, or I try to run migrate, and I get this message: ModuleNotFoundError: No module named ‘mysite’ I’ve searched in my settings file, even in wsgi file and I see everything well. I’ve searched on Internet a lot of forums without success. I changed Django version, without success, the same message. I’ve created a lot of projects and I get this message for first time. I checked if there is something with "mysite" declared. -
Can we make a python script that can detect and identify person height weight from an image?
I tried someones Git but the results are not that good as the sample images provided by him is also not giving accurate results. I want a script in python that takes an image path, scan that image and look for a person in that image, gives back height and weight of person. I know that can't be 100% accurate but it should be 90+ correct. Input - Sample Image Output - Height: 117.8 cm, Weight: 68.6 kg Input - Sample Image2 Output - Height: 170.8 cm, Weight: 77.12 kg -
Django-allauth change password not working
first time poster be gentle. I have created a project using allauth with the documentation including adding bootstrap elements. My login/logout/sign up pages all work but when I do change or forgotten password I get a confirmation saying password is changed successfully but only the old password still works. I even span up a fresh project with nothing else added such as custom user etc and this still happens and I can't figure out why it doesn't work out if the box. Any ideas? -
Django migrations wont work..OperationalError at /admin/blog/comment/ no such column: blog_comment.description
Apply all migrations: blog Running migrations: Applying blog.0002_alter_comment_description_alter_reply_description...Traceback (most recent call last): File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return super().execute(query, params) sqlite3.OperationalError: no such table: blog_reply The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/chandansblog/manage.py", line 22, in <module> main() File "/home/chandansblog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 356, in handle post_migrate_state = executor.migrate( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/migrations/migration.py", line 132, in apply operation.database_forwards( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 235, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 175, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 831, in alter_field self._alter_field( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 463, in _alter_field self._remake_table(model, alter_fields=[(old_field, new_field)]) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 336, in _remake_table self.execute( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 201, in execute cursor.execute(sql, … -
create a profile record when creating a user in Django
I'm trying to solve this error: TypeError: Profile.save() got an unexpected keyword argument 'force_insert' signals.py from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from .models import Profile @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() model.py class Profile(models.Model): # Managed fields user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) memberId = models.CharField(unique=True, max_length=15, null=False, blank=False, default=GenerateFA) The objective is to create a profile record when a user is created. Appreciate any wisdom on this. -
Generate html to pdf using xhtml2pdf in django project
I have an HTML page containing multiple tables. When converting it to a PDF using xhtml2pdf, it works fine if only a few tables are expanded. However, if I expand more tables, I run into a size limitation where the PDF turns out blank if the content exceeds a certain size(30Mb). Views.py def generate_pdf(request): template_path = 'app.html' context = { 'data': 'This is dynamic data passed to the template' } pdf_stylesheets = """ <style> @page { size: A4 landscape; margin: 1.5cm; } .table-wrapper { width: 100%; } table { width: 100%; border-collapse: collapse; table-layout: fixed !important; } thead { display: table-header-group; } tbody { page-break-inside: avoid !important; break-inside: avoid !important; } tr { page-break-inside: avoid !important; break-inside: avoid !important; } td { padding: 8px; border: 1px solid #ddd; font-size: 14px; vertical-align: top; } /* Column widths */ td:nth-child(1) { width: 10%; } td:nth-child(2) { width: 15%; } td:nth-child(3) { width: 10%; } td:nth-child(4) { width: 45%; max-width: 45%; word-wrap: break-word !important; word-break: break-word !important; overflow-wrap: break-word !important; white-space: pre-wrap !important; } td:nth-child(5) { width: 20%; } .message-cell { position: relative; max-width: 45%; word-wrap: break-word !important; word-break: break-word !important; overflow-wrap: break-word !important; white-space: pre-wrap !important; } .message-content { display: inline-block; width: … -
Accessing MEDIA_URL & trailing slash redirect
In order to access {{ MEDIA_URL }} from templates, I added + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urlpatterns. Recently I noticed that this breaks the default APPEND_SLASH functionality in Django. I.e. I get a 404 when the trailing is missing, unless I remove + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) from urlpatterns, in which case it correctly redirects to the URL with the trailing slash. I think I'm missing something fundamental, because it seems to me that accessing MEDIA_URL from templates is a basic requirement to display media correctly, without breaking other basic functions in Django. -
Custom GraphQL String Field Parameter
I'm required to sanitize all my inputs coming in via the GraphQL endpoint and remove potential malicious stuff (No the Django build-in mechanism are not enough, it shall be actively removed). As I do not want to add the sanitization for every mutation manually, I thought about creating a custom graphene.String() class called clean_string.String() including nh3.clean() for the sanitization so I must only exchange singe lines: import graphene import nh3 from graphql import StringValueNode, Undefined class String(graphene.String): @classmethod def parse_value(cls, value): if isinstance(value, str): cleaned_value = nh3.clean(value) else: cleaned_value = value return super(String, cls).parse_value(cleaned_value) @staticmethod def parse_literal(ast, _variables=None): if isinstance(ast, StringValueNode): return nh3.clean(ast.value) return Undefined In my schema.py I have then import clean_string class CreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: email = clean_string.String(required=True) password = clean_string.String(required=True) @staticmethod def mutate(_, info, email, password) # sanitized email & password But this does not get called at all. When I have inputs like <img>password</img> and do the sanitation manually the result will be <img>password but with my custom class nothing happens. Does anyone have a clue how to resolve this? Thanks in advance! -
Django url path not routing properly
NoReverseMatch at /post/comment/1 Reverse for 'comment-reply' with arguments '('',)' not found. 1 pattern(s) tried: ['post/comment/reply/(?P<pk>[0-9]+)\\Z'] path('post/<slug:slug>/comment/create', CommentCreate.as_view(), name='post-comment'), path('post/comment/reply/<int:pk>', ReplyCreate.as_view(), name='comment-reply'), path('post/comment/<int:pk>', CommentDetailView.as_view(), name='comment-detail'), class ReplyCreate(LoginRequiredMixin, CreateView): """ Form for adding a blog comment. Requires login. """ model = Reply fields = ['description',] def get_context_data(self, **kwargs): """ Add associated blog to form template so can display its title in HTML. """ # Call the base implementation first to get a context context = super(ReplyCreate, self).get_context_data(**kwargs) # Get the blog from id and add it to the context context['comment'] = get_object_or_404(Comment2, pk = self.kwargs['pk']) return context def form_valid(self, form): """ Add author and associated blog to form data before setting it as valid (so it is saved to model) """ #Add logged-in user as author of comment form.instance.author = self.request.user #Associate comment with blog based on passed id form.instance.comment=get_object_or_404(Comment2, pk = self.kwargs['pk']) # Call super-class form validation behaviour return super(ReplyCreate, self).form_valid(form) def get_success_url(self): """ After posting comment return to associated blog. """ return reverse('detail2', kwargs={'slug': self.kwargs['slug'],}) class CommentDetailView(LoginRequiredMixin,generic.DetailView): model = Comment2 comment2_detault.html: {% extends 'blog/basedetail.html' %} {% block content %} <div class="card mb-3"> <div class="card-body"> <div class="card-title fw-bold">{{ comment.author }} | ({{ comment.post_date }})</div> <p class="card-text">{{ comment.description }}</p> </div> </div> <div … -
Creating long polling requests in django or fastapi
I wanted to build long polling requests in django or fastapi. I want to use redis for it. I will listen to some key in redis. and when something updates i will return changed result as soon as some change happens in my db to client. But my server accepts many requests at the same time. Is there any way to build non blocking version of it? -
Switching from WSGI to ASGI (Gunicorn + Uvicorn) in Django Production – Site Not Loading
I recently built a Django application using Django Channels for WebSocket support. My asgi.py is set up for handling both HTTP and WebSocket connections, and everything works perfectly in development using Daphne and Uvicorn. In Productin initially, my app was running on Gunicorn (WSGI), but since I need WebSocket support, I switched to Uvicorn (ASGI). To achieve this, I modified my gunicorn.service file to use UvicornWorker instead of the default WSGI worker. I encountered the error: Django can only handle ASGI/HTTP connections, not lifespan. To fix this, I created a custom worker class based on a solution from older Stack Overflow answers: from uvicorn.workers import UvicornWorker class MyUvicornWorker(UvicornWorker): CONFIG_KWARGS = {"lifespan": "off"} Then, I updated my gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=django Group=www-data WorkingDirectory=/home/django/my_project ExecStart=/home/django/my_project/venv/bin/gunicorn \ --limit-request-line 8190 \ --access-logfile /var/log/gunicorn/access.log \ --error-logfile /var/log/gunicorn/error.log \ -k project.uvicorn_worker.MyUvicornWorker \ --workers 3 \ --env DJANGO_SETTINGS_MODULE=project.settings.base \ --bind unix:/run/gunicorn.sock \ --log-level=debug \ project.asgi:application ExecReload=/bin/kill -HUP $MAINPID [Install] WantedBy=multi-user.target After restarting gunicorn.service, everything appears to be running fine, gunicorn.service and nginx.service are active ping mysite.com is working No errors in /var/log/gunicorn/error.log -
Django: Migrations not detecting changes after manually deleting migration files in production app
What happened: I had an app called app with migrations up to 0012. I mistakenly deleted migration files, including 0001_initial.py. Now, when I run python manage.py makemigrations app, no new migration files are detected, even though I have made changes to the models. This issue is persisting even in a newly created app called comments, where no migration files are being detected either, despite having added new fields to the models. What I’ve tried: I’ve ensured that the app is listed in INSTALLED_APPS. I’ve run python manage.py makemigrations app to generate migration files, but no changes are detected. I can’t drop the database as it is a production environment, and I need to preserve existing posts and data. What I need help with: I need to figure out how to properly reset or re-sync the migrations without losing any production data. For now i have empty migrations folder with init.py innit that doesnt create any migration file. Specifically, how do I: Recreate missing migrations after deleting files manually (i.e., to match the state of the database, which still has migrations applied up to 0012). Ensure that any new apps or changes to models are correctly detected and have corresponding migration …