Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run SearchHeadline (a heavy function) only on the Paginated QuerySet result
I am using Django and Postgresql Full-Text Search to generate a paginated search result for my users. I rank and highlight my results. qs = ( self.filter(Q(title_vector=SearchQuery(search_term))) .annotate(rank=rank) .order_by("-rank", "pk") .annotate( title_snippet=SearchHeadline( "title", SearchQuery(search_term), highlight_all=True ) ) .distinct() ) In performance testing, I've identified that the SearchHeadline function is extremely heavy (as mentioned in the documentation) and is applied to every single row in the result - even if there are thousands of results being paginated in sets of 25. This makes the query take too long to complete. Another user on StackOverflow had the same issue as mine and discovered that only running ts_headline against the paginated results significantly improves performance (Relevant Question). I tested and confirmed that a similar approach would solve my problem. My question is how can I tweak my Django code to generate a SQL query against a query like the below example? After the Paginator applies a limit and offset to the result set, only then run ts_headline against those results only. SELECT id, ts_headline('italian', body, to_tsquery('italian', 'torino')) as headline, rank, title, location FROM ( SELECT id, body, title, location, ts_rank(body_tsvector, query) as rank FROM fulltextsearch.documents, to_tsquery('italian', 'torino') as query WHERE to_tsvector('italian', coalesce(body,'')) @@ … -
Multiple repeat error while validating email in django
i started learning Django a couple of days ago.Today i was learning forms with Django and everything was going well until i encountered the re repeat error during email validation.I tried multiple ways to solve this issue but failed. if anybody know how to fix this error,i'll be very thankful. below is my re code snippet import re regex = '^\w+(\.-]?\w+)*@\w+([\.-]?\w+*(\.\w{2,3})+$' if not re.search(regex,email): errorflag = True errormsg = "Not a valid email address" Errors.append(errormsg) if errorflag != True: dictionary["success"] = True dictionary["successmsg"] = "Form Submitted" -
What do I write in the views.py for my dashboard?
I am trying to create a system where users can register their complaints and view and edit them as well. They can also view other people's complaints but not edit them. This is how my dashboard should look. I need to show the number of complaints that are registered by the user so far in the white box but I don't know how. could someone please tell me how to do that? models.py: class Profile(models.Model): user = models.OneToOneField(User,null= True , blank = True, on_delete= models.CASCADE) profile_pic = models.ImageField(default = "msi.jpg", null = True, blank= True, upload_to= 'static/profileimages') first = models.CharField(max_length=500, null=True) last = models.CharField(max_length=500, null=True) email = models.CharField(max_length=500, null=True) mobile_number = models.IntegerField(null=True) location = models.CharField(max_length= 500, null= True) postal = models.IntegerField(null=True) def __str__(self): return self.first class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def … -
Django's sync_to_async and mypy
It seems that mypy doesn't really grok sync_to_async. For example, in the following code: @sync_to_async def get_point(...) -> Point: ... def other_func(): point = await get_point() I get the warning Class 'Point' does not define '__await__' so the 'await' operator cannot be used on its instance. What's the simplest way to add a correct type definition for sync_to_async? (Which is preferable to just ignoring the error) -
Get row separately for each category - django ORM
I have the following models: class Category(models.Model): name = models.CharField(max_length=100, null=False, blank=False) description = models.CharField(max_length=500, null=True, blank=True) class Website(models.Model): ... category = models.ManyToManyField('Category', related_name='website_category') ... Since each website can have multiple categories so I want to fetch each website multiple times for each category. For example: website 1 has categories: Category 1, Category 2 website 2 has categories: Category 2, Category 3 Required Output: Website Category website 1 category 1 website 1 category 2 website 2 category 2 website 2 category 3 I'm relatively new to Django ORM and unable to construct a query to fetch the desired results, so any help would be highly appreciable. -
How to access (previous or next) element and compare values in django template
I was working with a django app that built under a machine learning model and its pulling data from a joblib dump file. Everything was fine but I am getting error while accessing previous element in the template for loop. My views.py written as- Is there any way to access previous index and compare values for this particular problem? Please let me know. Thanks in advance :) -
django read mp3 file and send it as response
views.py from . import models, serializers from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.views import APIView class getSongData(APIView): serializer_class=serializers.SongSerializer def get(self, request, id, format=None): serializer = serializers.SongSerializer(models.Song.objects.get(id=id)) file_loc = serializer.data['audio_file'] # go below to see the data # read the mp3 file return Response(file_data) urls.py from django.urls import path from . import views urlpatterns = [ path('songs/audio/<int:id>', views.getSongData.as_view(), name='audio') ] serializers.py from rest_framework import serializers from . import models class SongSerializer(serializers.ModelSerializer): class Meta: model = models.Song fields = '__all__' models.py from django.db import models from datetime import datetime class Song(models.Model): title = models.CharField(max_length=64) audio_file = models.FileField() genre = models.CharField(max_length=64) created_at = models.DateTimeField(default=datetime.utcnow) The data [ { "id": 1, "title": "Kubbi | Cascade", "audio_file": "/media/Kubbi__Cascade.mp3", "genre": "Instrumental", "created_at": "2021-07-24T10:21:48Z" } ] When the user clicks on a song (lets say the song's id=1), a request gets sent to 'http://localhost:8000/api/songs/audio/1' then in views.py I extract the song's location via serializer.data['audio_file'] which is = "/media/Kubbi__Cascade.mp3", all i want to do is to read this audio file and send the data as a Response back to the frontend, I tried many solutions but they were throwing errors... -
Django changes is not reflecting on the browser
It's my second day of Django and everything seems to be going petty well. Though the installation process is a bit longer, I still find it friendly to get started with. I am currently learning how to pass data to static file from views.py. The problem I am having is that it is only showing the previous changes not the recent. I have hard-refresh but still not working. I don't know how to stop and rerun the server because I don't know how to combine both Ctr + BREAK. -
Static image in django not loading in browser
my image static file is not loading in browser. settings.py--- BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True INSTALLED_APPS = [ ---, 'django.contrib.staticfiles', --- ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR / 'static_dir'), ] STATIC_ROOT = os.path.join(BASE_DIR / "static_root") urls.py-- from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',mainApp.views.home, name='home') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) main.html-- {% load static %} <div> <p> <a href="#" class="btn btn-primary my-2">LinkedIn </a> <a href="mailto:xxxxxxx@gmail.com" class="btn btn-secondary my-2">Email Me</a> </p> <img scr="{% static 'me.JPG' %}" width='200' height='250'></img> </div> I have used similar .js and .css paths and they are working. The image is not loading in browser . but the image scr on inspecting the element shows <img scr="/static/me.JPG" width="200" height="250"> on loading 127.0.0.1:8000/static/me.JPG it is successfully showing the image. -
Using Smartsheet API: How do I access user data after a user is authenticated and taken to redirect url?
Context: I integrated a Node.js Smartsheet Oauth flow into my Django app by having the login button in django direct the user to the /auth url on the Node server. Once the flow is done and user logs in through Smartsheet, the redirect URL from the Smartsheet dev tools takes the user back to the Django website. Objective: I am trying to access the user data, so that before they log in a variable called user = undefined, and after they log in the variable called user is an object with a set of user data that comes from the smartsheet API. This object would include: id, email, first name, last name, etc... I have tried a few approaches: I tried to fetch data from the /callback url where the OAuth flow generates and saves token data, but I get rejections, maybe due to thoughtful security protocall Ive tried to play with "raw token requests" for current user, maybe accessing them from the Node.js server and then sending data back through a post request. I haven't get it working and it seems incorrect to post user data as it comes, and have the django app try to match the user … -
Compressed CSS files generated by django-compressor/libsass are not served on the first launch of the server, but are served on subsequent launches
I'm working on a Django app for the first time and I had reached a stage where I was feeling comfortable with the app's functioning in the development environment. To deploy I had to set DEBUG=False which brought some challenges. I learnt that the production servers won't serve static files the same way the development server does. I learnt the use of the py manage.py collectstatic command. I set up WhiteNoise, and upto this point I had no issues running the app in the development server with DEBUG=False. The last hurdle that remained was to serve scss files, as css. For this I used the django-libsass module. I setup the django-compressor, adding 'compressor' to list of INSTALLED_APPS, setting STATICFILES_FINDERS and COMPRESS_PRECOMPILERS as follows: STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ] COMPRESS_PRECOMPILERS = ( ('text/x-scss', 'django_libsass.SassCompiler'), ) Finally, I updated the template with the required {% compress css %} tags. On running collectstatic I notice that the files are generated in the appropriate folder /static/CACHE/css/output.RANDOM_NUM.css. This is where the odd issue happens. The first time I run the development server, the CSS file isn't served: WARNING - Not Found: /static/CACHE/css/output.RANDOM_NUMBER.css The request returns a 404. This is despite me being able … -
Django app button with two functionalities
I am building a Django app and on one of the HTML sheets I have a submit button that runs a function in views.py when clicked. <input type="submit" id="senden" class="inputfiles"/> <button for="senden" class="button" id="weiter_btn" >Submit</button> But I want it to first run a javascript function on the client-side and then go on and run the function in views.py. I tried to add onclick to the button element but that didn't work. <input type="submit" id="senden" class="inputfiles"/> <button for="senden" onclick="example()" class="button" id="weiter_btn" >Submit</button> Should I maybe create another hidden button that runs the js function and then somehow connect it to the submit button? -
Django Upload Folder is always Empty (This field is required issue)
I would like to upload a folder to my application but on the server side the request.FILES collection is always empty. Also form.is_valid doesn't work The solution for this problem seems to be to add enctype="multipart/form-data" but I have already added it an it doesn't work. Inside the browser I also get "This field is required" after pressing submit and yes I have choosen a directory. Here is my Dataset Model # Create your models here. class Datasets(models.Model): dataset_name = models.CharField(max_length=100, blank=True, null=True) description = models.CharField(max_length=1000, blank=True, null=True) share_with = models.ManyToManyField(User) uploaded_by = models.CharField(max_length=1000, blank=True, null=True) upvotes = models.IntegerField(null=False, default=0) downvotes = models.IntegerField(null=False, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) datafiles = models.FileField(blank=True, null=True) This is my form.py class UploadDatasetForm(forms.Form): dataset_name = forms.CharField( max_length=1000, widget=forms.TextInput(attrs={'class': 'form-control'})) description = forms.CharField( max_length=1000, widget=forms.TextInput(attrs={'class': 'form-control'})) share_with = forms.MultipleChoiceField( choices=tuple(UserProfile.objects.values_list('id', 'full_name')), widget=forms.CheckboxSelectMultiple, ) datafiles = forms.FileField(widget=forms.ClearableFileInput( attrs={ 'multiple': True, 'webkitdirectory': True, 'directory': True, })) My HTML-Template {% block content %} <h2>Register Here</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Register</button> </form> And here is my view.py @login_required def upload_dataset(request): print(request.user) form = UploadDatasetForm() if request.method == "POST": print('Receiving a post request') form = UploadDatasetForm(request.POST, request.FILES) print(request.FILES) if form.is_valid(): print("The form is … -
Get empty row after importing a dataset
I am importing a file with django-import-export and I want to take the values of each row. def get_import_data(file): hr_dataset = Dataset() return hr_dataset.load(file.read(), format='xlsx', headers=True) def upload_hr_file(request): if request.method == 'POST': hr_file = request.FILES['hr-file'] data = get_import_data(hr_file) hr_resource = HREmployeeResource() result = hr_resource.import_data(data, dry_run=True, raise_errors=True) if not result.has_errors(): result = hr_resource.import_data(data, dry_run=False, raise_errors=True) for row in result.rows: print(row.raw_values) return render(request, 'core/upload-hr-file.html', {}) I iterate through the rows of the Result with result.rows and each row seems to have a raw_values property but it returns an empty dict. Please, how can access the values of each row? Thank you in advance. -
How do I avoid invalidating my CDN cache whenever I add a new blog post to my database?
I am using Django REST API as a backend to a blog, with the front end in React hosted separately. I have the React front end behind Cloudfront, acting as a CDN. Whenever I want to add a new blog post / add any new record in my DB, I need to invalidate my cache for it to actually appear on the site. I understand why this happens. I want to know how I can avoid this, and still get the benefits of caching without wiping my whole cache everytime I want to see my new content. -
Django filter ORM Q
I write this query day_l = DAYLeave.objects.filter(user=request.user, Q(start_date__range=[sd, ed]) | Q(end_date__range=[sd, ed])) sd and ed are Date like '2021-04-06' when I execute I get this error SyntaxError: positional argument follows keyword argument user ---> foreignkey User table if I remove user=request.user its work but my main query I get error -
How to get Jenkins to show on port 8080 with Nginx, Gunicorn?
I'm trying to set up Jenkins so that I can set up a pipeline on an existing website, but Jenkins does not show up on port 8080. My project website has been up and running for several months. I'm using Nginx, Gunicorn, Ubuntu 20.04, and Django on an AWS EC2 instance. I'm now trying to set up a pipeline that includes a test/beta environment. This requires Jenkins as per the AWS tutorials. I followed the example from Digital Ocean and this example from Digital Ocean. When I try the URL https://theafricankinshipreunion.com:8080/, it says the site cannot be reached. When I try the URL https://theafricankinshipreunion.com (without the port), it takes me to the Unlock Jenkins page. After I enter the password from sudo cat /var/lib/jenkins/secrets/initialAdminPassword, the web browser just goes to a blank page. Looking at the page source, this page is the Setup Wizard[Jenkins] page, but the display is blank. The results from sudo systemctl status jenkins is active. The results from sudo ufw status for port 8080 is ALLOW. On AWS, the EC2 inbound rules inclues port 8080 TCP 0.0.0.0/0 and ::/0. So it appears that port 8080 is good. Checking for port use, netstat -nlp | grep 8080 … -
Django: Creating endpoint for fetching subcategories within a category
I am new to Django and wanted to create an endpoint that allows me to push all the existing subcategories within a category. I have seen methods where one can fetch specific data points within a given category but I am confused about how to create such custom endpoints. Here's my Serializers: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'categoryType') class SubCategorySerializer(serializers.ModelSerializer): categoryTitle = serializers.CharField(source="categoryType.categoryType", read_only=True) class Meta: model = SubCategory fields = ('id', 'categoryTitle', 'subcategoryType') #fields = '__all__' Here's my model: class Category(models.Model): categoryType = models.CharField(max_length=100,blank = False, unique = True, null = False) def __str__(self): return self.categoryType class SubCategory(models.Model): subcategoryType = models.CharField(max_length=100) categoryType = models.ForeignKey(Category,on_delete=models.CASCADE, null = True, related_name='category_type') def __str__(self): return f'{self.categoryType} :: {self.subcategoryType}' When I hit subcategory endpoint, I get the data in following format: [ { "id": 2, "categoryTitle": "Electronics", "subcategoryType": "Mobile" }, { "id": 3, "categoryTitle": "Electronics", "subcategoryType": "Tablet" }, { "id": 4, "categoryTitle": "Electronics", "subcategoryType": "HardDisk" }, { "id": 5, "categoryTitle": "Electronics", "subcategoryType": "Laptop" }, { "id": 6, "categoryTitle": "Sports", "subcategoryType": "Tennis" }, { "id": 7, "categoryTitle": "Sports", "subcategoryType": "Cricket" }, { "id": 8, "categoryTitle": "Sports", "subcategoryType": "Football" }, { "id": 9, "categoryTitle": "Sports", "subcategoryType": "BasketBall" } ] but what … -
Need TableField option in Django
I'm planning to create a page for mechanical design. The page will have lot of calculations. Assume for car design the user can add lot of design files, like engine design, exhaust design, brake design, etc. class DesignFile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_("File Name"), blank=True, max_length=255) calc_type = models.TextField(verbose_name="Calculation Type") User can create the file like, DesignFile(name='AudiEngine', calc_type='Engine') DesignFile(name='BMWEngine', calc_type='Engine') DesignFile(name='BMWExhaust', calc_type='Exhaust') DesignFile(name='GeneralBrake', calc_type='Brake') DesignFile(name='HandBrake', calc_type='Brake') Also i have different models for each calculations because all the inputs will be different. And Each calculations will have many rows. class EngineTable(models.Model): file = ForeignKey(DesignFile) class EngineRow(models.Model): table = ForeignKey(EngineTable) bore_dia = models.IntegerField() stoke_length = models.IntegerField() ... class BrakeTable(models.Model): file = ForeignKey(DesignFile) class BrakeRow(models.Model): table = ForeignKey(BrakeTable) material = models.CharField(max_length=30, blank=True, null=True) shoe_type = models.CharField(max_length=30, blank=True, null=True) ... So each calculation will link with any one DesignTable, and in that design there will be many rows linked to it. My Doubt is how to dynamically link the DesignFile to different Table model. I need kind of TableField in django. And I am using Django Rest Framework, So if I got to DesignFile it should give all the rows to that particular calculation -
Schedule a task on given date and time using Dango qcluster
I am trying to create events on given date and time using django qcluster but I am having trouble with as I do not have much experience with qcluster. what I am trying is- from django_q.tasks import schedule def event_scheduler(event_id, meeting): meeting_object = Event.objects.get(event_id) time = meeting_object.schedule_time # schedule event at this time task = schedule(meeting.start(), schedule_type=Schedule.ONCE, repeats=1, next_run=() #time for creating event example: 5 UTC 25 July 2021 ) How do i put '5 UTC 25 July 2021' on next run ? or is my method correct ? -
Can I easily retrospectively link ReactJS code to Django
I am writing my A-level computer science project and am looking to write the front end of an inventory management system with ReactJS. I am looking to start by writing the backend in Django, as I do not currently know much JavaScript. The question I am asking is whether it would be feasible to write the Django back-end now, and link in a JavaScript-based front end later using the Django REST API after the back-end has already been written. If I were to do this, is there anything I need to bear in mind? Sorry if this is a dumb question, I am very new to full-stack development. Any help is appreciated :) -
How to display strings containing a "\n" in Django HTML template
I can not find a way to use string variable containing a \n in Django HTML templates. This is my template: <body> <textarea id="my-text"></textarea> </body> <script> document.getElementById("my-text").value = "{{ message }}"; </script> with message = "Message containing a \n character" When Django renders the template, it generates an HTML like this one: <body> <textarea id="my-text"></textarea> </body> <script> document.getElementById("my-text").value = "Message containing a character"; </script> and the Javascript does not work. Is there a way to fix this? -
Django makemigrations KeyError: 'content_type'
Last time I changed the data model locally and tried to push it to production and migrate the database there I've got the following response from the makemigrations command: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/JoshuaMSchmidt/.virtualenvs/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/JoshuaMSchmidt/.virtualenvs/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/JoshuaMSchmidt/.virtualenvs/env/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/JoshuaMSchmidt/.virtualenvs/env/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/JoshuaMSchmidt/.virtualenvs/env/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/home/JoshuaMSchmidt/.virtualenvs/env/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 201, in handle pre_migrate_state = executor._create_project_state(with_applied_migrations=True) File "/home/JoshuaMSchmidt/.virtualenvs/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 79, in _create_project_state migration.mutate_state(state, preserve=False) File "/home/JoshuaMSchmidt/.virtualenvs/env/lib/python3.7/site-packages/django/db/migrations/migration.py", line 87, in mutate_state operation.state_forwards(self.app_label, new_state) File "/home/JoshuaMSchmidt/.virtualenvs/env/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 158, in state_forwards old_field = model_state.fields.pop(self.name) KeyError: 'content_type' Now I am not able to move forward or backwards and am stuck with the current data model on the server. Can I somehow drop all old migration files from the production server and start again clean from the current database? To be honest I am not really sure what the Error means Happy to supply additional Information as I also dont really know where to start. -
Details not showing up - Can someone please tell me what is wrong with my code?
I am creating a system where the user can view others complaints and view the complaint details as well but not edit them. views.py: class ViewParticularComplaint(TemplateView): model = Complaint form_class = ComplaintForm template_name = 'viewusercompaint.html' def get_queryset(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["complaints"] = self.model.objects.exclude(user = self.request.user) return context template: <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <p class="sub-typ-wr">Submit Type</p> <a href="/Login/Add-Complaint/Document-Style/"><button type="button" class="btn btn-secondary document-btn">Document</button></a> <div class="rep-num"> <label class="written-label" for="">Report Number</label> <div class="written-txt-field">{{complaints.reportnumber}}</div> </div> <div class="eve-dte"> <label class="written-label" for="">Event Date</label> <div class="written-txt-field">{{form.eventdate}}</div> </div> <div class="eve-typ"> <label class="written-label" for="">Event Type</label> <div class="written-txt-field">{{form.event_type}}</div> </div> <div class="dev-pro"> <label class="written-label" for="">Device Problem</label> <div class="written-txt-field">{{form.device_problem}}</div> </div> <label class="written-label eve-txt" for="">Event Text</label> <div class="Manufacturer"> <label class="written-label" for="">Manufacturer</label> <div class="written-txt-field">{{form.manufacturer}}</div> </div> <div class="pro-code"> <label class="written-label" for="">Product Code</label> <div class="written-txt-field">{{form.product_code}}</div> </div> <div class="brand-name"> <label class="written-label" for="">Brand Name</label> <div class="written-txt-field">{{form.brand_name}}</div> </div> <div class="exem"> <label class="written-label" for="">Exemption</label> <div class="written-txt-field">{{form.exemption}}</div> </div> <div class="pat-pro"> <label class="written-label" for="">Patient Problem</label> <div class="written-txt-field">{{form.patient_problem}}</div> </div> <div class="comp-textarea">{{form.event_text}}</div> <button type="button" class="btn btn-secondary attach-btn-1"><div class="fas fa-file-upload">{{form.document}}</div></button> </form> what should be seen is: something like this without the save button and stuff. But what I'm actually seeing is: What is the issue and how do I solve it?? -
I initially set my default PK as 0 in my Django model, and now makemigrations causes this error, even after changing the default to 1
I have now changed the default pk to be 1 but I continue to get this error which I am unable to fix. There is no owner field in the table yet, so I am very confused as to why it is unable to migrate and why it does not just set the default value to be 1 on every row (this is my superuser). To me it seems like it shouldn't be trying to set a value of 0, yet it still seems to be attempting to do this owner = ForeignKey( User, related_name='artist_owner', on_delete=CASCADE, default=1 ) psycopg2.errors.ForeignKeyViolation: insert or update on table "artists_artist" violates foreign key constraint "artists_artist_owner_id_90f328a8_fk_jwt_auth_user_id" DETAIL: Key (owner_id)=(0) is not present in table "jwt_auth_user".