Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set flag in django function and how to use in HTML
I'm new to Django. How to use flag in my function view and in HTML also. I am trying to do When flag is active (flag == 1) it will render home/index.html. otherwise it will render login.html. How to do this. views.py def home_view(request): if 'username' in request.session: test_objs = Test.objects.all().values() return render(request, 'home/index.html', {'test_objs ': test_objs }) return redirect('/login/') home.html <h1 class="text-center mb-5">Test</h1> <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">ID</th> <th scope="col">Name</th> <th scope="col">Phone Number</th> <th scope="col">Email address</th> <th scope="col">Address</th> <th scope="col" colspan="2">Actions</th> <th scope="col"><i style="color:green" class="fas fa-plus" onclick="test()"></i></th> </tr> </thead> <tbody> {% for test_obj in test_objs %} <tr> <th scope="row">{{ test_obj.id }}</th> <td>{{ test_obj.id }}</td> <td>{{ test_obj.name }}</td> <td>{{ test_obj.phone_number }}</td> <td>{{ test_obj.email }}</td> <td>{{ test_obj.address }}</td> <td><a href="{% url 'native:test_edit' test_obj .id %}"><i class="fas fa-edit" style="color:blue"></i></a></td> <td><a href="{% url 'native:test_delete' test_obj .id %}"><i class="fas fa-trash-alt" style="color:red"></i></a></td> </tr> {% endfor %} </tbody> </table> -
How to display valriables in django template without creating a new view
I'm making a dashboard in django and I need to display some data in a template which is in a form of Dataframe. My backend returns me eighter a dataframe of a variable. I've read about django variables in their documentation but its not clear to me https://docs.djangoproject.com/en/2.2/ref/templates/language/#variables can anyone suggest some other way of doing that: Im quite new to this, any help would be appriciated. -
Axios get request gets 401 error but then succeeds when I refresh the page
When I "naturally" make an api call, e.g by clicking on "My Inventory" which makes a get request to api.mysite.com/api/inventory/uuid/, it fails with a 401 error. However, when I'm on that page and I refresh it, suddenly it all works (although my .catch method is still triggered, suggesting an error happened?!) Here is my code: config = { headers:{ 'Authorization' : 'Token ' + localStorage.getItem('token') } } This is my axios get request: axios.get(this.url, this.config.headers) .then(res => { this.setState({ products: res.data }) if (res.data.length > 0) { if (!res.data[0].is_owner) { this.setState({ inventory_owner: res.data[0].user_name, is_owner: res.data[0].is_owner }) } } }) .catch(res => { console.log("error it didnt work "+res.response.data.detail) }) While I was writing this question, I noticed the 2nd call doesn't come from the refresh, but from componentWillReceiveProps, which as the following code (pretty much identical) componentWillReceiveProps() { const path = this.props.history.location.pathname if (path === '/inventory') { this.url = 'https://api.mysite.com/api/inventory/' } else { if(this.param1.length>12){ this.param1 = this.param1 } else{ this.param1 = path[path.length - 1] } this.url = 'https://api.mysite.com/api/inventory/' + this.param1 } axios.get(this.url, this.config) .then(res => { console.log("this work tho") console.log("the url "+this.url) console.log("the config "+this.config.headers.Authorization) this.setState({ products: res.data }) }) } the console outputs identitcal values for url and config, so … -
want to add many texts for same cmt_id
I want to add multiple comments for the same cmt_id but when I am trying to add and press save it shows an error: django.db.utils.IntegrityError: UNIQUE constraint failed: I tried to remove unique=True, but it did not work class Comment(models.Model) cmt_id = models.IntegerField(unique=True) text = models.TextFiled() created_date = models.DateTimeField(default=timezone.now) I expect that it shows multiple comments for same cmt_id. -
Django 2.2 NoReverseMatch error, kwargs returns blank string?
I get a NoReverseMatch error with a blank string for kwargs. Am I doing something wrong in the models.py file that doesn't save the username associated with the post? NoReverseMatch at /groups/posts/in/nasa-rocks/ Reverse for 'for_user' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['posts/by/(?P[^/]+)/$'] models.py: from django.db import models from django.urls import reverse from django.conf import settings # Create your models here. import misaka from groups.models import Group from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='posts',on_delete='CASCADE') group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete='CASCADE') created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:detail',kwargs={'username':self.user.username,'pk':self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['user','message'] urls.py: from django.urls import path from . import views app_name = 'posts' urlpatterns = [ path('',views.PostListView.as_view(),name='list'), path('create/',views.PostCreateView.as_view(),name='create'), path('by/<username>/',views.UserPosts.as_view(),name='for_user'), path('by/<username>/<pk>/',views.PostDetailView.as_view(),name='detail'), path('delete/<pk>/',views.PostDeleteView.as_view(),name='delete') ] views.py: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views import generic from django.http import Http404 from braces.views import SelectRelatedMixin from . import models from . import forms from django.contrib.auth import get_user_model User = get_user_model() # Create your views here. class PostListView(SelectRelatedMixin,generic.ListView): model = models.Post select_related = ('user','group') class UserPosts(generic.ListView): model = models.Post template_name = 'posts/user_post_list.html' def get_queryset(self): … -
how to change value of some field in model by based on the value of another field from another django model
Here is my two model.In here i want to change the value of current_balance of model Ledger.in Default the value of current_balance is equals to opening_balance but if the user selects the payment_option (if payment_option_id == ledger.id) and updates the value of amount_to_pay from Expense Model then the value of current_balance in Ledger model should be (opening_balance-amount_to_pay).how can i do that ? models.py class Ledger(models.Model): name = models.CharField(max_length=200) account_number = models.CharField(max_length=250,unique=True) opening_balance = models.FloatField(default=0.0) amount_to_pay = models.OneToOneField('Expense',on_delete=models.CASCADE) account_type = models.CharField(max_length=200) current_balance = models.FloatField(default=0.0) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = AutoSlugField(unique_with='id', populate_from='name') class Expense(models.Model): pay_from = models.CharField(max_length=200) payment_option = models.ForeignKey(Ledger, on_delete=models.CASCADE) amount_to_pay = models.FloatField(default=0.0) expense_date = models.DateField(default=datetime.date.today) expense_type = models.ForeignKey(ExpenseType, on_delete=models.CASCADE) note = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = AutoSlugField(unique_with='id', populate_from='expense_type') -
How to initialize a mysql database in Django without using mysql shell?
I am a newbie to Django. In would like to initialize the database with name "todolist" without using mysql shell and writing the query "CREATE DATABASE todolist;". Can anyone tell me where can I put the database initialization code in django so that I can run the query from a .sql file and automatically initialize the database while running the code. If any other better options are available I am open to try that also. Thanks -
How much can I rely on the inspectdb command of django for using a large legacy MySQL database?
I need to make a website portal for generating reports based on the activities in the library of my college. For that, I have been given a large database with more than 200 tables. Since I have done website development on django, I was hoping to use that. Now, since I already have a legacy database, I thought of using inspectdb command of django to automatically generate the models according to the database. python manage.py inspectdb > portal/models.py This generated the models for me. I wish to know, how much can I rely on these models. There are multiple OneToOne relations in my database, but django simply made them as ForeignKeys. Could there be more such errors in the models generated? Since the number of tables are large, it's difficult for me to go through every table and check the corresponding models. If the models so generated can't be trusted, I was hoping to make a website using simple python and connection string for connecting MySQL to python. That allows me to access the database, though I'm not sure how to create a website without using a framework and how to integrate front pages to the website. -
Operational error, no such table error in django
I have three database tables in my project. When I apply migrations, they are applied successfully and are visible on the admin site too. But when I click on one of the three database tables on the admin site, I get an operational error saying that table does not exist. The rest of the two tables work correctly. I tried deleting the migrations folder and applying the migrations again. But the same error repeats. The error is as follows Internal Server Error: /admin/users/subscription/ Traceback (most recent call last): File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.0.3-py3.7.egg\django\db\backen ds\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.0.3-py3.7.egg\django\db\backen ds\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: users_subscription The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.0.3-py3.7.egg\django\core\hand lers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.0.3-py3.7.egg\django\core\hand lers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.0.3-py3.7.egg\django\core\hand lers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.0.3-py3.7.egg\django\contrib\a dmin\options.py", line 574, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.0.3-py3.7.egg\django\utils\dec orators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.0.3-py3.7.egg\django\views\dec orators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.0.3-py3.7.egg\django\contrib\a dmin\sites.py", … -
How to use Multiprocessing in Pandas?
when i use multiprocessing in normal program its working fine in pandas,but when i use this multiprocessing time is not reducing. i tried with normal code using multiprocessing import multiprocessing import time import pandas as pd start=time.time() def square(df1): df1['M_threading'] = df1['M_Invoice_type'] def multiply(df4): df4['M_threading'] = df4['M_Invoice_type'] if __name__ == '__main__': df = pd.read_excel("filename.xlsx") df1 = df.loc[df['M_Invoice_type'] == 'B2B'] df4 = df.loc[df['M_Invoice_type'] == 'B2BUR'] p=multiprocessing.Process(target=square,args=(df,)) p1 = multiprocessing.Process(target=multiply, args=(df,)) p.start() p1.start() p.join() p1.join() print("Done") end=time.time() print(end-start) I expect the output time of code 25sec, but the actual output is 51sec. -
do I still need install mysql in django virtual env while I already have mysql in my machine
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by : import pymysql conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture') then I download django frame and try to use it to connect mysql , what I do is : create a my.cnf file content is : [client] database = shfuture host = localhost user = root password = MYSQLTB default-character-set = utf8 change settings.py to : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': os.path.join(BASE_DIR, 'my.cnf'), }, } } then run : python manage.py runserver but got a error : django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Do i still need to install a addition mysql in django virtual env ? if I can use the existing mysql instead -
Comment Replies adding only to a particular comment
I am writing a webapp and would like to add comment/reply functionality. The comments work well, but while trying to add replies, all replies are saved to the first comment alone even when added from other comments. I would like to make replies be linked to other comments. Replies are linked to a particular comment using a ForeignKey() relationship and a related_manager. I have tried a for loop to get each comment from the Comment() models in the template, and while it renders each comment well, I can't seem to link them to their specific replies. # models.py class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) name = models.CharField(max_length=400) email = models.EmailField() text = models.TextField() time_stamp = models.DateTimeField(auto_now_add=True) def __str__(self): return "Comment %s by %s" %(str(self.text)[:20], self.name) class ReplyComment(models.Model): comment_reply = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name="replies") name_reply = models.CharField(max_length=400) text_reply = models.TextField() time_stamp = models.DateTimeField(auto_now_add=True) def __str__(self): return "Reply by %s to %s" %(self.name_reply, str(self.comment_reply)) # views.py def article(request, slug): article = Article.objects.get(slug=slug) comments = Comment.objects.filter(article=article) # comment form if request.method == 'POST': form = CommentForm(request.POST or None) reply_form = ReplyCommentForm(request.POST or None) if form.is_valid(): text = form.cleaned_data['text'] email = form.cleaned_data['email'] name = form.cleaned_data['name'] # create the comment comment = Comment(article=article, text=text, email=email, name=name) … -
how to declare a variable in html for primary key and use it in an 'if' statement
I need to run a segment of a code when the primary key of the object is 1,4,7...etc. Basically, I need to run a if statement for a certain block of code. {% with i = ev.pk %} {% if i%3 == 1 %} <div class="container"> <div class="intro"></div> <div class="row articles"> {% endif %} {% endwith %} <div class="col-sm-6 col-md-4 item" data-aos="fade-left"><a href="#"><img class="img-fluid" src="{{ ev.image.url }}"></a> <h3 class="name">{{ ev.event_title }}</h3> <p class="description">{{ event.event_details }}</p><em class="float-left">{{ ev.date }}</em><em class="float-right">{{ ev.venue }}</em></div> </div> </div> {% endfor %}``` The above code doesn't work, I need: 1. Declare a variable (i) 2. assign it ev.pk 3. run an if statement {% if i%3 == 1%} I am open for suggestions if there is a better way to code this. -
What is causing inefficiency when parsing this QuerySet into tuples?
In a django app, I am attempting to parse a Queryset, representing individual time-series values x from n sensors, into tuples (t, x1, x2 ... xn), and thence into a json object in the format specified by google charts here: https://developers.google.com/chart/interactive/docs/gallery/linechart None values are used as placeholders if no value was logged for a given timestamp from a particular sensor The page load time is significant for a QuerySet with ~6500 rows (~3 seconds, run locally) It's significantly longer on the server http://54.162.202.222/pulogger/simpleview/?device=test Profiling indicates that 99.9% of the time is spent on _winapi.WaitForSingleObject, (which I can't interpret) and manual profiling with a timer indicates that the server-side culprit is the while loop that iterates over the QuerySet and groups the values into tuples (line 23 in my code example) Results are as-follows: basic gets (took 5ms) queried data (took 0ms) split data by sensor (took 981ms) prepared column labels/types (took 0ms) prepared json (took 27ms) created context (took 0ms) For the sake of completeness, the timing function is as follows: def print_elapsed_time(ref_datetime, description): print('{} (took {}ms)'.format(description, floor((datetime.now()-ref_datetime).microseconds/1000))) return datetime.now() The code performing the processing and generating the view is as-follows: def simpleview(request): time_marker = datetime.now() device_name = request.GET['device'] device … -
Word frequency and authors names
I create a django rest api that should return: 10 most common words with their number available at the address / stats / and The 10 most common words with their numbers per author available under the address / stats / / This script finds the addresses of subpages with articles and collect the data from them. how to add a functions to the scraper that will return these words? import requests from bs4 import BeautifulSoup as bs from selenium import webdriver url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent' : 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page-number').text.split('/')[1]) for page in range(2, num_pages + 1): r = s.get(url.format(page)) soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) all_links = [item for i in all_links for item in i] d = webdriver.Chrome() for article in all_links: d.get(article) soup = bs(d.page_source, 'lxml') [t.extract() for t in soup(['style', 'script', '[document]', 'head', 'title'])] visible_text = soup.getText() # here I think you need to consider IP rotation/User-Agent changing try: print(soup.select_one('.post-title').text) except: print(article) print(soup.select_one('h1').text) break … -
Im using Django as Backend and Reactjs as Frontend, So what must i use to route the urls
What must i use for routing urls? Using React-Router or Urls from Django? ReactJS Route: <Router> <Route path="/" exact component={StatefullComponent} /> <Route path="/blog" exact component={BlogPost} /> <Route path="/blog/detail/:id" component={DetailPost} /> </Router> Django Route(Urls): urlpatterns = [ url(r'^blog/', include('blog.urls', namespace='blog')), ] Question: 1.Which route is better? 2.Can i use both route for my urls? 3.If i use django urls, my frontend will using single page route like react did? -
Enforce field uniqueness to parent in many-to-one relation
I have Table models which are many-to-one with a Restaurant model. Is there a way to have a field reference_label in the Table model that must be unique per restaurant, but not across different restaurants? In short, I want to enforce reeference_label uniqueness for tables with the same foreign key. I know I can just use the Table's id, but I want each restaurant to be able to customize how they label their tables. -
Word frequency View and Models
My task is to create a rest api which retrieves the content of articles and their authors from the website. I created a django project, I wrote a scrapy script and created a postgresql database. How to create View and Models in django that will give the following results? : 10 most common words with their number available at the address / stats / The 10 most common words with their numbers per author available under the address / stats / / posts authors with their name available in the address / stats / / available under the address / authors / -
How to access a child-template-variable from the base one? If that's even possible
I have a base.html template in which i'll include two different headers, but only one of them will show up depending on a variable I want to declare on the child template. I read on this jinja page that "because assignments outside of blocks in child templates are global and executed before the layout template is evaluated it’s possible to define the active menu item in the child template" So this is what I was hoping to do: base.html: {% if header_type == "header1" %} {% include '/header_1.html' %} {% endif %} {% if header_type == "header2" %} {% include '/header_2.html' %} {% endif %} And on the header_1.html file I was hoping to set a variable like header_type = "header1". Basically the child-page will tell which header should be rendered, but it seems I'm not able to do that. I'm not entirely sure this is the best way of achieving this "dynamic header", if anyone has any better suggestion. -
Can not use link with url to admin page 'django.urls.exceptions.NoReverseMatch'
I'm trying to add link to Django admin page, but it won't load page with this link because trows "django.urls.exceptions.NoReverseMatch: Reverse for 'admin' not found. 'admin' is not a valid view function or pattern name." Django v2.2.1 urls.py: from django.conf.urls import url from django.contrib import admin from django.urls import path from MyApp import views urlpatterns = [ path('', views.index, name='index'), path('admin/', admin.site.urls, name='admin'), url(r'^login/$', views.LoginFormView.as_view(), name='login'), url(r'^logout/$', views.LogoutView.as_view(), name='logout'), ] index.html: <a href="{% url 'admin' %}"> <div class="menu-btn">admin</div> </a> -
127.0.0.1 refused to connect in docker django
I'm trying to connect to an instance of django running in docker. As far as i can tell I've opened the correct port, and see in docker ps that there is tcp on port 8000, but it there is no forwarding to the port. After reading the docker compose docs on ports, i would expect this to work (I can view pgadmin on 127.0.0.1:9000 too). My docker compose: version: '3' services: postgresql: restart: always image: postgres:latest environment: POSTGRES_USER: pguser POSTGRES_PASSWORD: pgpassword POSTGRES_DB: pgdb pgadmin: restart: always image: dpage/pgadmin4:latest environment: PGADMIN_DEFAULT_EMAIL: admin@admin.com PGADMIN_DEFAULT_PASSWORD: admin GUNICORN_THREADS: 4 PGADMIN_LISTEN_PORT: 9000 volumes: - ./utility/pgadmin4-servers.json:/pgadmin4/servers.json depends_on: - postgresql ports: - "9000:9000" app: build: . environment: POSTGRES_DB: pgdb POSTGRES_USER: pguser POSTGRES_PASSWORD: pgpassword POSTGRES_HOST: postgresql volumes: - .:/code ports: - "127.0.0.1:8000:8000" - "5555:5555" depends_on: - postgresql - pgadmin I have tried with the following combinations for (app) ports, as are suggested here: ports: - "8000" - "8000:8000" - "127.0.0.1:8000:8000" but i still see This site can’t be reached 127.0.0.1 refused to connect. on trying to access the site. I'm sure that this is a port forwarding problem, and that my server is turning correctly in django because i can run a docker attach to the container and … -
private and public field in Django REST Framework
I want to have a list of public and private recipes, hiding all private recipes unless it's owner's. I created a manager for this: class RecipeManager(models.Manager): def public_recipes(self, *args, **kwargs): return super(RecipeManager, self).filter(private=False) def private_recipes(self, *args, **kwargs): user = kwargs.pop('user') return super(RecipeManager, self).filter(private=True, user=user) class Recipe(models.Model): name = models.CharField(max_length=100) recipe = models.CharField(max_length=200) private = models.BooleanField(default=False) views.py: class RecipeViewSet(viewsets.ModelViewSet): queryset = Recipe.objects.all() serializer_class = RecipeSerializer permission_classes = (AllowAny,) serializers.py: class RecipeSerializer(serializers.ModelSerializer): class Meta: model = Recipe fields = ('id', 'name', 'recipe', 'total_ingredients') depth = 1 So, where can I use the methods public_recipes, private_recipes or is there a better solution for this? -
How to use django pagination by date
I am making a simple timesheet django app and want to find a way to paginate the list view by "work weeks" so a page left or right loads the previous or next work week? I have been able to get the current week to filter correctly and with no filtering I can paginate by # of entries but this is not what I want. Here is my view code. class UserListView(ListView): model = Tsheet template_name = 'empTime/user_entries.html' # app/model_viewtype.html context_object_name = 'db' paginate_by = 7 def get_queryset(self): date = datetime.date.today() beginWeek = date - datetime.timedelta(date.weekday()) endWeek = beginWeek + datetime.timedelta(7) u = get_object_or_404(User, username=self.kwargs.get('username')) return Tsheet.objects.filter(name = u).filter(workDate__range=[beginWeek,endWeek]).order_by('workDate') def get_context_data(self, **kwargs): extraData = super(UserListView,self).get_context_data(**kwargs) extraData['n'] = self.request.user return extraData -
Persist HTMLSession in Django
What is the best method of persisting a HTMLSession in Django between different views? I use the request.session to persist some data between views, but I can't find a solution to also persist the HTMLSession. For example, I use requests-html to create a HTMLSession to grab a link, but I have a few more views that will do different things but needs access to the same HTMLSession. Data that I need to persist I store in request.session which is working fine, I just can't figure out how to persist the HTMLSession. I've tried serializing the HTMLSession, however, further investigation lead to me to realize these should NOT be serializable, and only iterate over the HTMLSession data and serialize those. Custom class from requests_html import HTML, HTMLSession class Foo(): def __init__(self): session = HTMLSession() views.py def get_item(request): foo = Foo() request.session['item'] = 'test' return HttpResponse('test') # Foo() initializes the HTMLSession # Need to use that same session between each view def show_item(request): item = request.session['item'] return HttpResponse('test') Code above doesn't make sense, just trying to show what I'm trying to achieve. Is this possible? Or am I completely misunderstanding something? -
"No module named 'mysite'" error when trying to run "python3 manage.py migrate"
When trying to run: python3 manage.py migrate I get: ModuleNotFoundError: No module named 'mysite' Viewed other questions, and none of them relate to my issue. I believe it's something incorrectly configured with Django and not my site, because this error shows up with any project I try to do, both inside and outside virtualenvs. Also when I run django-admin it displays a warning at the bottom: Note that only Django core commands are listed as settings are not properly configured (error: No module named 'mysite').