Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't run compress in django app deployed with heroku
I am trying to deploy a Django 3.2.4 app on heroku, with django-compressor 2.4.1. I wanted heroku to compress the files, so I ignored my local compress directory and added a post-compile file, as specified here. Here is the build log Compressing static files Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: ... other stuff File "/app/.heroku/python/lib/python3.9/site-packages/django/template/backends/django.py", line 123, in get_package_libraries raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'compressor.templatetags.private_static': cannot import name 'PrivateFileSystemFinder' from 'compressor.finders' (/app/.heroku/python/lib/python3.9/site-packages/compressor/finders.py) ! Push rejected, failed to compile Python app. ! Push failed I followed the steps for setting up django-compressor as per the docs. -
Applying filter to queryset only when query is provided in Django
Let's say I have a model called Article with the field title. I have a method that returns a queryset for this model, and the method takes an optional argument called query which if provided, is used to filter out the queryset. So something like this: def get_articles(query=None): if query: return Article.objects.filter(title__icontains=query) else: return Article.objects.all() This works fine, but notice how this method has two return statements, as in, I'm writing out two separate queries. Is there a way to do this in one go? In other words, the ideal scenario would be writing just one query instead of two. Thanks for any help. -
Is it possible to create my own domain email with django and Amazon SES?
I'm creating a site using Django and hosting it with Amazon EC2. My domain is managed by Namecheap, and they charge for email forwarding. I was thinking if there's a way to create a mailbox inside the django project, in order to validate an email that uses my own domain so I can forward it without using Namecheap service. I found projects like Django-mailbox and Django-ses but they seem to only manage emails that already exists. Thank you -
Django slow query with a nullable Foreignkey
Imagine we have this two models class Offer(models.Model): fetch_datetime = models.DateTimeField(db_index=True) tracking = models.ForeignKey(Tracking, models.SET_NULL, blank=True, null=True) class Tracking(models.Model): MANUAL = "Manual" AUTO = "Auto" UNMATCHED = "Unmatched" MATCHING_TYPES = [(MANUAL, "Matched by a human"), (AUTO, "Matched by a computer"), (UNMATCHED, "Not matched")] matching_status = models.CharField(max_length=10, choices=MATCHING_TYPES, default=UNMATCHED) And we want to query like this Offer.objects.filter(fetch_datetime__range=(now_minus_14days, now)) .select_related('tracking') .filter(tracking__matching_status__iexact="manual") .annotate( fetch_day=Cast("fetch_datetime", DateField()) ) When the query is executed with the default index that django creates on the field Offer.tracking the query is so slow. On the other hand, when we get rid of this index, the query is fast. I'm so confused. Anybody can give a solution? Thank's in advance -
How can I use CSS on form.ImageFiled in Django?
I would like to apply CSS to form.ImageFiled in Django same as Charfeild but I got the error. File "/Users/hogehoge/Desktop/hoge/hoge/forms.py", line 42, in PostForm photo = forms.ImageField(label='Image', validators=[file_size],widget=forms.ImageField(attrs={'class': 'fileinput'})) File "/Users/hoge/opt/anaconda3/lib/python3.8/site-packages/django/forms/fields.py", line 545, in __init__ super().__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'attrs' How can I apply CSS CSS on form.ImageFiled? forms.py photo = forms.ImageField(label='Image', validators=[file_size],widget=forms.ImageField(attrs={'class': 'fileinput'})) html <div class="col-8 col-lg-4">{{ form.photo }}</div> -
Django Image Processing/Serving to improve page speed
I am building a site that has a piece of functionality that is pulling images from the Instagram API and they are being flagged up as the main issue in pagespeed insights. The site is here: http://demo.emmawedgwoodaesthetics.co.uk/ and the problematic page speed is here  If I hover on one of the images in devtools it shows me this:  Okay so my understanding is that the files size is too big and I need to serve a smaller file. Facebooks/Instagram Documentation is super bad and I cant find a way there to ask for a smaller image. My template has this: <div class="carousel ml-10p" x-ref="carousel"> {% for post in instafeed%} <div class="w-3/5 h-10v pr-5 "><img class="rounded-3xl shadow-xl w-40 h-40 " src="{{ post.media_url}}" alt=""></div> {% endfor %} </div> The w-40 h-40 are what is rendering the 160x160. So how do I solve this problem? I am thinking I need to use an image processing third party package? Do I need to? I am thinking the minimum requirement is take a set of image_urls from instagram(1440 x 1440) convert them to smaller images on the server and then serve those in the view. I have been looking at sorl-thumbnail, django-imagekit and … -
i keep on receiving ('NoneType' object has no attribute 'price') as an error in server
i keep on receiving the error ('NoneType' object has no attribute 'price') on my server and i have no idea how to remove it or what the problem is, i added a product in my admin and then i removed it in my admin but that item was in my cart so when i refreshed my cart i got that error in my server this is my models.py class Shoe(models.Model): brands = models.ForeignKey(Brands, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) price = models.DecimalField(max_digits=7, decimal_places=2) image_1 = models.ImageField(null=True, blank=True) class Cart(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) complete = models.BooleanField(default=False) date_ordered = models.DateTimeField(auto_now_add=True, null=True) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): cartitems = self.cartitem_set.all() total = sum([item.get_total for item in cartitems]) return total @property def get_cart_items(self): cartitems = self.cartitem_set.all() total = sum([item.quantity for item in cartitems]) return total @property def shipping(self): shipping = True cartitems = self.cartitem_set.all() return shipping, cartitems class CartItem(models.Model): shoe = models.ForeignKey(Shoe, on_delete=models.SET_NULL, blank=True, null=True) cart = models.ForeignKey(Cart, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True, null=True) @property def get_total(self): total = self.shoe.price * self.quantity return total -
a generic class for the creation, modification or deletion of objectsz in django
from django.contrib.auth.models import AbstractUser from django.db.models import Model class Repository(object): def init(self, model: Model or AbstractUser): self.model = Model def list(self): return self.model.objects.all() def retreive(self, _id: int): return self.model.objects.get(id=_id) def put(self, _id: int, data: dict): _object = self.model.objects.get(_id) if _object is None: return Exception('object not found') else: for i in data: if hasattr(_object, i) and getattr(_object, i) != data[i]: setattr(_object, i, data[i]) _object.save() return _object def create(self, data: dict): return self.model.objects.create(**data) def delete(self, _id): return self.model.objects.get(_id).delete() -
foreign key in django
I have a model for musics and a model for comment of musics: class music(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) STATUS_CHOICES = (('draft', 'Draft'), ('published', 'Published'),) music = models.FileField() music_image = models.ImageField(upload_to="images/") singer_name = models.CharField(max_length=100) music_name = models.CharField(max_length=100) text_of_music = models.TextField() create = models.DateField(auto_now_add=True, blank=True, null=True) update = models.DateField(auto_now=True, blank=True, null=True) publish = models.DateField(default=timezone.now, blank=True, null=True) slug = models.CharField(max_length=250, unique_for_date='publish') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def get_absolute_url(self): return reverse('music:music_detail', kwargs={"id":self.id}) class comment(models.Model): # Foreignkey for each music For = models.ForeignKey(music, on_delete=models.CASCADE, related_name='post') body = models.CharField(max_length=500) created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) commented_by = models.ForeignKey(User, on_delete=models.CASCADE) and this is my view: def music_Detail(request, id=None): user = request.user template_name = 'music/music_detail.html' Music = music.objects.all().filter(id=id) new_comment = None Comment = comment.objects.all().filter(active=True) form = comment_form(data=request.POST) if request.method == 'POST': if form.is_valid(): new_comment = form.save(commit=False) new_comment.For = Music new_comment.save() form = comment_form() return render(request, template_name, {'Music': Music, 'Comment': Comment, 'form': form}) Well, I get this error when I comment: Cannot assign "<QuerySet [<music: m, majid kharatha>]>": "comment.For" must be a "music" instance. How can I solve this problem and how can I display the information of the user who left this comment? -
paypal user login page (page after clicking the paypal button) reloads indefinitely, after adding "&vault=true&intent=subscription"
I am integrating PayPal for subscription related service, I have earlier implemented for single time payment by adding the Paypal button via adding the script <script src="https://www.paypal.com/sdk/js?client-id=SB_CLIENT_ID"></script> but for subscription as per the documentation https://developer.paypal.com/docs/subscriptions/integrate/#subscriptions-with-smart-payment-buttons we are supposed to add &vault=true&intent=subscription also thus making it <script src="https://www.paypal.com/sdk/js?client id=SB_CLIENT_ID&vault=true&intent=subscription"></script> but after adding this I get the following error in the chrome console and the login page reloads indefinitely Failed to load resource: the server responded with a status of 400 (Bad Request) -
Can't updating an object from serializer DRF
I'm trying to update the balance each time that I create a transaction. so far I have tried this but it isn't working. What I'm trying is to check the type of transaction, 1 means is an income and 2 means that is an expense, next I get the object filtering from the user id that in the balance model filed is call user_id, to later add or take away to the amount the incoming data depending on the transaction type. Model class Balance(models.Model): balance = models.FloatField( verbose_name="Balance", blank=False, null=False) user_id = models.ForeignKey( 'expenseApi.Users', verbose_name="Usuario", blank=False, null=False, on_delete=models.PROTECT) def __str__(self): return '{}'.format(self.pk) serializer class TransactionsSerializer(serializers.ModelSerializer): user_id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Transactions fields = ['type', 'user_id', 'description', 'amount', 'id'] def create(self, request, validated_data): user = self.context['request'].user balanceObj = Balance.objects.get(user_id=user) if self.context["view"].kwargs['type'] == 1: balanceObj.balance = F('balance') + self.context["view"].kwargs['amount'] balanceObj.save() if self.context["view"].kwargs['type'] == 2: balanceObj.balance = F('balance') - self.context["view"].kwargs['amount'] balanceObj.save() return super().create(**validated_data) The balance object is created when a user is created.And it is asing an amount of 0 class RegisterSerializer(serializers.ModelSerializer): tokens = serializers.SerializerMethodField() email = serializers.EmailField(max_length=50) balance = serializers.SerializerMethodField() class Meta: model = Users fields= ['id', 'email', 'password', 'name', 'lastname', 'birthday', 'tokens', 'balance'] extra_kwargs = { 'password': { 'write_only': … -
I am new to django and i am trying to make a get request to a path to list all the fields of a model but getting errors
My models.py from django.db import models # Create your models here. class LiveClass(models.Model): standard = models.IntegerField() no_of_students_registered = models.IntegerField(default=0) class Meta: verbose_name_plural = 'Class' class User_details(models.Model): name = models.CharField(max_length=30) standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) email = models.EmailField(max_length=30) mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' class Mentor(models.Model): name = models.CharField(max_length=30) standard = models.ManyToManyField(LiveClass) details = models.TextField() class Meta: verbose_name_plural = 'Mentors' class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_name = models.CharField(max_length=30) chapter_details = models.TextField() mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) class_time = models.DateTimeField() class Meta: verbose_name_plural = 'LiveClass_details' class LiveClass_registration(models.Model): class_details = models.OneToOneField(LiveClass_details, on_delete=models.CASCADE) name = models.OneToOneField(User_details, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'LiveClass_registration' This is serializer for all my models , please tell a way to reduce the code in it as all of it is a repetition my Serializer.py from rest_framework import serializers from . import models class LiveClass_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass fields = '__all__' class User_details_serializer(serializers.ModelSerializer): class Meta: model = models.User_details fields = '__all__' class LiveClass_details_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass_details fields = '__all__' class Mentor_serializer(serializers.ModelSerializer): class Meta: model = models.Mentor fields = '__all__' class LiveClass_registration_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass_registration fields = '__all__' my urls.py from django.urls import path, include from . import views urlpatterns = [ path('liveclass/', … -
Django Create multiple views
I am new to django.I have to create multiple views and create buttons for them in the main page. I have to create different view for different filter of the table.My main page show 404 error and my app page only shows one view(the first one linked in urls.py). hereis my code: views.py from django_tables2 import SingleTableView from django.db.models import Max from django.db.models import Min from .models import airdata from .tables import AirdataTable class AirdataListView(SingleTableView): model = airdata table_class = AirdataTable template_name = 'dashboard/data.html' q = airdata.objects.aggregate(alpha=Min('pol_max'))['alpha'] queryset = airdata.objects.filter(pol_min= q).order_by('-state') class AirdataListView2(SingleTableView): model = airdata table_class = AirdataTable template_name = 'dashboard/data2.html' q = airdata.objects.aggregate(alpha=Max('pol_max'))['alpha'] queryset = airdata.objects.filter(pol_min= q).order_by('-state') urls.py from django.urls import path from . import views from .views import AirdataListView,AirdataListView2 urlpatterns = [ path('', AirdataListView2.as_view()), path('', AirdataListView.as_view()), ] template {% load render_table from django_tables2 %} <!doctype html> <html> <head> <title>Air Data</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> </head> <body> {% render_table table %} </body> </html> -
django and postgres what is the alternative to uuid
I want all of the ID fields of all model classes(tables) in my Django project to be unique. by unique I mean unique throughout all of the tables, not just one table. I don't wanna use UUID due to the performance and storage issues and actually I don't need my Id fields to be that kind of unique I just want them to be probably a 5 or 6 digit unique number in 30 tables. my database is Postgres. Why I need it: assume that there are 3 tables: news, article, and tag. I want to assign multiple tags to news or articles. so I store tag_id and news_id or article_id in another table called typetag. so news and articles can not have similar ids as the django auto-incrementing primary key generates. how would I tackle this problem? -
Django How To Get Current Logged In User's Form Input On Database
I have been making a website where a user logs in, and then they fill a form describing themselves further (what city they are in, which neighbourhood, which category, their description), then that input is collected into the database. Currently, the user logs in, but when they fill a form, the database doesn't store their username, meaning that they cannot edit their profile informations. Right now, I can only determine each input's user manually on Django admin, and I would like it to be automatic through simple code. Here is my models.py class Usta(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) website = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) telefon = models.CharField(max_length=200, null=True) desc = models.TextField(max_length=1000, null=True) il = models.ForeignKey(Il, on_delete=models.SET_NULL, null=True) ilce = models.ForeignKey(Ilce, on_delete=models.SET_NULL, null=True) image = models.ImageField(default='ananas.jpg', upload_to='profile_images') def __str__(self): return self.name Here is my views.py def createUsta(request): form = UstaForm() if request.method == 'POST': #print('Printing POST:', request.POST) form = UstaForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'form.html', context) Here is my forms.py class UstaForm(ModelForm): class Meta: model = Usta fields = ('name', 'category', 'il','ilce', 'website', 'email', 'desc', 'telefon', 'image') Here is my HTML (forms.html) for logged … -
Generate pdf from embedded Kibana dashboards from the Frontend
I'm trying to build a portal with Django and React. I'm also using Elasticsearch + Kibana. The situation : I've made 2 dashboards in Kibana and put those dashes in the react app (via iFrame method). Everything is fine up so far. The problem : I want to generate a pdf or ppt document, containing those Kibana dashboards and let the user download it. I know Kibana has a paid option to generate a pdf from dashboards but that's not possible in my case, plus it is from the Kibana interface. I've tried to use libraries like revealJS and puppeteer or take screenshots programmatically and insert them into pdf files but none seem to work (CORs errors in most cases, screenshots made don't display the content of the iframes). The last thing I tried was : https://www.geeksforgeeks.org/how-to-take-screenshot-of-a-div-using-javascript/ Thank you for your answers. -
Is djangorestframework-jwt not good for http, https?
I am trying to build an API server for http and started off with djangorestframework and someone suggested using djangorestframework-jwt. However, I saw this from their homepage. Unlike some more typical uses of JWTs, this module only generates authentication tokens that will verify the user who is requesting one of your DRF protected API resources. The actual request parameters themselves are not included in the JWT claims which means they are not signed and may be tampered with. You should only expose your API endpoints over SSL/TLS to protect against content tampering and certain kinds of replay attacks. Does djangorestframework-jwt work for http and https? Is it safe? If not, what is the alternative? Is this the approach for authentication in a REST API? -
Need An Query from Django Model
I have created two models in Django from which I want to make a query First Parties Model class Party(models.Model): name = models.CharField(max_length=30, unique=True) contact = models.CharField(max_length=13) opening_Balance = models.FloatField() current_Balance = models.FloatField(blank=True, null=True) date = models.DateField(default=timezone.now, blank=True) Second is the dispatch where I will dispatch my product in inventory: class DirectCompanyRecieve(models.Model): date = models.DateField(default=timezone.now, blank=True) slug = models.SlugField(null=True, blank=True, default='none5lucky-cement') orderStatus = models.CharField(max_length=50, choices=[( 'Pending', 'Pending'), ('Received', 'Received'), ('Dispatched', 'Dispatched')], default='Pending') company = models.ForeignKey(Company, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) Destination = models.CharField(max_length=50) qty = models.IntegerField() rate = models.IntegerField() FrieghtPerTon = models.FloatField(null=True) Frieght_left = models.FloatField(null=True, blank=True) total_amount = models.FloatField(null=True, blank=True) company_lg_id = models.IntegerField(blank=True, null=True) wareHouse_lg_id = models.IntegerField(blank=True, null=True) Now I Need a query Like The 'BW', 'NW ', 'ML' etc are brand Names -
Django - conditional permissions - how to?
I'm trying to figure out how to (and if) use Django Groups/Permissions for cases when the permission depends on current user and it's attributes. class Team(..): ... class User(...): team = ... class Product(...): team = ... I have two Groups - admins and users. Let's say that I use DRF and I want any "admin" to see/fetch all product objects that belong to user's team and also update/delete. But I want regular user to be able only to retrieve (readonly) products. I'm thinking about creating permission: "can_edit_teams_products" Which would belong only to the admins group. But even if this was a common way to do that, how to check such permissions? It's not static, I need to get user.team when checking the permission. -
How to Use Materialize CSS Time Input with Django?
my current view - start_time = form.cleaned_data['start_time'] end_time = form.cleaned_data['end_time'] model - start_time = models.TimeField(auto_now=False, auto_now_add=False) end_time = models.TimeField(auto_now=False, auto_now_add=False) HTML - <input type="text" id="start_time" name="start_time" class="timepicker" placeholder="Start Time"> <input type="text" id="end_time" name="end_time" class="timepicker" placeholder="End Time"> Form Error I get : -
How do I use Graphql generated JWT to authenticate my rest_framework view?
I am using Graphql jwt to generate my token but I am not able to find a way to authenticate my rest_framework view using that token. -
Not able to use gensim module in Django
I have included the 2 import statements in my views.py from gensim.summarization.summarizer import summarizer from gensim.summarization import keywords However, even after I installed gensim using pip, I am getting the error: ModuleNotFoundError: No module named 'gensim.summarization' -
Django problem with form using action and not the if method == post in the view
So i am trying to add a value to the session dictionary because i wanted to make a cart/checkout for guests. This is the code in my views.py def productdetail(request, pk): Decks = decks.objects.get(id=pk) if request.method == 'POST': form = order(request.POST) if form.is_valid(): request.session['cart'] = [pk] else: form = order() return render(request, 'shop/single_product.html', {'deck': Decks, 'form': form}) And the code in my html <form action="{% url 'productdetailcart' deck.id%}" method="post"> {% csrf_token %} {{ form }} <input class="btn btn-lg btn-block btn-round btn-b" type="submit" value="Add To Cart"> Now my problem is that without the action in the form tag the session.['cart'] adds the value in the session which is what i want. But if i have the action to go to that url i only go to the url without adding the pk to the session.cart . Its like im forced to choose between going to the page or saving to session. -
Django Mongodb dumpdata not valid json format
We are using Django and MongoDB on our backend. We are also using Djongo to communicate with MongoDB. When running ./manage.py dumpdata > fixtures/db.json This produces a json dump that is not valid. The problem is that nested objects are not parsed correctly. { "model": "project.project", "pk": 1, "fields": { "name": "iiuyo", "project_type": "blank", "created_at": "2021-06-09T13:27:06.468Z", "modified_at": "2021-06-09T13:27:06.468Z", "account": 1, "status": "active" } }, { "model": "template.template", "pk": 1, "fields": { "data": "OrderedDict([('slides', [OrderedDict([('shapes', [OrderedDict([('type', 'image'), ('version', '3.6.3'), ('originX', 'left'), ('originY', 'top'), ('left', 0), ('top', 0), ('width', 960), ('height', 540), ('fill', 'rgb(0,0,0)'), ('stroke', None), ('strokeWidth', 0), ('strokeDashArray', None), ('strokeLineCap', 'butt'), ('strokeDashOffset', 0), ('strokeLineJoin', 'miter'), ('strokeMiterLimit', 4), ('scaleX', 1), ('scaleY', 1), ('angle', 0), ('flipX', False), ('flipY', False), ('opacity', 1), ('shadow', None), ('visible', True), ('clipTo', None), ('backgroundColor', '#fff'), ('fillRule', 'nonzero'), ('paintFirst', 'fill'), ('globalCompositeOperation', 'source-over'), ('transformMatrix', None), ('skewX', 0), ('skewY', 0), ('crossOrigin', ''), ('cropX', 0), ('cropY', 0), ('id', 'workarea'), ('name', ''), ('link', OrderedDict()), ('tooltip', OrderedDict([('enabled', False)])), ('layout', 'fixed'), ('workareaWidth', 600), ('workareaHeight', 400), ('src', ''), ('filters', [])]), OrderedDict([('type', 'chart'), ('version', '3.6.3'), ('originX', 'left'), ('originY', 'top'), ('left', 41.04), ('top', 33.12), ('width', 888.48), ('height', 450.2133070866142), ('fill', 'rgba(144,13,13,1)'), ('stroke', ''), ('strokeWidth', 1), ('strokeDashArray', None), ('strokeLineCap', 'butt'), ('strokeDashOffset', 0), ('strokeLineJoin', 'miter'), ('strokeMiterLimit', 4), ('scaleX', 1), ('scaleY', 1), ('angle', … -
OperationalError: no such table: django_content_type and django_session
I cannot access my app, when I enter the URL, it gives me the error OperationalError: no such table: django_session This usually means I need to migrate, or delete my sqlite database and redo migrations, so I did that multiple times. I deleted everything in the migrations folder and sqlite3.db and ran: python manage.py makemigrations app_name python manage.py migrate app_name No errors yet. Then after creating a superuser I run: python manage.py runserver It tells me 18 migrations have not been made, which I was able to fix with: python manage.py migrate --fake I try the site and again I get the no such table: django_session error. I read this thread Django: no such table: django_session and tried everything in it, including the approved solution, same error. Also, when I try to run the migrate command again, I get this error OperationalError: no such table: django_content_type so I went to this thread sqlite3.OperationalError: no such table: django_content_type once again, the solutions that worked for them did not work for me. This problem started after we migrated to MySQL, I tried to switch databases using a .env file, but ran into these problems, so I tried to switch back to sqlite …