Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I fix IntegrityError?
I'm learning Django, and I have the following error IntegrityError at /admin/book/book/add/ (1048, "Column 'publication_date' cannot be null") My models are constructed like this from django.db import models class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() def __str__(self): return self.name class Meta: ordering = ['name'] class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() def __str__(self): return u'%s %s' % (self.first_name, self.last_name) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete = models.CASCADE) publication_date = models.DateField(null = True ,blank=True) def __str__(self): return self.title What I must do? -
Django: NameError: Slug is not defined
Can anyone advise on how to query the `total_likes of a post to be shown in my HTML, I tried, but was given this error: NameError: Slug is not defined An expert has suggested me to use generic class views which i am not familiar with, is there any other ways i can query the correct post and define the slug? Unsure of why it didnt work for the home feed view but it did work for the detail blog view. Whats wrong actually. I cant include a slug argument in the home view as the url does not contain a . is there really no other way to do it? I think it might be the way I am querying and linking the blog post with the likes but I'm not sure why I'm wrong and I don't know how to modify it despite trying for a few hours. views.py def home_feed_view(request): context = {} blog_posts = sorted(BlogPost.objects.all(), key= attrgetter('date_updated'), reverse = True) blog_post = get_object_or_404(BlogPost, slug=slug) total_likes = blog_post.total_likes() liked = False if blog_post.likes.filter(id=request.user.id).exists(): liked = True context['blog_posts'] = blog_posts context['blog_post'] = blog_post context['total_likes'] = total_likes return render(request, "HomeFeed/snippets/home.html", context) def LikeView(request, slug): context = {} post = … -
Django Allauth set username as Gmail Address
I am new to Django Allauth and am a bit confused and need help I have a custom user model with the following fields username = models.CharField(_('username'), max_length=130, unique=True) full_name = models.CharField(_('full name'), max_length=130, blank=True) is_staff = models.BooleanField(_('is_staff'), default=False) is_active = models.BooleanField(_('is_active'), default=True) date_joined = models.DateField(_("date_joined"), default=date.today) phone_number_verified = models.BooleanField(default=False) change_pw = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True,default=create_new_ref_number()) country_code = models.IntegerField(default='+91') two_factor_auth = models.BooleanField(default=False) I am able to successfully signup a user using gmail signin. However, in the username field, "user" value is saved. I want to save the email address from gmail as username. I have done some research and it seems like I need to write some save signals and add some settings, but I am not really sure what to write where. I have gone through the docs and its a bit confusing. Using SocialAccounts , I am able to get photo and full_name def socialuser(self): data = SocialAccount.objects.get(user=self.id).extra_data nameofuser = data.get('name') return nameofuser def socialuserphoto(self): data = SocialAccount.objects.get(user=self.id).extra_data pictureurl = data.get('picture') return pictureurl I use the href below for both signup or signin a user <a title="Google" class="socialaccount_provider google" style="text-decoration:none;" href="/accounts/google/login/?process=login">Sign in with Google</a> -
Django tamplate can not loaded
I called a template in the django render function, but django cannot find it here is the django view code: from django.shortcuts import render # Create your views here. def home_page(request): return render(request, "index.html") And after this I tried to check my settings.py and urls.py, but found nothing, and the file is also in the tamplate subfolder of the app here is the directory structure: │ .gitignore │ db.sqlite3 │ funcational_test.py │ manage.py │ ├─Terminal_equipment_management │ │ asgi.py │ │ settings.py │ │ urls.py │ │ view.py │ │ wsgi.py │ │ __init__.py │ │ │ └─__pycache__ │ └─webui │ admin.py │ apps.py │ models.py │ tests.py │ views.py │ __init__.py │ ├─migrations │ ├─tamplate index.html the settings.py is: INSTALLED_APPS = [ "api", "webui", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] urls.py is: from django.contrib import admin from django.urls import path, include from webui import views urlpatterns = [ path("", views.home_page, name="home_page"), ] But when I visit localhost:8000/, Django will report TemplateDoesNotExist at / here is some Error Message: Template-loader postmortem Django tried loading these templates, in this … -
Unable to Run Celery and celery beat using docker in django application (Unable to load celery application)
when I am trying to run my application I using without docker its working perfectly , but In docker-compose I am getting this error : | Error: Invalid value for '-A' / '--app': | Unable to load celery application. | The module sampleproject was not found. my docker-compose file app: container_name: myapp hostname: myapp build: context: . dockerfile: Dockerfile image: sampleproject tty: true command: > bash -c " python manage.py migrate && python manage.py runserver 0.0.0.0:8000 " env_file: .env ports: - "8000:8000" volumes: - .:/project depends_on: - database - redis redis: image: redis:alpine celery: build: context: ./ dockerfile: Dockerfile command: celery -A sampleproject worker -l info depends_on: - database - redis celery-beat: build: . command: celery -A sampleproject beat -l info depends_on: - database - redis - celery my Docker file FROM python:3.8 COPY requirements.txt requirements.txt RUN pip install -r requirements.txt --no-cache-dir \ && rm -rf requirements.txt RUN mkdir /project WORKDIR /project my folder structure is something like this : -
how can you return values introduced in a form to the same page? Django
I'm creating an email scrapper that outputs the emails of a specific URL introduced to a form. The problem is that as of now, the email list is printed to another separated URL, but I want it to return to the same page. How could you do this? I'm new Emailsearcher.html: This is the HTML code I have and that I want it to print the form values. As you can see here, I've tried using a loop but it doesn't work. {% include "leadfinderapp/navigation.html" %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> </head> <body> <div class="container"> <br/> <div class="row justify-content-center"> <div class="col-12 col-md-10 col-lg-8"> <form class="card card-sm" action="{% url 'scrap' %}" method="GET"> <div class="card-body row no-gutters align-items-center"> <div class="col-auto"> <i class="fas fa-search h4 text-body"></i> </div> <!--end of col--> <div class="col"> <input type="text" class="form-control form-control-lg form-control-borderless" placeholder="Introduce URL" name="Email" id="InputSearch" value="{{ Email.get }}" aria-describedby="searchHelp"> </div> <!--end of col--> <div class="col-auto"> <button class="btn btn-lg btn-success" type="search">Find Email Address</button> </div> <!--end of col--> </div> </form> </div> <!--end of col--> </div> {% for email in email_list %} <p> {{ email }} </p> {% endfor %} </div> <!-- Begin Page Content --> <!-- /.container-fluid --> <!-- Footer --> {% include 'leadfinderapp/footer.html' %} … -
Is there anyway to send WhatsApp messages to multiple phone numbers in Django using Twilio
I am trying to send the same message to multiple phone numbers using Twilio. This is the code in my views.py file to send WhatsApp message. The for loop is working only for the first number. Is this the right way to call for loops in Django? phone_numbers = ['number-1', 'number-2'] form = MessageForm(request.POST) if request.is_ajax(): if form.is_valid(): body = form.cleaned_data.get('body') for number in phone_numbers: send_whatsapp_message(body, number) return JsonResponse({'body': body}) -
Django REST API with Custom User table
Can someone please provide me a guide/reference using which I can implement user authentication and permission using stored procedure in MySQL? I want to create the user table first. -
django efficient ways to decompose and compose user data to and from bytes
So, I have a concept of a virtual data-store. I want to make sure that Whatever information the user enters, It is converted into binary and stored to the database. Upon retrieval, it must be reconverted from Binary. This is the core idea. Here are my models: class DataSheetField(models.Model): """ Represents a parent which belongs to a dataSheet. Fields have their own data types. Field data is stored in different models, depending on the dataType set. """ class DataTypes(models.TextChoices): """ A list of all the supported dataTypes formatted as different choices. This list is flexible although migrations might take a while. """ FLOAT = 'FLOAT' BOOLEAN = 'BOOLEAN' CHAR = 'CHAR' INTEGER = 'INTEGER' BIG_INTEGER = 'BIG_INTEGER' SMALL_INTEGER = 'SMALL_INTEGER' BYTES = 'BYTES' DATE_TIME = 'DATE_TIME' objects = models.Manager() id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True) name = models.SlugField(max_length=100, validators=[MinLengthValidator(2)], db_index=True) data_type = models.CharField(choices=DataTypes.choices, default=DataTypes.INTEGER, db_index=True, max_length=15) created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True) data = models.ManyToManyField('api_backend.FieldData') ... REQUIRED_FIELDS = [name, data_type] This model DataSheetField can be considered as a field in any normal database. It has it's own data-type which is going to be used to validate the data stored inside it. The field also has a many to many field data. … -
The modified time (auto_now) works on Django but not in Heroku when deployed
So this is my code in class Post(models.Model) class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) and snippet of my code in home.html {% if post.date_modified is not Null %} <small class="text-secondary font-italic">— modified at {{ post.date_modified }}</small> {% endif %} The codes work perfectly in Django, however, when I deployed them in Heroku: the date_modified of posts are filled (same date and time as date_posted) sodate_modified is not Null. This makes them show up even if the post is not updated by the user. I have already done: python manage.py makemigrations python manage.py migrate git add -A, git commit -m "message", git push heroku master heroku run python manage.py makemigrations heroku run python manage.py migrate Does anyone know how to fix this or explain why this happened? I can't seem to find any solution related to this. Maybe I missed something. -
Django User model saves twice into database
I am trying to create multi user registration system with Django. However, anytime I call the save() method to save a User type, it saves into the User table twice. The funny thing about the second model that is saved is that many required fields are empty. I am using a custom user model that I created from AbstractBaseUser. I also rewrote the forms for the CustomUser model. For the multiple user types, I am using a profile model (Student model has a OneToOne field to the user model) models.py: class User(AbstractBaseUser, PermissionsMixin): # I've removed some unimportant code here email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) class Types(models.TextChoices): STUDENT = 'STUDENT', 'Student' DEPARTMENT_USER = 'DEPARTMENT_USER', 'Department user' ADMIN = 'ADMIN', 'Admin' user_type = models.CharField(_('Type'), max_length=50, choices=Types.choices, default=Types.STUDENT) first_name = models.CharField(_('First name'), max_length=70, blank=False, default="") middle_name = models.CharField(_('Middle name'), max_length=70, blank=True, default="") last_name = models.CharField(_('Last name'), max_length=70, blank=False, default="") is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # a admin user; non super-user is_superuser = models.BooleanField(default=False) # a superuser last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['user_type', 'first_name', 'last_name'] # Email & Password are required by default. objects = UserManager() class Meta: verbose_name … -
I want to add Foreign Key to Model Messages of model Namefor link, but i am getting this error. i am new to django so i dont understand the error
models.py from django.db import models import uuid # Create your models here. class NameforLink(models.Model): name=models.CharField( max_length=50) id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) def __str__(self): return self.name class Messages(models.Model): id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name_id=models.ForeignKey(NameforLink, on_delete=models.CASCADE, default=uuid.uuid4, related_name='name_id') checkbox1=models.CharField(max_length=50, default='') checkbox2=models.CharField(max_length=50, default='') commentbox=models.CharField(max_length=500, default='', null=True, blank=True) THIS is the error message: in check_constraints raise IntegrityError( django.db.utils.IntegrityError: The row in table 'comment_messages' with primary key '1' has an invalid foreign key: comment_messages.nameId_id contains a value '4f25c6ae984345d081e2c1373bed61d9' that does not have a corresponding value in comment_nameforlink.id. -
How to execute jQuery code before submitting the form
How do I make my jQuery code execute before submit and before sending it to database? I'm trying to take user input from checkbox, process it in jQuery and send this value to a hidden html field. When executing separately the code works as it should, console.log returns correct value, however when executed inside the project Django returns error that the value is empty ("") and jQuery alert added for debugging does not execute. <form id="cat-form" action="" method="post"> {% csrf_token %} <ul> <p>Imię:</p> <input type="text" id="name" name="cat_name" required> </ul> <ul> <p>Question?</p> <input type="radio" id="f_low" name="friendliness" value="0" required> <label for="f_low">Answer 1</label> <br> <input type="radio" id="f_medium" name="friendliness" value="1"> <label for="f_medium">Answer 2</label> <br> <input type="radio" id="f_high" name="friendliness" value="2"> <label for="f_high">Answer 3</label> </ul> <ul><input type="hidden" id="friendliness_level" name="friendliness_level"></ul> <input type="submit"/> </form> Script: <script type = "text/javascript" language = "javascript"> $('#cat-form').submit(function() { // Take html user input into variables var friendliness = $("input[type=radio][name=friendliness]:checked").val(); // populate hidden fields with variable values $('#friendliness_level').val(friendliness); console.log($('#friendliness_level').val()) }); </script> views.py def cat_create(request): if request.method == 'POST': cat = Cat() cat.friendliness_level = request.POST.get('friendliness_level') cat.save() return render(request, 'cats/cat_description.html') else: return render(request, 'cats/cat_description.html') -
Value: abc must be an instance of <class 'dict'> with EmbeddedField
Trying use EmbeddedField of Djongo but without any success. Output error: Value: abc must be an instance of <class 'dict'> class MetaData(models.Model): title = models.CharField(max_length=255) keyword = models.CharField(max_length=255) def __str__(self): return self.title class Meta: abstract = True class Posts(models.Model): _id = models.ObjectIdField() heading = models.CharField(max_length=255) content = models.TextField() metadata = models.EmbeddedField(model_container=MetaData) objects = models.DjongoManager() def __str__(self): return self.heading Preview error on Django Admin: python: 3.8.0 MondoDB: 4.4.3 Django: 3.0.5 Djongo: 1.3.3 -
how can i order by data per group by in django ORM
I have 3 models in django ORM like this class Singer(m.Model): name = m.CharField(max_length=50) class Music(m.Models): singer = m.ForeignField("singer") title = m.CharField(max_length=50) class PlayedHistory(m.Models): played_time = m.DateTimeField(auto_now_add=True) music = m.ForeignField("music") and I want to get top 3 singer of music played per month using PlayedHistory like... Date | Singer | PlayCount | LastPlayed | ---------------------------------------------- 202012 singer1 40000 202101T12:30:12 (202012 top1) 202012 singer2 39000 202101T11:10:22 (202012 top2) 202012 singer3 38000 202101T10:10:22 (202012 top3) 202011 singer2 90000 202011T11:11:55 (202011 top1) 202011 singer5 87000 202011T11:11:14 (202011 top2) 202011 singer4 50000 202012T08:13:52 (202011 top3) ... 201912 singer4 10000 202012T08:13:52 i tried to using orm queryset, first group by singer and count played PlayedHistory.objects.\ values('music__singer__name').\ annotate(Singer=F('music__singer__name'), PlayCount=Count('id')).\ values('Singer', 'PlayCount').order_by('PlayCount') So the result is ... | Singer | PlayCount | -------------------------- singer2 129000 singer5 87000 singer4 50000 singer1 40000 singer3 39000 but i wonder how can i group per one month and show just top 3 record... please some information or advice thank you :) -
How to implement JavaScript in Django?
I am creating a basic To-Do web app and I'm struggling with the last part - which is implementing JavaScript in Django. I created a separate .js file in a static folder. // Create a "close" button and append it to each list item var myNodelist = document.getElementsByTagName("LI"); var i; for (i = 0; i < myNodelist.length; i++) { var span = document.createElement("SPAN"); var txt = document.createTextNode("\u00D7"); span.className = "close"; span.appendChild(txt); myNodelist[i].appendChild(span); } // Click on a close button to hide the current list item var close = document.getElementsByClassName("close"); var i; for (i = 0; i < close.length; i++) { close[i].onclick = function() { var div = this.parentElement; div.style.display = "none"; } } // Add a "checked" symbol when clicking on a list item var list = document.querySelector('ul'); list.addEventListener('click', function(ev) { if (ev.target.tagName === 'LI') { ev.target.classList.toggle('checked'); } }, false); // Create a new list item when clicking on the "Add" button function newElement() { var li = document.createElement("li"); var inputValue = document.getElementById("myInput").value; var t = document.createTextNode(inputValue); li.appendChild(t); if (inputValue === '') { alert("You must write something!"); } else { document.getElementById("myUL").appendChild(li); } document.getElementById("myInput").value = ""; var span = document.createElement("SPAN"); var txt = document.createTextNode("\u00D7"); span.className = "close"; span.appendChild(txt); li.appendChild(span); for (i … -
Djoser authentication working differently on production server than development
I have been working on getting logins working with both emails and usernames, and I ended up finding this link. The first answer on that worked excellently in my development environment, and I was very happy with how simple the solution was, but doesn't work at all on my production server. Here is what I have tried: Checking python versions are the same Checking django versions are the same Checking djoser versions are the same Checking simplejwt versions are the same Removed and replaced all code on production server using git Removed and replaced all code on production server using ftp Checked that the code in the models.py file is correct Replaced the database with the local database Deleted and rebuilt the virtual environment Checked for errors in the logs Opened port 8000 on the production server and served it with manage.py runserver No matter what I do, I still get {"detail": "No active account found with the given credentials"} as the response when using email as the username, but things work fine when using the username as the username. I have no idea where to check now. As far as I can tell, there is absolutely no difference between … -
how to make some part of the page as unauthenticated in django?
I have a Django project which uses JWT as the authentication class. But for certain pages of my app has no authentication. But still when I make request it returns the following thing. { "detail": "You do not have permission to perform this action." } My authentication classes are here REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } My views file is here class Hello(APIView): authentication_classes = [] def post(self, request): return Response('Hello') So how do I achieve this thing? -
Django unit test constraints
So I have a problem in writing my unit tests for a Check and Unique constraint. Here are the their definition: # assert that a partner can have only one headquarter constraints = [ models.UniqueConstraint( fields=['partner', 'active'], condition=models.Q(headquarter=True), name='HQ already set.' ) ] # assert every partner contant has at least one of email/phone number pair defined constraints = [ models.CheckConstraint( check= ( models.Q(email__isnull=False) & models.Q(phone_number__isnull=False) ), name='E-mail or phone number should be set.' ) ] And the unit test asserts which fails: from django.db.utils import IntegrityError .... # HQ already defined so it should work with self.assertRaises(Exception) as raised: partnerHQCopy.save() self.assertEqual(IntegrityError, type(raised.exception)) ..... # The contact added has both email and phone number None with self.assertRaises(Exception) as raised: partnerContact.save() self.assertEqual(IntegrityError, type(raised.exception)) And the traceback: ====================================================================== ERROR: test_unique_hq_for_partner (partners.tests.PartnerModelsTestCases) ---------------------------------------------------------------------- ..... sqlite3.IntegrityError: UNIQUE constraint failed: partners_partnerbranch.partner_id, partners_partnerbranch.active ..... django.db.utils.IntegrityError: UNIQUE constraint failed: partners_partnerbranch.partner_id, partners_partnerbranch.active ====================================================================== ERROR: test_partner_contact_no_email_no_phone (partners.tests.PartnerModelsTestCases) ---------------------------------------------------------------------- ..... sqlite3.IntegrityError: CHECK constraint failed: E-mail or phone number should be set. ..... django.db.utils.IntegrityError: CHECK constraint failed: E-mail or phone number should be set. -
Django HTML can't read the values of the dict
When I pass a simple dict (myDict = {"key": "value"}) throught render to html, it creates an error as the html can't read the values of the dict .. {{ myDict["key"] }} <!--- prompts an error--> django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '['key']' from 'myDict['key']' Why didn't I pass the value directly? Because my question is not about this particular example. I'm searching for a more effecient way to use in case I wanted to pass bigger dicts and avoid writing down a for loop and if conditions on every line. -
How to deal with multiple rows of same table in django orm?
I have this table: User |Book name | count ------*----------*------ user1 | A | 4 user2 | A | 5 user1 | B | 6 user2 | B | 9 I have this table, Now I want to fetch all the users which have a total book count of less than 10. How can I write such a Django or query which involves dealing with two rows of the same table? -
How to use django-river transition approval in ListView or DetailView
I successfully implement django-river transition approval in my admin page so different groups can submit the approval and so on following the demo tutorial https://github.com/javrasya/fakejira I'm attempting to utilize the river-action "Transaction approval" on my ListView or DetailView so the users can submit on the approval using my ListView url instead of entering the admin page. My current ListView as below: class WorkOverRequestSubmitListView(ListView): model = WorkoverRequest context_object_name = 'submit_wor_list' template_name= 'wor/workovers_submit_list.html' Would you suggest what I should edit and add to my project to make this work! -
Set the value of a variable in django template using 'with' tag for checking in an 'if' condition. But get's error : 'endif', expected 'endwith'
I have set a variable as False in django templates, then sets the variable to True in an if condition both using 'with var=True/False' I use seperate 'endwith' tags for each 'with' tag. But I'm getting an error saying 'endif', expected 'endwith'. Template code as below: {% date_range as the_days %} {% for day in the_days %} {% with is_order_day=False %} {% for order in orders % {% if order.created_at.date == day.date in orders %} {% with is_order_day=True %} {% endif %} {% endfor %} {% if is_order_day %} <p>{{day.date}}</p> {% endif %} {% endwith %} {% endwith %} {% endfor %} thanks in advance. -
Django how to change the name of Custom User Model in error messages in a form
I have created a sign up form called UserRegistrationForm using UserCreationForm in djnago and have a custom user model name CustomUserModel. When I sign up using wrong credentials, the error messages show "Custom user model with this User name already exists.". I would like it to be something like "Username already exists". How can I do that? Forms.py class UserRegistrationForm(UserCreationForm): user_name = forms.CharField(max_length=150) email = forms.EmailField() first_name = forms.CharField(max_length=120) last_name = forms.CharField(max_length=120, required=False) date_of_birth = forms.DateField( widget=forms.DateInput( format='%d/%m/%Y', attrs={'type': 'date', 'min': '1900-01-01', 'max': str(timezone.now().year)+'-'+str(timezone.now().month)+'-'+str(timezone.now().day)}, ) ) gender = forms.ChoiceField( widget=forms.Select, choices=(('M', 'Male'), ('F', 'Female'), ('T', 'Transgender'), ('N', 'NonBinary')), initial='N', ) def is_valid(self): form = super(UserRegistrationForm, self).is_valid() print("*******************************") print(self.errors) print("*******************************") return form Here is a picture to help you understand my problem here the error states "Custom user model with this User name already exists." I want to change this message -
How to remove a library whose initial migration is being depended on?
So my model used to inherit from a Message class of django-postman library. Therefore my 0001_initial migration looks like this: class Migration(migrations.Migration): initial = True dependencies = [ ('postman', '0001_initial'), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('message_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='postman.Message')), ('created_at', models.DateTimeField(auto_now_add=True)), ('deliver_at', models.DateTimeField(blank=True, null=True)), ('content', models.TextField(blank=True, null=True)), ], bases=('postman.message',), ), ] Now I want to totally remove my own Message model. I can remove it normally and run makemigrations which creates 0004_delete_message that looks like this: class Migration(migrations.Migration): dependencies = [ ('postman', '0001_initial'), ('my_app', '0003_migrate_data_to_new_model'), ] operations = [ migrations.DeleteModel( name='Message', ), ] Now the issue is that I totally want to remove django-postman library, including from my INSTALLED_APPS. This creates the issue of both of these migrations not being applicable because they both depend on postman.0001_initial which doesn't exist anymore. Is there clean way of going about that deprecation while still keeping my migrations working or do I have to manually edit my 0001_initial and run CreateModel for the model introduced in postman.0001_initial, and change bases of my model to point to that model I created?