Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get TextChoice enum value in __str__ method
This is how I tried defining models in models.py from django.db import models class Country(models.Model): class Countries(models.TextChoices): US = 'US', 'United States' EP = 'EP', 'Europe' IND = 'IN', 'India' name = models.CharField(max_length=2, choices=Countries.choices, blank=True) def __str__(self): return getattr(self.Countries, self.name) the str invocation just gives two letter country code. How do I get full info like US (United states) or US, United States -
Django Oauth V2 redirect uri
these are all my tested redirects at once https://127.0.0.1:8080/auth/linkedin https://127.0.0.1:8080/oauth/complete/linkedin-oauth2/ https://127.0.0.1:8080/users/auth/linkedin/ https://127.0.0.1:8080/social-auth/complete/linkedin-oauth2/ https://127.0.0.1:8080/social-auth/linkedin https://127.0.0.1:8080/social-auth/linkedin/callback https://127.0.0.1:8080/auth/linkedin/callback I keep getting "bummer, something went wrong. redirect uri does not match" -
Restricting accesses on views based on the custom user type in Django
I created a custom user using AbstractUser with 3 user types USER_TYPE = ( ("type1", "type1"), ("type2", "type2"), ("type3", "type3"), ) class User(AbstractUser): user_type = models.CharField(max_length=50, choices=USER_TYPE, null=True, blank=True, default="") and each user have a dashboard its only visible to the corresponding user, but my case I can access all dashboard if any user is logged in so how to restrict the access based on this user types (type1, type2, type3 ) I am using class-based views -
django taggit, import_export : I had an error '_TaggableManager' object has no attribute 'objects' why?
I'm using django-taggit and django-import-export. I want to add tags using import, but it didin't worked. I think that my problem is ManyToManyWidget(KnowHow.free_tags) in this row of KnowHowResource, but I don't know how to solve and wonder why. I'm also in this issue. free_tags = fields.Field(attribute="free_tags", column_name="free_tags", widget=widgets.ManyToManyWidget(KnowHow.free_tags)) admin.py from django.contrib import admin from import_export import resources from import_export import fields,widgets from import_export.admin import ImportExportModelAdmin from .models import KnowHow # Register your models here. class KnowHowResource(resources.ModelResource): free_tags = fields.Field(attribute="free_tags", column_name="free_tags", widget=widgets.ManyToManyWidget(KnowHow.free_tags)) class Meta: model = KnowHow import_id_fields=['id'] #fields =('id', 'author', 'category', 'title', 'text', 'file', 'basic_tag', 'free_tags',) #admin.site.register(KnowHow) @admin.register(KnowHow) class knowHowAdmin(ImportExportModelAdmin): resource_class = KnowHowResource models.py from django.db import models from django.urls import reverse from taggit.managers import TaggableManager class KnowHow(models.Model): BASIC_TAGS =( ('1','one'), ('2','two'), ('3','three'), ('4','four'), ('5','five'), ('6','six'), ) CATEGORY =( ('1','Type2'), ('2','Type1'), ) author = models.ForeignKey('auth.User',on_delete=models.CASCADE) category = models.CharField(max_length=1,choices=CATEGORY,default='1') title = models.CharField(max_length=200) text = models.TextField(blank=True,default=' ') # delault=' ':import system will give a error if text column is null file = models.FileField(blank=True,upload_to='explicit_knowhows') basic_tag = models.CharField(max_length=1,choices=BASIC_TAGS,default='1') free_tags = TaggableManager(blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('portal:index') -
webhook response with django channel's AsyncHttpConsumer on Heroku
I am trying to migrate my code from wsgi to use asgi/channel's asyncHttpConsumer. I can get a http_request from diaglogflow. Then I can either use send() or send_response() for response. I can do something like await self.send_response(200, b'response text', headers=[(b"Content-Type", b"text/plain"), ]) and my heroku server sends it out normally, but dialogflow does not get anything back. I have another wsgi application that just uses from django.http import JsonResponse ... fulfillmentText = {'fulfillmentText': "server works correctly"} return JsonResponse(fulfillmentText, safe=False) where this actually returns to dialogflow correctly. I tried to use JsonResponse on the asgi/channel side but it just gives me an error that just basically say I'm not using send_response correctly. What do I need to do to convert my response correctly on the asyncHttpConsumer side? -
Django /admin/ doesn't accept correct credentials. How do I fix it?
This question was asked multiple times already, but I didn't find solution so far. All the requirements from docs are satisfied already. I created superuser from shell opened by command python manage.py shell. Then I ran command manage.py runserver, went to http://127.0.0.1:8000/admin/ and entered login and password for newly created superuser. And I'm receiving error message: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. Why? I tried to recreate superuser, change password, create different superuser just in case there are inacceptible characters with as simple credentials, as possible, but still the same result. What's wrong with that? How do I fix this? I'm using Windows 10, PyCharm, Python 3.7, Django 2.2.3. -
DRY fields in Django models
I know about using inheritance and abstract models in reusing common fields in different models. I'd like to know if the following approach is possible instead of inheritance and mixins. from django.db import models common_modified_by = models.CharField() class Author(models.Model): name = models.CharField() modified_by = common_modified_by class Book(models.Model): title = models.CharField() modified_by = common_modified_by Will the above code work? Why or why not? -
DRF - How to limit depth of a serializer?
I have many models and using DRF as a REST API. Almost every serializer is nested. This causes a problem such that ModelASerializer is multiple times nested because it uses ModelBSerializer which uses ModelCSerializer... etc. class ModelBSerializer(..): modelcs = ModelCSerializer(...) class Meta: fields = '__all__' class ModelASerializer(..): modelbs = ModelBSerializer(many=True..) class Meta: fields = '__all__' The thing is that it obviously slows down everything. I thought that if I add depth=2/1 to ModelASerializer.Meta, modelcs won't be serialized because they are 2/1 levels nested. But it still serializers everything. Is it possible to make it work? I can create new serializers but this would be much more elegant. -
Dependent Drop Down Menu In Django Admin
In models.py, I have a field (category) that has to display choices based on the choice from one of my previous fields (gender). How can I write my model in such a way that it is accomplished in my admin site? I could not find any solution for this online. -
Django models' best solution for this reverse ForeignKey
I'm making a personal project to manage restaurants. Two of my models are facing a problem, these models are DiningRoom and Table. DiningRoom is the representation of any area that the restaurant could have (e.g. we could have one area inside and other area in the terrace of the building). And in every DiningRoom we can set a layout of Tables. So, the more object-oriented way I find to map this is by many-to-one relationship (ForeignKey). Since one DiningRoom can have many Tables, and one Table can be only in one DiningRoom. Right? So my models are: class DiningRoom(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE, null=False) name = models.CharField(max_length=50, null=False, blank=False) rows = models.IntegerField(max=15, null=False) cols = models.IntegerField(max=15, null=False) # rows and columns are for the room's grid layout. class Table(models.Model): row = models.IntegerField(max=15, null=False) # The row in the room's grid where the table is at. col = models.IntegerField(max=15, null=False) # the column in the room's grid where the table is at. dining_room = models.ForeignKey(DiningRoom, on_delete=models.CASCADE, null=False) # Here is the problem. The problem is that when I am querying DiningRooms of the account in the view, I need to fetch also the Tables that are related to each DiningRoom in … -
Execute other python script when django server is started
I have a Django project and other python script which is a ZMQ socket which continuously listens for message to perform some operation, ZMQ server script is an independent script which for now runs as python zmq_server.py in a terminal or cmd. What I am trying to do is start the ZMQ server script when python manage.py runserver is called to start the django server. I did some digging but found nothing related to this, is it possible to do something like this? -
creation of the profile editing view
hello everyone it's been a while since I haven't coded but I noticed some pref changes so I have some problem with the profile application edited the profile my code views @login_required def edit_profile(request): if request.method =='POST': user_form =UserEditForm(data=request.POST or None, instance=request.user) profile_form=ProfileEditForm(data=request.POST or None, instance=request.user.profile ,files =request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() else: user_form=UserEditForm(instance=request.user) profile_form=ProfileEditForm(instance=request.user.profile) context ={ 'user_form':user_form, 'profile_form':profile_form, } return render(request,'accounts/edit_profile.html',context) form class UserEditForm(forms.ModelForm): class Meta: model=User fields=('username', 'email') class ProfileEditForm(forms.ModelForm): class Meta: model=Profile fields=('description', 'image') another try to see the same error form class EditProfileForm(UserChangeForm): class Meta: model=User fields=('username', 'email') view @login_required def edit_profile(request): if request.method =='POST': form= EditProfileForm(request.POST,instance=request.user) if form.is_valid(): form.save() return redirect("/profile/") else: form=EditProfileForm(instance=request.user) args={'form': form} return render(request,'accounts/edit_profile.html',args) error The view accounts.views.edit_profile didn't return an HttpResponse object. It returned None instead. -
Django Pagination Where User Selects/Types Desired Page
I am looking to create a pagination like either of the following examples: https://www.martindale.com/search/attorneys/?term=Bankruptcy%20near%20New%20York%2C%20USA (top right of search results) https://www.adidas.com/us/superstar?start=0 (scroll to the bottom) Where a user could either type in the page they want to go to and press enter or have a dropdown selection showing all the possible pages to choose from and then once selecting, automatically go to that page (the dropdown probably seems better to prevent users from typing a random set of numbers of characters into the input field). When attempting to do this, I ran into an issue not being able to use a template tag within forms.py. I was able to make a template for loop dropdown menu that loops through all the possible pages. But this for loop is not using forms.py which I don't think is desirable (because no validation). My pagination code is currently separate from forms.py. I would still like to keep the current next, previous, first, and last links to appease those types of users. But if there are lots of pages of results, I want to give users freedom to quickly go to a desired page they want without clicking next or previous a bunch of times … -
How to parametrize django model objects for pytest of modal views
From actual situation I have in my django project three models each with CRUD views. models.py class Model1(models.Model) pass class Model2(models.Model) pass class Model3(models.Model) pass in the views.py they are correct linked to BSModalCreateView, BSModalReadView, ...they are also entered in the urls.py of the django project (It works fine on the system ;) ) BUT! Now I try to test the correct functionality of these, starting from the reachability by the url. So I start in test_views.py with: test_views.py import pytest from django.urls import reverse from ..models import * @pytest.mark.django_db class TestBodyvalueRUD(object): @pytest.fixture(autouse=True) def setup_stuff(self, db): Model1.objects.create(...) @pytest.mark.parametrize("url_location", ['Project/CRUD_Model1/read/0', 'Project/CRUD_Model1/update/0', 'Project/CRUD_Model1/delete/0', ]) def test_view_url_exists_at_desired_location(self, client, url_location): response = client.get(url_location) assert response.status_code == 301 @pytest.mark.parametrize("url_name", [...]) def test_view_url_accessible_by_name(self,client, url_name): pass @pytest.mark.parametrize("url_name, template_file", [...]) def test_view_uses_correct_template(self, client, url_name, template_file): pass What is the correct way to parametrize the model objects? As the complete set of tests is identical I don't want to create it for all models (code redundency). I'm also not very happy with the style of the parametrization of the class methods - anyway I guess the need to move BTW - In actual code I'm also facing problems with the db interaction to the django test db. Seems I'm … -
How to set value in charfield which is the value of previous charfield?
I was wondering if it is possible to set the value of another charfield automaticaly basing on previous choice ? I'm working on some simple movie-app and I need to change the colors of badge in html, basing on movie type. I would like to automate it instead of setting the collors manually. I'm kinda new in django. Basing on "kind" value I need to set the "color" value. My Code: AGE_CATEGORY = { ("0","All"), ("6","Kids"), ("16","Teenagers"), ("21","Adults") } MOVIE_CATEGORY = { ("H","Horror"), ("F","Fantasty"), ("ScI","Science-Fiction"), ("C","Comedy"), ("R","Romance"), ("T","Thriller"), ("D","Drama"), } MOVIE_CATEGORY_COLORS = { ("H","danger"), ("F","primary"), ("ScI","secondary"), ("C","warning"), ("R","success"), ("T","dark"), ("D","info"), } class Movies(models.Model): title = models.CharField(max_length=100) age = models.CharField(choices=AGE_CATEGORY, max_length=2) kind = models.CharField(choices=MOVIE_CATEGORY, max_length=3) color = models.CharField(choices=MOVIE_CATEGORY_COLORS, max_length=1) price = models.FloatField() date = models.DateField() max_seats = models.IntegerField() description = models.TextField() def __str__(self): return self.title -
'posix_spawn: No such file or directory' error while using scp command in windows
Im trying to scp my django app (its in the desktop) to my server using linode. Im using Windows 10 version 1903. I typed this command: scp -r excelsite ****@**.**.**.***:~/ But it gave out this error... BTW, im using OpenSSH. CreateProcessW failed error:2 posix_spawn: No such file or directory Any help if very much appreciated! -
How to render Django TextField within VueJs Template
I am writing my backend using DRF and using VueJS frontend templates. In the admin panel I use Ckeditor to edit textfield. class ArticleModelForm(forms.ModelForm): content = forms.CharField(widget=CKEditorUploadingWidget) class Meta: model=Article fields = [ "title", "slug" "published_at"] While rendering a post TextField I can not use template filters to render correctly, so text seems ruined. I have tried lots of things but no success yet. <template> <div> <div class="container negative-margin-top150"> <div class="col col-xl-8 m-auto col-lg-12 col-md-12 col-sm-12 col-12"> <div class="ui-block"> <!-- Single Post --> <article class="hentry blog-post single-post single-post-v1"> <div class="post-content-wrap"> <div class="post-content" > <p class="post-paragraph"> {{article.content}} </p> <p>{{content}}</p> </div> </div> </article> <!-- ... end Single Post --> </div> </div> </div> </div> </template> and my script is below <script> import axios from 'axios'; export default { name: "Article", props: { slug: { type: String, required: true } }, data() { return { article: {}, content: `${content}`, } }, methods: { setPageTitle(title) { document.title = title; }, setRequestUser() { this.requestUser = window.localStorage.getItem("username"); }, getArticle(slug) { axios.get(`http://localhost:8000/api/articles/${this.slug}`) .then(response => { this.article = response.data; this.setPageTitle(response.data.title); this.content = window.content; }); } }, created() { this.getArticle(); this.setRequestUser(); }, }; </script> Now in the browser my text is rendered with template tags <h3>The standard Lorem Ipsum passage, … -
Spider wrapped in Django gets stuck how to stop?
I have a Scrapy spider wrapped in to Django and to start it programatically I am using scrapyscript which uses Billiard queues and Processes to run Scrapy. I know it's a strange setup but I need a spider that can be run by cron and work with django orm. Also, everything works fine, I get my data scraped, I can run it programatically, but one thing sucks: the spider gets stuck and code execution waits forever. # start.py cmd = ['C:\\PycharmProjects\\...\\start.bat', ] subprocess.call(cmd) # start.bat python C:\\...\\manage.py runserver --noreload # urls.py from my_app.myFile import MyClass c = MyClass() # myFile.py class MyClass(object): def __init__(self): githubJob = Job(ScrapOnePage, url='some/url') processor = Processor(settings=None) data = processor.run(githubJob) print(data) ScrapOnePage works out great, no need to show it, it does the job. The problem is Processor, somehow after saying "spider closed" it doesn't let go and doesn;t continue to another line. print(data) never happens, no matter how long I wait. This is what hangs around forever: 2020-01-05 22:27:29 [scrapy.core.engine] INFO: Closing spider (finished) 2020-01-05 22:27:29 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 1805, 'downloader/request_count': 4, 'downloader/request_method_count/GET': 4, 'downloader/response_bytes': 5933, 'downloader/response_count': 4, 'downloader/response_status_count/200': 1, 'downloader/response_status_count/301': 3, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2020, 1, 5, 21, 27, 29, 253634), … -
why i am having an attribute error in django
I'm beginner in django and studying it recently from a course, i'm working on authentication and login and logout functionality here is my Error And here is my views.py file def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_ative: login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponseRedirect("ACCOUNT NOT ACTIVE") else: print("Someone tried to login and failed") print('Username:{} and password {}'.format(username, password)) return HttpResponse("INVALID LOGIN DETAILS SUPPLIED") else: return render(request, 'basic_app/login.html', {}) And here is my login.html file {% extends 'basic_app/base.html' %} {% block body_block %} <div class = 'jumbotron'> <h1>Please Login</h1> <form action="{% url 'basic_app:user_login' %}" method="POST"> {% csrf_token %} <label for="username">Username</label> <input type="text" name="username" placeholder="Enter Username"> <label for="password">Password:</label> <input type="password" name="password" placeholder="Enter Password"> <input type="submit" value="submit"> </form> </div> {% endblock %} -
'PublishForm' object has no attribute 'get'
I am facing the error 'PublishForm' object has no attribute 'get'. I have no idea what is wrong. After a deep research I can't find a solution to this and eventually had to ask you guys. Well below is my code models.py SEMESTER_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ) class Publish(models.Model): dates = models.CharField(max_length=255, choices = SEMESTER_CHOICES) def __str__(self): return self.dates form.py SEMESTER_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ) class PublishForm(forms.ModelForm): def __init__(self, **kwargs): super(PublishForm, self).__init__(self, **kwargs) selected_choices = [i.dates for i in Publish.objects.all()] self.fields['dates'].SEMESTER_CHOICES = ({(k, v) for k, v in SEMESTER_CHOICES if k not in selected_choices}) class Meta: model = Publish fields = ['dates'] view.py def add(request): if request.method == 'POST': form = PublishForm(request.POST) if form.is_valid(): form.save() return redirect('mainapp:add') else: form = PublishForm() context = { 'form' : form } return render(request, 'mainapp/add.html', context) What am I missing here? Thank You -
Redirect Form to Home after submit - Django
I am trying to redirect the user to the homepage after submitting the registration form but seem to be stuck. I know you can utilize return HttpResponseRedirect('/') but is there a way to incorporate that inline with return render(request, 'signup.html', {'form': form}) # Signup Form def signup(request): form = UserCreationForm() if request.method == "POST": email = request.POST.get('email') password1 = request.POST.get('password1') password2 = request.POST.get('password2') user = User.objects.create(email=email) user_type = request.POST.get('user_type') # create jobseeker or company object if user_type == "jobseeker": jobseeker = JobSeeker.objects.create(user=user) else: # if user_type == "company": company = Company.objects.create(user=user) return render(request, 'signup.html', {'form': form}) -
IntegrityError - 1048, cannot be null - Unable to save validated_data
I want to accept the below mentioned JSON data from the user and want to save it into database (MySql). { "organisation_name":"abc pqr" } When I make a POST request it return me the error - IntegrityError at /api/organisation/ (1048, "Column 'organisation_id' cannot be null") Request Method: POST Request URL: http://127.0.0.1:8000/api/organisation/ Django Version: 2.1.15 Exception Type: IntegrityError Exception Value: (1048, "Column 'organisation_id' cannot be null") Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py in execute, line 76 Python Executable: /usr/local/bin/python Python Version: 3.7.6 Python Path: ['/app', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages'] Server time: Sun, 5 Jan 2020 20:26:14 +0000 views.py from typing import Optional, Any from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.parsers import JSONParser from . import serializers class OrganisationApiView(APIView): def get(self, request, formate=None): return Response({"message": "You are Cool!!"}) def post(self, request, formate=None): serializer = serializers.OrganisationSerializer(data=request.data) if serializer.is_valid(raise_exception=True): organisation_saved = serializer.save() organisation_name = serializer.validated_data.get('organisation_name') message = f"Onboarding for {organisation_name} has been successful!." return Response({'message': message, 'response': organisation_saved, 'status': status.HTTP_200_OK}) else: return Response(serializer.error_messages) def put(self, request, pk=None): return Response({'message': 'PUT'}) def patch(self, request, pk=None): return Response({'message': 'PATCH'}) def delete(self, request, pk=None): return Response({'message': 'Delete'}) models.py from django.core.validators import EmailValidator, validate_image_file_extension from django.db import models class BaseModel(models.Model): … -
django ajax django.utils.datastructures.MultiValueDictKeyError
I found an ajax sample for crud operations. Here is the original project I added 'city' field to my modal and got an error Traceback (most recent call last): File "C:\Users\Atilgan\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) KeyError: 'city' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Atilgan\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Atilgan\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Atilgan\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Atilgan\Desktop\Depo\jquerry\crud\views.py", line 10, in create member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'], city=request.POST['city']) File "C:\Users\Atilgan\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'city' Here is codes create script $('#create').on('click', function(){ $firstname = $('#firstname').val(); $lastname = $('#lastname').val(); $city = $('#city').val(); if($firstname == "" || $lastname == ""){ alert("Please complete the required field"); }else{ $.ajax({ url: 'create', type: 'POST', data: { firstname: $firstname, lastname: $lastname, lastname: $city, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(){ Read(); $('#firstname').val(''); $('#lastname').val(''); $('#city').val(''); } }); } }); views create def create(request): member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'], city=request.POST['city']) member.save() return redirect('/') models.py class Member(models.Model): firstname = models.CharField(max_length=40) lastname = models.CharField(max_length=40) city= models.CharField(max_length=40) def __str__(self): return self.firstname + " " + self.lastname + " " + self.city Sorry about that … -
How to pass a variable to a function from a view
I am using a SoftDeletableModel model from django-model-utils, which is an abstract base class model with a is_removed field that marks entries that are not going to be used anymore, but are kept in db for any reason. It has the following structure: class SoftDeletableModel(models.Model): is_removed = models.BooleanField(default=False) class Meta: abstract = True objects = SoftDeletableManager() all_objects = models.Manager() def delete(self, using=None, soft=True, *args, **kwargs): """ Soft delete object (set its ``is_removed`` field to True). Actually delete object if setting ``soft`` to False. """ if soft: self.is_removed = True self.save(using=using) else: return super().delete(using=using, *args, **kwargs) In the event I actually want to delete an object rather than set is_removed=True, I need to add soft=False in the delete process. How would I go about doing this in a view/template? -
Relation does not exist but no migrations to apply Django
I'm finally trying to build some tests (I should have done this long ago). But whenever I try python manage.py test I get django.db.utils.ProgrammingError: relation "Customers Table" does not exist Along with a stacktrace that gives no indication which model it is referring to (many models relate to Customers Table). I commented everything out of test.py - so the only thing python manage.py test is doing is trying to build that test db. I guess the question is around migrations because I imagine that's how it's building the test database. I am not sure how to even begin digging around in my 50+ migrations to find where/when I made this relation. Is there a way to purge/clean migrations without messing things up too much? Then I could create a new migration that reflects current-state accurately without preserving the sins of my past migrations.