Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
problem in connecting to mysql wamp and django?
I have a problem in connect mysql wamp to django using mysql connector Hi , I Have a database in mysql and i want to connect it to django with mysqlconnector library : I tries these : Step 1 : pip install mysqlconnector Step 2 : then change settings.py like this : DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'dbname', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } after this i run the server using : python manage.py runserver and at the end i got this error : Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x04B39C00> Traceback (most recent call last): File "C:\Users\p.mikaeil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\p.mikaeil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\p.mikaeil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\p.mikaeil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\p.mikaeil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\p.mikaeil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\p.mikaeil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\p.mikaeil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\p.mikaeil\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, … -
Reddit API is returning invalid_grant even though I'm not reusing the code
So this is a bug. What I want is simple: that the api returns the token. Here's a snippet of the code for the view: params = { "code": request.GET.get('code'), "state": request.GET.get('state'), } SESSION_STATE = request.session.get('state') CLIENT_AUTH = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET) if SESSION_STATE == params['state']: r = requests.post('https://www.reddit.com/api/v1/access_token', auth=CLIENT_AUTH, headers={ "User-Agent": "...", }, data={ "grant_type": "authorization_code", "code": params['code'], "redirect_uri": REDIRECT, }) I've seen the documentation. It says that if I'm getting the error, I must be using an old or expired code. However, it doesn't look like I'm doing so. -
Django post in nested serializer
I have 3 models :Workflow,WorkflowLevels,WorkflowLevelPermissions: models.py : class Workflow(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=32, default=None, null=True) description = models.CharField(max_length=100, default=None, null=True) tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, default=None, null=False) class Meta: unique_together = ('name', 'tenant',) class WorkflowLevel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) workflow = models.ForeignKey(Workflow, on_delete=models.CASCADE, related_name="levels", default=None, null=False) level = models.IntegerField(default=None, null=False) operation = models.CharField(max_length=32, default=None, null=False) class Meta: unique_together = ('workflow', 'level',) class WorkflowPermission(models.Model): short_name = models.CharField(max_length=32, primary_key=True, default=None, null=False) class WorkflowLevelPermission(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) level = models.ForeignKey(WorkflowLevel, on_delete=models.CASCADE, default=None, null=False, related_name = 'workflow_permissions' ) permission = models.ForeignKey(WorkflowPermission, on_delete=models.CASCADE, default=None, null=False) class Meta: unique_together = ('level', 'permission',) def short_name(self): return self.permission.short_name Im using nested seriarlizers to display Workflow data in this format .json: [ { "name": "test", "description": "Easy", "levels": [ { "level": 1, "operation": "AND", "workflow_permissions": [ { "short_name": "admin_approval" }, { "short_name": "coordinator_approval" } ] }, { "level": 2, "operation": "AND", "workflow_permissions": [] } ] } ] The serializers: class WorkflowPermissionSerializer (serializers.ModelSerializer): class Meta: model = WorkflowPermission fields = '__all__' class WorkflowLevelPermissionSerializer (serializers.ModelSerializer): short_name = serializers.SerializerMethodField('short_name') class Meta: model = WorkflowLevelPermission fields = ['short_name'] def short_name(self): return self.permission.short_name class WorkflowLevelSerializer (serializers.ModelSerializer): workflow_permissions = WorkflowLevelPermissionSerializer(many=True) class Meta: model = WorkflowLevel fields = ['level', 'operation', … -
Django command "python3 manage.py collectstatic --noinput" scrambling .py files when copying files to s3
I am trying to using Django collectstatic to send my script.py file to AWS S3. That file is then read by AWS Glue to execute Spark Job. When i manually upload the script.py, AWS Glue can read it properly. When i use the following command to send my script to AWS S3, the script.py gets scrambled python3 manage.py collectstatic --noinput Attaching screenshot of AWS Glue Edit Script for reference I have tried changing the script.py to have only few imports and a print, That works and AWS Glue is able to read the script.py Then i tried to add a few more print statements, then it scrambles. It is difficult to conclude, exactly when it scrambles, as sometimes adding a couple of import in script.py also scrambles. Anyone faced this? -
Logger has no handlers configured
I configure django logging as follows: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[%(server_time)s] %(message)s', }, 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, }, 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False, }, 'django.request': { 'handlers': ['mail_admins', 'console'], 'level': 'ERROR', 'propagate': False, }, 'django.db.backends': { 'handlers': ['console'], 'level': 'INFO' }, 'mylogger': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, } } And mylogger is used as follows, in a separate module: logger = logging.getLogger('mylogger') def myfunc(): logger.warning('something') Stepping through the code shows me that: the logger instance gets created before the configuration is applied the configuration is properly applied to mylogger, by django but when used, the logger instance (which should correspond to the mylogger logger) is not properly configured (!?) I do not understand what is going on here. -
The serializer field might be named incorrectly and not match any attribute or key on the `GenericRelatedObjectManager` instance
I can't figure out why I'm getting this error "The serializer field might be named incorrectly and not match any attribute or key on the GenericRelatedObjectManager instance.". I been working on this for days, Can someone help me please? What is wrong with my code? Thanks in advance. I want to create a nested serializer that has a CRUD functionality. I have 3 interrelated models namely Company, Address, and Country. Company model have a field called "address" and it's a GenericForeignKey. Address model have a field called "country" and it's ForeignKey. Country model is a CountryField(). I'm using django_countries plugin. Model Structure Company |__Address (GenericForeignKey) |___Country (ForeignKey) Company Model from django_countries.fields import CountryField class SalesClientCompany(models.Model): address = GenericRelation( Address, null=True, blank=True, ) Address Model class Address(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,) object_id = models.UUIDField( primary_key=False, unique=False, default=uuid.uuid4, blank=True, null=True, ) content_object = GenericForeignKey() country = models.ForeignKey( Country, verbose_name=_("Country"), to_field='country', blank=False, on_delete=models.CASCADE, ) Country Model from django_countries.fields import CountryField class Country(SmardtAbstractHistory): country = CountryField( unique=True, ) name = SmardtTranslateField( models.CharField( max_length=50, null=True, ) ) Serializers from rest_framework import serializers from django.contrib.contenttypes.models import ContentType, ContentTypeManager from models.client_companies import SalesClientCompany from country.models.countries import Country from models.addresses import Address class CountrySerializer(serializers.ModelSerializer): class Meta: model = … -
AttributeError: 'tuple' object has no attribute 'startswith' when start migrate
I made makemigrations, and next I used migrate. But it conduct to next error: AttributeError: 'tuple' object has no attribute 'startswith' I understand, that it links with confusing string and massive, but how to fix it? There is when renterinfo.0001_initial starts migrate Here my renterinfo.0001_initial file: from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Addresses', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('id_renter', models.IntegerField()), ('subject', models.IntegerField()), ('city', models.CharField(blank=True, max_length=50, null=True)), ('street', models.CharField(blank=True, max_length=50, null=True)), ('house', models.CharField(blank=True, max_length=4, null=True)), ('housing', models.CharField(blank=True, max_length=3, null=True)), ('building', models.CharField(blank=True, max_length=2, null=True)), ('office', models.CharField(blank=True, max_length=3, null=True)), ('telephon', models.CharField(blank=True, max_length=16, null=True)), ('type', models.TextField(blank=True, null=True)), ], options={ 'db_table': ('renterinfo_addresses',), 'managed': True, }, ), migrations.CreateModel( name='IndEntrep', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('org_prav_form', models.TextField()), ('inn', models.CharField(max_length=12)), ('account_name', models.CharField(max_length=20)), ('acc_pwd', models.CharField(blank=True, max_length=128, null=True)), ('second_name', models.CharField(max_length=40)), ('first_name', models.CharField(max_length=40)), ('patronymic', models.CharField(max_length=40)), ('identity_doc', models.CharField(max_length=40)), ('serial_doc', models.CharField(max_length=8)), ('number_doc', models.CharField(max_length=8)), ('ogrnip', models.CharField(blank=True, max_length=15, null=True)), ], options={ 'db_table': ('renterinfo_indentrep',), 'managed': True, }, ), migrations.CreateModel( name='LegalDocuments', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=40, null=True)), ], options={ 'db_table': ('renterinfo_legaldocuments',), 'managed': True, }, ), migrations.CreateModel( name='Organizations', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('org_prav_form', models.TextField()), ('inn', models.CharField(max_length=12)), ('account_name', models.CharField(max_length=20)), ('acc_pwd', models.CharField(blank=True, max_length=128, null=True)), ('name', models.CharField(blank=True, max_length=50, null=True)), ('snameplp', models.CharField(blank=True, max_length=80, null=True)), … -
CSS class selector is applying to a div with no class specified?
I am a bit new to CSS and have been struggling with why a selector has been applying to a classless div. Here is my css file: .page-header p, form{ font-family: 'Raleway', sans-serif; float: right; margin: 5px; padding-top: 30px; } And here is my HTML file: <div class="page-header"> {% if user.is_authenticated %} <form action = "{% url 'logout' %}"> <button type="submit">Logout</button> </form> <form action = "{% url 'errandlist' %}"> <button type="submit">View my errands</button> </form> <p>Welcome {{ user.get_username }}.</p> {% else %} <form action = "{% url 'login' %}"> <button type="submit">Login</button> </form> <form action = "{% url 'signup' %}"> <button type="submit">Sign up</button> </form> <p>You are not logged in.</p> {% endif %} <h1><a href="/">bingoHelper</a></h1> </div> <div> {% block content %}{% endblock content %} </div> The first div is properly applying the page-header class. The problem is, the bottom div is somehow using the page-header class even though there is no class specified. For example, in the following HTML file that shows the block content, the form is floating right and has the Raleway font: {% extends "base.html" %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock content %} Any help … -
Is it a good idea to delete explicitly in each request to minimise work for garbage collector in long run
Suppose we have a APIView like this which returns large queryset. Can I minimise the work for garbage collector by doing like this? class MyView(APIView) def get_list(self, request, format=None): params=request.query_params result = MyModel.objects.all() serializer = MyModelSerializer(result, many=True) del result #deleting explicitly here del params #deleting explicitly here return Response(serializer.data, status=status.HTTP_200_OK) I read that calling gc.collect() in each request is not a good idea. Is this a good idea to do this so that garbage collector will have less stuff to collect garbage? -
Django rest nested serializer not displaying fields
I have a model Workflow and WorkflowLevel. Each workflow has many WOrkflow levels .Im trying to use nested serializer : class WorkflowLevelSerializer (serializers.ModelSerializer): class Meta: model = WorkflowLevel fields = '__all__' class WorkflowSerializer (serializers.ModelSerializer): levels = WorkflowLevelSerializer(many=True) class Meta: model = Workflow fields = ('id', 'name', 'description', 'tenant', 'levels') The levels field is not displaying in the workflow listAPI view . Getting error: Got AttributeError when attempting to get a value for field `levels` on serializer `WorkflowSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Workflow` instance. Original exception text was: 'Workflow' object has no attribute 'levels'. -
Click the button and save current time and default values in the database (Django)
When the button "Add" in my browser is clicked, it will automatically save the name (Module 1), current date, and location (Sector 1) to the database. Here are my codes so far: models.py from django.db import models from django.utils import timezone class Alert(models.Model): module = models.ForeignKey(Module, on_delete = models.CASCADE, default='Module 1') date = models.DateTimeField(default = timezone.now) location = models.CharField(max_length=10, default='Sector 1') def __str__(self): return self.module views.py from django.shortcuts import render from django.contrib import messages from django.views.generic import ListView from .models import Alert, Module from .forms import AlertForm def home(request): context = { 'modules': Module.objects.all(), 'alerts': Alert.objects.all(), } if request.method == 'POST': form = AlertForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, ('Item has been successfully added to the database!')) return render(request, 'home/home.html', context) return render(request, 'home/home.html', context) def alert(request, module_id): try: mdl = Module.objects.get(id=module_id) except Module.DoesNotExist: mdl = None context = { 'module': mdl, 'alerts': Alert.objects.all() } return render(request, 'home/alert.html', context) home.html <div class="container"> <form method="POST">{% csrf_token %} <input type="submit" value="Add"> </form> </div> -
In Django: From Admin Panel/Code/Shell, I am not able to save any DateTime Fields?
Django/Mysql, I am saving the DateTime Field of any user "LastLogin". I am using Django version 11.4, Mysql Version 5.7. it is not getting saved. -
How to update postgres password when authenticating to RDS via STS token (IAM)
Rds has supported IAM-based authentication into postgres for a while now, but I don't see any discussion about getting it working within a django app happening anywhere. It's a simple enough system - your app runs with a service role (or has an iam user's access key and secret), to which permission to connect as a particular db user has been attached, via a standard IAM policy. Whenever the app needs to connect to the database, it uses the AWS SDK to request a token from STS, which is authorized via the service role so no credentials are required. It uses the received token as the password when connecting to the database, and the database must have a user with that name which is configured to use the iam authentication mechanism. But the tokens are only good for 15 minutes. This means that the connection factory needs to set a max-age for the connection that is less than 15 minutes, and it needs to request a new token/password every time it opens a new connection. Django expects a password to be set at application initialization, not dynamically generated every time a new connection is made. This seems like the kind … -
How to make a django admin panel for a ready database?
how to make a django admin panel for a ready mysql database ? I have a mysql database with tables and records in it , i want to make an admin panel for it how can i do that ? i searched and there was no strict answer for it . any suggestions will be helpfull , thanks to this great community . -
Django in Ubuntu 18.04 on Azure VM is not accessible
I'm trying to deploy my Django application to Azure virtual machine with Ubuntu 18.04. I have set up the VM and connect to it via SSH. Then run the update and upgrade command Setup Python and Virtualenvironment Upload my code and activate the environment Allow the port 8000 using sudo ufw allow 8000 for testing After installing all the requirements, when I run the command: python manage.py runserver 0.0.0.0:8000 The application runs, but when I open the URL as: :8000/ It doesn't return anything not any errors in the console What can be wrong here? -
Django template as input to form template
I have a form_template.html and a form my_form. I also have a table my_table, with a column my_template. my_table.my_template is a Django template which gets its values from my_form. Inside form_template.html, I would like to put my_table.my_template. Is this possible? I currently have this: form_template.html <form method="POST"> {% csrf_token %} {{my_table.my_template|safe|default:""}} </form> my_template <p>Some text properly displayed</p><textarea id="my_form_detail">{{my_form.detail.value|default:""}}</textarea> my_template can be displayed, except the textarea has {{my_form.detail.value|default:""}} instead of my_form.detail value. Thank you! -
Jquery Sortable Not dragging or dropping list items in django
I am trying to implement Jquery sortable drag and drop from one list to another but I am unable to do so. Below is my code. Also I tried several tricks like making the id="item_{{index_num}}" but didn't work. I also tried draggable and droppable but nothing really worked. Please help. This is what I want to achieve : https://jqueryui.com/sortable/#connect-lists {% extends 'base.html' %} {% load static %} {% block abc %} <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <style> #sortable1, #sortable2 { border: 1px solid #eee; width: 142px; min-height: 20px; list-style-type: none; margin: 0; padding: 5px 0 0 0; float: left; margin-right: 10px; } #sortable1 li, #sortable2 li { margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 120px; } </style> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#sortable1, #sortable2").sortable({ connectWith: ".connectedSortable" }).disableSelection(); }); </script> <div class="wrap"> <ul id="sortable1" class="connectedSortable"> <li id="item_1" class="ui-state-default">Item 1</li> <li id="item_2" class="ui-state-default">Item 2</li> <li id="item_3" class="ui-state-default">Item 3</li> <li id="item_4" class="ui-state-default">Item 4</li> <li id="item_5" class="ui-state-default">Item 5</li> </ul> <ul id="sortable2" class="connectedSortable"> <li id="item_6" class="ui-state-highlight">Item 1</li> <li id="item_7" class="ui-state-highlight">Item 2</li> <li id="item_8" class="ui-state-highlight">Item 3</li> <li id="item_9" class="ui-state-highlight">Item 4</li> <li id="item_10" class="ui-state-highlight">Item 5</li> </ul> </div> {% endblock %} -
How can we display text file in django templates from my local file system without using static and media folder?
if use this path in html tag than it will give error like this "GET /home/uadmin/destination/2019-02-12/PP1002258_RUTTER_1/PP1002258_RUTTER_1-2 HTTP/1.1" 404 2389 and if i use tag of html than file will be downloaded. -
getting 405 method not allowed
getting the 405 error, cant say why. views.py: class PostTweet(View): def Post(self, request): if request.method =='POST': print(post) return HttpResponse('posted') urls.py: from django.conf.urls import url, include from django.contrib import admin from tweets.views import Index, Profile, PostTweet admin.autodiscover() urlpatterns = [ url(r'^$', Index.as_view()), url(r'^user/(\w+)/$', Profile.as_view()), url(r'^user/(\w+)/post/$', PostTweet.as_view()), ] html: {% extends "base.html" %} {% block content %} <div class="row clearfix"> <div class="col-md-12 column"> <form method = 'POST'>{% csrf_token %} <!-- <div class="col-md-8 col-md-offset-2 fieldWrapper"> --> {{ form.text.errors }} {{ form.text }} <!-- </div> --> {{ form.country.as_hidden }} <button type="submit" value="post it">Post </form> </div> <!-- <div class="col-md-12 column"> {% for tweet in tweets %} <div class="well"> <span>{{ tweet.text }}</span> </div> {% endfor %} </div> --> </div> {% endblock %} Still getting the above error no matter what I do. Any ideas will be appreciated. Thanks -
Server-side image conversion to webp format [duplicate]
This question already has an answer here: Convert images to webP using Pillow 1 answer How I can do image conversion to webp? I already did pip install webp. import PIL.Image def foobar(request): images = request.FILES.getlist('images') for i in images: try: foo = Image.open(i) except: return HttpResponse(status = 400) foo = Image.convert(foo, 'webp', quality = 100) # pseudocode Image.objects.create(image_field = foo) return HttpResponse(status = 201) -
How do I handle arrays that are returned in json format?
I am trying to get items in an array that is in a json response. When I try to log response in my console, I can see the array and it's items, but when I try to access an item in the array, I get "[object Object]" instead. JSON response: { email: "test@test.com" groups: [{ id: '1' name: 'admin' }] id: 1 is_active: true last_login: "2019-02-12T23:22:50.440290Z" username: "test" } I've already tried: user.groups.name user.groups(['name']) user.groups[2] //this is the method that requests the response getUserData(){ this.userService.getUserDetails().subscribe( response => { this.users = response; console.log(response); }, error => console.log('Error', error) ); } //this is how I am calling the response in my html component file <div *ngFor="let user of users"> {{ user.username }} {{ user.groups }} </div> I need to access the "name" attribute and print out 'admin' in my div tags. -
Writing a Get Function Gives me an Attribute Error
This is my models.py class Grade(models.Model): grade = models.CharField(max_length=255, primary_key=True) This is my views to perform get(post is not required, I can run if post methood is required as well). class GetGrade(generics. GenericAPIView): ''' GET site/ ''' queryset = Grade.objects.all() serializer_class = DataSerializer def get(self, request, *args, **kwargs): a_grade = Grade.objects.all() return Response( data=DataSerializer(a_grade).data, status=status.HTTP_200 ) My serializer is below: class DataSerializer(serializers.ModelSerializer): class Meta: model = Grade fields = ("grade",) Everything seems straightforward. It might be something silly that I might be doing. -
Dependencies installed in one conda env is getting reflected in another
I am new to the world of Python, Conda and pipenv. I have installed anaconda in my system to start developing Python and then to write Flask and Django Web Apps. So using conda create -n Django-Apps and conda create -n Flask-Apps. I have created 2 seperate envs for my different projects. In Django-Projs folder I activated conda activate Django-Apps and installed Django and installed Flask in Flask Folder after activating Flask-Apps. But apparently in my Flask-Apps conda env I am able to use Django. So, I wanted to know it is common behaviour of dependency sharing in conda envs. Or, I have done something wrong that is making all my dependencies installed in another env being reflected in all. If so, how can I mitigate this? -
Populating sqlite3 from excel django.db.utils.IntegrityError: FOREIGN KEY constraint failed
I'm trying to populate sqlite3 DB from an excel file using a populating script Models.py from django.db import models class Major(models.Model): name = models.CharField(max_length=30, db_index=True) def __str__(self): return self.name class School(models.Model): name = models.CharField(max_length=50, db_index=True) majors = models.ManyToManyField(Major) def __str__(self): return self.name class professor(models.Model): #Link each professor to the correct Major and school ID #major = models.ForSeignKey(Major, on_delete=models.CASCADE) #school = models.ForeignKey(School, on_delete=models.CASCADE) ProfessorIDS = models.IntegerField() ProfessorName = models.CharField(max_length=100) ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4) NumberofRatings = models.CharField(max_length=50) #delete major from the model school = models.ForeignKey(School , on_delete=models.CASCADE) major = models.ForeignKey(Major , on_delete=models.CASCADE) def __str__(self): return self.ProfessorName populating script # populate.py import os import django from django_xlspopulator.populator import Populator os.environ.setdefault('DJANGO_SETTINGS_MODULE','blog_project.settings') django.setup() from locate.models import professor pop = Populator('C:/Users/David/Desktop/db_setup/professors.xlsx', professor) pop.populate() Error message Traceback (most recent call last): File "C:\Users\David\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.2-py3.7.egg\django\db\backends\base\base.py", line 239, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "populate_professor.py", line 10, in <module> pop.populate() File "C:\Users\David\AppData\Local\Programs\Python\Python37\lib\site-packages\django_xlspopulator\populator.py", line 30, in populate self.model.objects.create(**entry) File "C:\Users\David\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.2-py3.7.egg\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\David\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.2-py3.7.egg\django\db\models\query.py", line 413, in create obj.save(force_insert=True, using=self.db) File "C:\Users\David\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.2-py3.7.egg\django\db\models\base.py", line 718, in save force_update=force_update, update_fields=update_fields) File "C:\Users\David\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.2-py3.7.egg\django\db\models\base.py", line 748, in save_base updated = … -
Django is deployed on a ubuntu server and cannot be “makemigrations”
I was fine when testing django locally, but when I used python manage.py makemigrations on a ubuntu server, I get an error "django.db.utils.ProgrammingError: (1146, "Table 'NewHuBu.topic_sort_model' doesn't exist") ”enter image description hereenter image description here