Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any alternative to Base64 Encoding on image upload for Android-Django communication?
I saw a lot of examples on the subject where the image is base64-encoded and sent to a server with a POST request. This is the typical chunk of code for that: ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); byte[] imageBytes = byteArrayOutputStream.toByteArray(); final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT); I am currently using the Volley Android package. I also noticed that with this method the image is contained in the BODY variable of the POST request and not in FILES (which is the case if I use Postman for the POST test). I would like to not encode the image with Base64 and put the data on the FILES variable. Is there any Android example on that? Thanks in advantage -
Cookies works in Postman , but not in browser
I created a login API using Django rest framework and then used session auth. When i sent request via Postman , i get csrftoken and sessionid cookies. and i was able to access content on backend. OK fine. But when i built small login form html and called that API for logging in. It worked. I see COOKIES IN RESPONSE BUT COOKIES ARE NOT SET IN CHROME BROWSER. Under Storage section in dev tools cookies are empty. when i tried to access content(other views/apis) , i was not able to.. I think its because of Cookies are not being stored in browser.. Been on this like 5 days. Please can Someone explain about cookies not being saved.? -
Measuring time spent on webpage
I would like to measure the time a user spends in a specific webpage. I can measure that with JavaScript but I want to save it inside my database. With ajax I can send it when the user unloads the page but the onunload JavaScript event may not get triggered for some reason. Can someone give me some guidance on that topic? -
Session-django for access username from mysql database
I want to access mysql database of django and by taking username from database I want to create username's directory on s3 and by using django-sessions..how to do this? -
can one have multiple html files in a single template directory in django?
Directory structure of my project, here I have a templates directory with two other directories home and diagnosis each directory having its a respective HTML file. So I want to know if that's the best way to do it or am doing it the wrong way ? -
Javascript not working in Bootstrap Carousel [Django Template]
I am working on Django template. All the path of the extended HTML files path are correct and working. My dashboard.html is: {% extends "./base.html" %} {% block content %} <style type="text/css"> .image { height: 400px; width: 100%; } </style> <div class="container-fluid border border-top border-bottom border-success text-center py-3"> <h5><i class="fas fa-podcast mr-1"></i><strong>Today's Thought: </strong>{{thought.thought}}</h5> </div> {% if news %} <div class="container-fluid border border-top border-bottom border-success text-center py-3 "> <h4><i class="far fa-newspaper mr-1"></i><strong>Newsletter:</strong> <h4> <!-- <h5> --> {% for n in news %} <div>{{n.description|safe}}</div> <!-- </h5> --> {% endfor %} </div> {% endif %} {% if photos %} <div class="container-fluid"> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> {% for photo in photos %} {% if forloop.counter0 == 0 %} <li data-target="#carouselExampleIndicators" data-slide-to="{{ forloop.counter0 }}" class="active"></li> {% else %} <li data-target="#carouselExampleIndicators" data-slide-to="{{ forloop.counter0 }}"></li> {% endif %} {% endfor %} </ol> <div class="carousel-inner"> {% for photo in photos %} <div class="carousel-item active"> <img src="{{photo.file.url}}" class="d-block w-100 image" alt="image"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> {% endif %} {% endblock content %} My base.html is <!DOCTYPE html> <html lang="en"> <head> … -
Do I have to clean form data with no inputs?
I currently have a form submission wiht only a button thats posting to my backend to perform API calls. The form does not have any data being submitted other than the name of the name of the button to execute code blocks. Do I have to clean the form even though there are no data inputs? <form action="" method="POST"> {% csrf_token %} <button class="btn btn-danger" type="submit" name="delete">Delete</button> </form> -
Unable to access document from mongo collection using pymodm in Django shell
Here is my Model: class Member(MongoModel): first_name = fields.CharField(required=True, max_length=200) last_name = fields.CharField(required=True, max_length=200) empi = fields.CharField(required=True, max_length=200) Here is Data in the mongo collection member: { "_id" : ObjectId("5e2aee76e5046c2c6dd8f454"), "first_name" : "Lawson", "last_name" : "Joy", "empi" : "1" } { "_id" : ObjectId("5e2aee76e5046c2c6dd8f455"), "first_name" : "Kevin", "last_name" : "Peterson", "empi" : "2" } And output of Django shell: In [12]: from pymodm import connect In [14]: from models import Member In [13]: Member.objects.count() Out[13]: 0 Why the documents of Member collection is not visible to pymodm ? If mongo shell shows that 2 documents exists in Member collection, the output of count() should be 2. -
Django forms - how to add labels inside boxes?
I have simple django- form: class ContactUsForm(forms.ModelForm): class Meta: model = Contact fields = ('subject', 'email', 'message') widgets = {'time': forms.HiddenInput()} labels = { 'subject': 'my_subject', 'email': 'my_email', 'message': 'my_message', } Model: class Contact(models.Model): email = models.EmailField(max_length=100) subject = models.CharField(max_length=100) message = models.TextField() time = models.DateTimeField(default=timezone.now) def __str__(self): return self.message And html: <h2 class="mb-5">Contact</h2> {% load crispy_forms_filters static %} <form method="POST" class="post-form">{% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-outline-secondary">Send</button> </form> How to remove labels above boxes and put it inside? Is it possible to do it with crispy? -
Auto date with read only mode in Django
def __init__(self, *args, **kwargs): #now = datetime.now() super(TestForm, self).__init__(*args, **kwargs) self.fields['training_date']=datetime.date.today How can we get auto today's date with a read-only mode in Django form? I am trying to render my form with the current date in the read-only input field. How can I achieve this, any solution?? I have tried multiple ways but did not work for me. -
Django equivalent of SELECT * GROUP BY in MySQL
I'm having troubles using .annotate() and .aggregate() in Django ORM. My table structure: ----------------------------------------------------- | id group_id date_time | | ================================================= | | 1 1 2020-01-25 19:51:46.603859 | | 2 2 2020-01-24 18:40:24.301419 | | 3 1 2020-01-25 20:14:11.123860 | | 4 2 2020-01-25 05:20:21.507901 | ----------------------------------------------------- I have the following MySQL Query: SELECT *, MAX(date_time) AS date_time_max FROM 'my_table' GROUP BY group_id Which returns: -------------------------------------------------------------------------------- | id group_id date_time date_time_max | | ============================================================================ | | 1 1 2020-01-25 19:51:46.603859 2020-01-25 20:14:11.123860 | | 2 2 2020-01-24 18:40:24.301419 2020-01-25 05:20:21.507901 | -------------------------------------------------------------------------------- And I'm trying to convert it to Django ORM so I can have a full QuerySet of objects. Until now I have been using this code: unique_qs = MyModel.objects.filter(id__lte=50).values_list('group_id', flat=True).distinct() for qs in unique_qs: unique_qs.append(MyModel.objects.filter(group_id = qs).latest('date_time')) But it's really inefficient and time consuming. Could you give me some lead on how to achieve it? -
Django create path to an image file
I have a normal app that has a directory structure similar to the following: ...static/ Training/ css/ img/ js/ ...templates/ .... Within one of my templates, I would like to get the image name from the database and build the path to the image. For example, if I had the image MyPicture.jpg, then I would like to include static and combine this with 'Training/img/' and the file name to get something like '..path to static../Training/img/MyPicture.jpg' I found the following article that suggested using template tags, so I have tried this: from django import template register = template.Library() @register.filter def addstr(arg1, arg2): # Apparently, add has side effects, so use this: # https://stackoverflow.com/questions/4386168/how-to-concatenate-strings-in-django-templates return str(arg1) + str(arg2) With the template: {% with static|addstr:"Training/img/"|addstr:course.img as imgpath %} <img class="card-img rounded-lg rounded-top" src="{{ imgpath }}" alt="Card image"> {% endwith %} This is unfortunately leaving out the static part of the address. How do I combine all three parts ? [p.s. I have a {% load static %} at the top of the template ] Thanks Mark -
django setup is not sefine
File "populate.py", line 4, in django.setup() File "C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\conf__init__.py", line 76, in getattr self._setup(name) File "C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\conf__init__.py", line 61, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Django i18n issue on heroku
I am developing a Django web application and deploy this application to heroku. I use i18n to implement multi-language function. this is my po file /locale/zh_hant/LC_MESSAGES/django.po #: lib/templates/langs/index.html:7 msgid "name" msgstr "名稱" #: myShopCar/settings.py:211 msgid "German" msgstr "德文" #: myShopCar/settings.py:212 msgid "English" msgstr "英文" #: myShopCar/settings.py:213 msgid "Tranditional Chinese" msgstr "繁體中文" #: myShopCar/settings.py:214 msgid "Simplied Chinese" msgstr "簡體中文" this is my template /lib/templates/langs/index.html {% load i18n %} {% get_current_language as LANGUAGE_CODE %} {{ LANGUAGE_CODE }} {% trans "name" %} {% trans "login" %} it works well and translates correctly on my computer and heroku. later, i execute the command django-admin makemessages -l zh_hant , then msgid "login" was added to django.po, and I changed msgstr "名稱" to msgstr "名字" /locale/zh_hant/LC_MESSAGES/django.po #: lib/templates/langs/index.html:8 msgid "login" msgstr "登入" #: lib/templates/langs/index.html:7 msgid "name" msgstr "名字" #: myShopCar/settings.py:211 msgid "German" msgstr "德文" #: myShopCar/settings.py:212 msgid "English" msgstr "英文" #: myShopCar/settings.py:213 msgid "Tranditional Chinese" msgstr "繁體中文" #: myShopCar/settings.py:214 msgid "Simplied Chinese" msgstr "簡體中文" it also works well on my computer. then i deployed my application to heroku, but it doesn't works correctly on heroku this time. it seems that heroku did not reload the new .mo file after new deploy. Is there anything I lost? … -
Basic PUT/PATCH request for Django Rest Framework
I'm quite new to Django and DRF and it is quite hard for me to find general examples for CRUD methods. I want to implement a PUT or PATCH request to be able to alter my objects. This is what I have: models.py from django.db import models class Card(models.Model): name = models.CharField(max_length=200) attraction = models.BooleanField() lake = models.BooleanField() mountain = models.BooleanField() museum = models.BooleanField() viewpoint = models.BooleanField() img = models.CharField(max_length=500) crowdedness = models.IntegerField(default=0) rating = models.DecimalField(max_digits=2, decimal_places=1) priceMin = models.DecimalField(max_digits=5, decimal_places=2, default=0.00) priceMax = models.DecimalField(max_digits=5, decimal_places=2, default=100.00) mapsURL = models.CharField(max_length=200, default="/") openingHoursFrom = models.DateTimeField() openingHoursTo = models.DateTimeField() description = models.CharField(max_length=1000, default='Lorem ipsum dolor.') def __str__(self): return self.name views.py class CardView(viewsets.ModelViewSet): queryset = Card.objects.all() serializer_class = CardSerializer def patch(self, request): queryset = Card.objects.all() serializer_class = CardSerializer serializers.py from rest_framework import serializers from .models import Card class CardSerializer(serializers.ModelSerializer): class Meta: model = Card fields = ('id', 'name', 'attraction', 'lake', 'mountain', 'museum', 'viewpoint', 'img', 'crowdedness', 'rating', 'priceMin', 'priceMax', 'mapsURL', 'openingHoursFrom', 'openingHoursTo', 'description') Obviously, the patch request doesn't work. But if I don't explicitly declare def patch() I get a patch not allowed error. How can I implement a basic patch method (or put method), which alters an object by passing the complete object … -
Django daphne asgi: Django can only handle ASGI/HTTP connections, not websocket
This is really frustrating, i did set everything up according to the documentation, but daphne keep throwing error when i try to run it independently, it does work correctly when i use python manage.py runserver. this is very frustrating and i cant seem to find similar error anywhere else 2020-01-25 09:57:17,627 INFO Starting server at tcp:port=8000:interface=127.0.0.1 2020-01-25 09:57:17,628 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2020-01-25 09:57:17,628 INFO Configuring endpoint tcp:port=8000:interface=127.0.0.1 2020-01-25 09:57:17,629 INFO Listening on TCP address 127.0.0.1:8000 127.0.0.1:44516 - - [25/Jan/2020:09:57:27] "WSCONNECTING /ws/score/" - - 2020-01-25 09:57:28,637 ERROR Exception inside application: Django can only handle ASGI/HTTP connections, not websocket. File "/home/sofdeath/.local/lib/python3.7/site-packages/daphne/cli.py", line 30, in asgi await self.app(scope, receive, send) File "/home/sofdeath/.local/lib/python3.7/site-packages/django/core/handlers/asgi.py", line 146, in __call__ % scope['type'] Django can only handle ASGI/HTTP connections, not websocket. 127.0.0.1:44516 - - [25/Jan/2020:09:57:28] "WSDISCONNECT /ws/score/" - - ^C2020-01-25 09:57:39,126 INFO Killed 0 pending application instances here is my asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tabulator.settings') application = get_asgi_application() my routing.py: from django.urls import re_path from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator import judge.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( judge.routing.websocket_urlpatterns … -
After running inspectdb for POSTGIS DB, python manage.py runserver gives error (Django-2.2)
Running: python manage.py inspectdb --database=geoserver > map/models.py After: python manage.py runserver gives below errors: Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\Hassan\Miniconda3\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\Hassan\Miniconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "d:\DSS2.0\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "d:\DSS2.0\venv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "d:\DSS2.0\venv\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "d:\DSS2.0\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "d:\DSS2.0\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "d:\DSS2.0\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "d:\DSS2.0\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Hassan\Miniconda3\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, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed ValueError: source code string cannot contain null bytes Traceback (most recent call last): File "d:\DSS2.0\venv\lib\site-packages\django\apps\registry.py", line 155, in get_app_config return self.app_configs[app_label] KeyError: 'admin' During handling of the above exception, another exception occurred: Traceback (most recent call … -
django template loading takes time
i made an app in django which shows data taking it from various sources like excel, sql and web scrapping. everything is working fine except the time to load the webpage. i need to optimize so that web can be open in lesser time. below is my views code from django app from django.shortcuts import render from django.http import HttpResponse from .models import Sale_detail from django.contrib import messages import pandas as pd from datetime import date, datetime, timedelta from decimal import localcontext, Context, ROUND_DOWN from babel.numbers import format_currency import time import xlwings import MySQLdb import os.path import datetime from selenium import webdriver from selenium.webdriver.chrome.options import Options # Create your views here. def connect_sql(): connection = MySQLdb.connect(host="localhost",user="root",passwd="",db="djnago_test") cur = connection.cursor() return cur,connection def load(): options = Options() options.headless = True driver = webdriver.Chrome(chrome_options=options) driver.get("http://www.punjabsldc.org/realtimepbGen.aspx") time.sleep(3) mw =[] power_plant = ["ippRajpura1","ippRajpura2","ippTS1","ippTS2","ippTS3","ippGVK1","ippGVK2","GGSSTP3","GGSSTP4","GGSSTP5","GGSSTP6","GHTP1","GHTP2","GHTP3","GHTP4"] for i in power_plant: # print(f'\"{i}\"') element = driver.find_element_by_xpath(f'//*[@id=\"{i}\"]') mw.append(element.text) driver.close() return mw # def index(request): def sale_detail(request): def adv_sale(): sum_list= [] x = datetime.datetime.now() month = x.strftime("%B") path = r'\\10.9.32.2\adm\Ash\FY 2019-20\Sale detail sheet\SALE DETAIL SHEET JANUARY 2020.xlsx' customers1 = [] customers2 = [] cur,conn = connect_sql() cur.execute("SELECT * FROM dashboard_sale1") for row in cur.fetchall(): customers1.append(int(row[1])) customers2.append(row[2]) conn.close() customers2_length = range(0,len(customers2)) … -
Unable to set background image in Django
So I have a base.html file, to which I am trying to add a background image. This base.html file is inherited in all other system files, and I am hoping that adding the background image to base.html will automatically add the background image in all those files which inherit it. I have a master.css file in my static/css path, and I am trying to add the background image to it by: body{ background-image: url(./background.jpeg); } I have put the image in same folder as the master.css. I am also attaching a screenshot of my file structure. Where am I going wrong? Any help is appreciated. Thank you. -
How to add variables inside the for loop of Jinja python
I am trying to loop over a product list{more so a queryset} in django using for loop, by adding the range of products The following code works when printed out in cmd prompt for card in allproduct[nextRangePage:limit]: print(card.name) But the Jinja pattern fails for some reason {% for card in allproduct[{%'nextRangePage'%}:{%'limit'%}] %} The error is django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[{%'nextRangePage'' from 'allproduct[{%'nextRangePage'' The context variables are: context = { 'product': product_list, 'pages': pages, 'nextRangePage': nextRangePage, } -
Save reverse Foreign Key in Django CreateView
I have these 2 models: class Company(models.Model): ... contact_person = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_("Contact person")) ... class Assignment(models.Model): ... company = models.ForeignKey('company.Company', null=True, blank=True, on_delete=models.CASCADE, verbose_name=_("Company")) ... I want to automatically fill the company field when using Django's CreateView based on the current logged-in user. Because every Company model has a ForeignKey relationship with User. So I override the form_valid method, but how can I get the correct value here for the company field? class AssignmentCreateView(generic.edit.CreateView): def form_valid(self, form): instance = form.save(commit=False) instance.company = self.request.user super(AssignmentCreateView, self).save(form) -
Django REST Framework - serializer users
I would like to add new offer using username instead of userID. Could you please advise how this should be managed with user_receiver? models.py User = get_user_model() class Offer(models.Model): user_sender = models.ForeignKey(User, related_name='user_sender', on_delete=models.CASCADE) user_receiver = models.ForeignKey(User, related_name='user_receiver', on_delete=models.CASCADE) serializer.py class OfferSerializer(serializers.ModelSerializer): current_user = serializers.CharField(default=serializers.CurrentUserDefault()) user_receiver = ??? class Meta: model = Offer fields = ('user_sender', 'user_receiver') -
TypeError at /users/sigup create_user() takes from 2 to 4 positional arguments but 5 were given
My models has username, birthdate, language, curreny, etc... i make guest need to fill there username, email, password (required), and birthdate(optional) when they try to sign up. but error occur. TypeError at /users/sigup create_user() takes from 2 to 4 positional arguments but 5 were given models.py username = models.CharField(max_length=10, blank=False, unique=True) language = models.CharField( choices=LANGUAGE_CHOICES, max_length=2, blank=True, default=LANGUAGE_KOREAN) currency = models.CharField( choices=CURRENCY_CHOICES, max_length=2, blank=True, default=CURRENCY_KOREA) birthdate = models.DateField(blank=True, null=True) login_method = models.CharField( max_length=50, choices=LOGIN_CHOICES, default=LOGIN_EMAIL) forms.py def save(self): username = self.cleaned_data.get("username") email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") birthdate = self.cleaned_data.get("birthdate") user = models.User.objects.create_user( username, email, password, birthdate) user.save() views.py class SignUpView(FormView): template_name = "users/signup.html" form_class = forms.SignUpForm success_url = reverse_lazy("cores:home") def form_valid(self, form): form.save() username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") birthdate = self.cleaned_data.get("birthdate") user = authenticate(self.request, email=email, password=password) if user is not None: login(self.request, user) return super().form_valid(form) want to the guest login with email and password, but how can I acheive it? -
form method clean_field not working properly during testing
I have a little project where users can make posts. Posts are not published by default (e.g. status is 'pre-moderation'), but if a user is in a specific group, their post status will be automatically changed to 'published' in the form below. This works like a charm in the actual usage. But when i decided to cover that part of the project with tests i found out that it DOESN'T work during tests. I need some help. I believe i'm missing something and doing the test wrong. models.py STATUS_CHOICES = ( ('pre-moderation', "Pre-moderation"), ('published', "Published"), ) class NewsPost(models.Model): """ Simple NewsPost model """ status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='pre-moderation', blank=True) body = models.TextField('Body', max_length=500) author = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name='posts') forms.py class NewsPostCreateForm(ModelForm): """ NewsPost form that adds a summernote widget """ class Meta: model = NewsPost fields = ('body', 'status') widgets = { 'body': SummernoteWidget(), 'status': HiddenInput(), } def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(NewsPostCreateForm, self).__init__(*args, **kwargs) def clean_status(self): """ Change status to published if the user has the required permission """ if self.user.groups.filter(name__in=['editor', 'admin']).exists(): print('---- this print will be visible in tests ----') return 'published' if self.instance: return self.instance.status return None tests.py @pytest.fixture def user_with_permissions(): group = Group.objects.get(name='admin') … -
manage.py (python manage.py makemigrations) Error
So i am new to Python and Django and following a tutorial by Mr. Vitor Freitas link: https://simpleisbetterthancomplex.com/series/2017/09/11/a-complete-beginners-guide-to-django-part-2.html I copied this code into models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics') starter = models.ForeignKey(User, related_name='topics') class Post(models.Model): message = models.TextField(max_length=4000) topic = models.ForeignKey(Topic, related_name='posts') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) created_by = models.ForeignKey(User, related_name='posts') updated_by = models.ForeignKey(User, null=True, related_name='+') Now when i run manage.py on cmd python manage.py makemigrations i get this error Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\admin\development\myproject\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\admin\development\myproject\env\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\admin\development\myproject\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\admin\development\myproject\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\admin\development\myproject\env\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\admin\development\myproject\env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in …