Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to dockerize Django app, Docker cannot find ft2build.h
I'm new to Docker and I'm trying to dockerize a Django app: FROM python:3.10.8-alpine3.15 ENV PYTHONUNBUFFERED=1 WORKDIR /app RUN apk update \&& apk add --no-cache gcc musl-dev postgresql-dev python3-dev libffi-dev \&& pip install --upgrade pip COPY ./requirements.txt ./ RUN pip install -r requirements.txt COPY ./ ./ CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] But when I run docker build -t sometag . I receive the following error: #9 23.05 Preparing metadata (setup.py): started #9 23.32 Preparing metadata (setup.py): finished with status 'error' #9 23.33 error: subprocess-exited-with-error #9 23.33 #9 23.33 × python setup.py egg_info did not run successfully. #9 23.33 │ exit code: 1 #9 23.33 ╰─> [10 lines of output] #9 23.33 ##### setup-python-3.10.8-linux-x86_64: ================================================ #9 23.33 ##### setup-python-3.10.8-linux-x86_64: Attempting build of _rl_accel #9 23.33 ##### setup-python-3.10.8-linux-x86_64: extensions from 'src/rl_addons/rl_accel' #9 23.33 ##### setup-python-3.10.8-linux-x86_64: ================================================ #9 23.33 ##### setup-python-3.10.8-linux-x86_64: =================================================== #9 23.33 ##### setup-python-3.10.8-linux-x86_64: Attempting build of _renderPM #9 23.33 ##### setup-python-3.10.8-linux-x86_64: extensions from 'src/rl_addons/renderPM' #9 23.33 ##### setup-python-3.10.8-linux-x86_64: =================================================== #9 23.33 ##### setup-python-3.10.8-linux-x86_64: will use package libart 2.3.21 #9 23.33 !!!!! cannot find ft2build.h #9 23.33 [end of output] #9 23.33 #9 23.33 note: This error originates from a subprocess, and is likely not a problem with pip. #9 23.33 … -
How to Run an ML model with Django on Live server
I have a Django project that uses a public ML model("deepset/roberta-base-squad2") to make some predictions. The server receives a request with parameters which trigger a queued function. This function is what makes the predictions. But this works only on my local. Once I push my project to a live server, the model no starts to run but never completes. I have tried to set up the project using different guides, to avoid my project downloading the ML model every time a request is made, but it doesn't solve it. I don't know what else to do, please. If there's any extra information needed, I can provide. Here is my setup as it is now: views.py class BotView(GenericAPIView): serializer_class = BotSerializer def post(self, request, *args, **kwargs): try: serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() print(serializer.data) return Response(data=serializer.data, status=status.HTTP_200_OK) except Exception as e: print(str(e)) return Response(data=str(e), status=status.HTTP_400_BAD_REQUEST) serializers.py from .tasks import upload_to_ai class BotSerializer(serializers.Serializer): questions = serializers.ListField(required=True, write_only=True) user_info = serializers.CharField(required=True, write_only=True) merchant = serializers.CharField(required=True, write_only=True) user_id = serializers.IntegerField(required=True, write_only=True) def create(self, validated_data): # call ai and run async upload_to_ai.delay(validated_data['questions'], validated_data['user_info'], validated_data['merchant'], validated_data['user_id']) return "successful" tasks.py from bot.apps import BotConfig from model.QA_Model import predict @shared_task() def upload_to_ai(questions:list, user_info:str, merchant:str, user_id:int): model_predictions = predict(questions, BotConfig.MODEL, … -
Best implementation for working hours of multiple users in week in Django
I would like to understand the best implementation to manage the working hours of a user which could also be divided into different time slots. example: from 8:00 to 12:00 and from 15:00 to 18. For now I was proceeding like this: class WorkHoursDay(models.Model): weekday = models.CharField(choices=WEEKDAYS, max_length=255) from_hour = models.TimeField(choices=TIME) to_hour = models.TimeField(choices=TIME) barber = models.ForeignKey(Barber, on_delete=models.CASCADE) class Meta: ordering = ('weekday', 'from_hour') unique_together = (('weekday', 'barber'),('from_hour', 'to_hour')) The TIME list is developed like this: [8:00, 8:05, 8:10...]. In this way I'm going to manage the users' working hours day by day by generating an object for each day and I don't know how good it is. Sounds like dirty programming to me. -
Redirection to previous page after login using LoginRequiredMiddleware
I used to use next_param = request.POST.get('next') to redirect users to their previous page after they log in. I however, decided to go fancier with my code and now force any unauthenticated user to login by using LoginRequiredMiddleware: users are automatically redirected to login page if not authenticated. This allows me to avoid having to call a decorator for all views. Instead, specify the accessible views that don't require the user to be logged in. Small problem: my next_param = request.POST.get('next')doesnt work now for obvious reason: I cannot stick ?next={{ request.path|urlencode}} in the referring page since the redirection happens automatically and the user doesnt have to click anywhere. What alternative do I have to redirect the user to the initial/previous page they landed on before being redirected automatically? base.py MIDDLEWARE = [ .. 'mysite.middleware.LoginRequiredMiddleware', ] middleware.py import re from django.conf import settings from django.shortcuts import redirect EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: pass def __init__(self, get_response): self.get_response = get_response def __call__ (self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request,'user') path = request.path_info.lstrip('/') print(path) if not request.user.is_authenticated: if not any(url.match(path) for url in EXEMPT_URLS): return … -
how to upload pdf file and excel sheet in one submit?
I have a django application and I try to upload a pdf file and a excel file with one submit function. So The pdf function works. But If I try to upload a excel sheet then I get this error: 'utf-8' codec can't decode byte 0xa0 in position 16: invalid start byte But I tested the excel function seperately and that works. But apperently combing with the pdf function it doesn't work. So this is the template: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ pdf_form }} </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </div> <div class="d-grid gap-3"> <div class="form-group"> {{ excel_form }} </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{conten_excel}}</textarea> </div> </div> </div> <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </form> </div> </span> </div> </body> </html> {% endblock … -
Need to be superuser to edit a file of a django app. The django project has a Docker Container
I have cloned, followed the instructions, and setup the Docker, Django, Postgres project from Docker's Github on my Linux machine. I used docker compose run web django-admin startapp auth to setup the app's directory. When I edit a file in auth, e.g. auth/models.py, I get an insufficient permissions error message. auth/ is owned by root, which is confusing because manage.py is owned by me. I ran sudo chown -R $USER:$USER composeexample manage.py as instructed by the ReadMe. I don't want to have to chown each new app I make. -
How to pass a variable to class based views (ListView)
My Views.py code class ListaFuncionariosView(ListView): model = Funcionarios template_name = '../templates/funcionarios/lista_funcionarios.html' paginate_by = 10 ordering = ['FuncionarioCartao'] queryset = Funcionarios.objects.filter(EmpresaCodigo=1) funcionarios_number = Funcionarios.objects.aggregate(Count('FuncionarioCartao')) My HTML <h1>Good Morning</h1> Exists: {{funcionarios_number}} <br> {{funcionarios}} I would like to show the total number of registered employees in my db table (in the HTML file below), but I don't know how to put variables in class based views, in this case ListView. I'm using 4.0 Django I tried put: funcionarios_number = Funcionarios.objects.aggregate(Count('FuncionarioCartao')) in bellow of my class, but this is not showed in my html. -
How to insert new string to DB by button Django
How to insert new string to DB by button Django and take id new record <a href="{% url "main:create_bd_line" %}"><button type="button" class="btn btn-secondary">Начать</button></a> def create_bd_line(request): user_group = request.user.groups.values_list() university = user_group[0][1] -
How to automatically add '/static/' in every url that loading files
I want to use static without {% load static %}, just a raw html. How can I automatically add 'static' in every url, that loading any file. For example, site requesting file in "/js/script.js", but I want to get "/static/js/script.js" url. How can I do this?Shall I use middleware or it would be some easiest way? Thanks! -
display commas instead of periods
in my sql table I have decimal data with dot as a separator but the display in my page is done with commas I would like to display them with dot in my settings i have this LANGUAGE_CODE = "fr-fr" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True my models class VilleStation(models.Model): nomVille = models.CharField(max_length=255) adresse = models.CharField(max_length=255) cp = models.CharField(max_length=5) latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) in the templates i have this {% for c in object_list %} {{c.nomVille}} {{c.adresse}} {{c.cp}} {{c.latitude}} {{c.longitude}} {% endfor %} thank -
Django fullstack developer
What do I need to learn in order to connect the frontend to a ready-made backend on a django? I tried googling, but after a few inaccurate answers I decided to ask the question here -
Performing Boolean Logic in views and template
am having two set of challenges. First, I have a model with field submit as Boolean field. I use model form and render it in template. There are two options as Boolean select i.e. 'Yes' and 'No' option for user to select whether he want to save the form or not. I want if this user select 'Yes', the form should be save. else if he select 'No', the form should not be save. I have exhausted all the logics that i thought could work but cannot achieve this. Below is the views views.py def submit(request): if request.method =='POST': form = submitForm(request.POST) form.instance.user = request.user sub = form.save() if sub.sumit ==True: if sub: messages.info(request, 'You have submitted you form successfully') return redirect('home') messages.info(request, 'Continue editing your data') return render(request, 'portal/home/submit.html') form =submitForm() context = { 'form':form, # 'sub':sub } return render(request, 'portal/home/submit.html', context) my second question is in this view. since I could not achieve what i wanted in the above form, i just query it in this user_info so that if user save the submit as 'Yes' or 'No' some certain buttons in template should or should not show. below is how i try but not exactly what i … -
ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, environment variable DJANGO_SETTINGS_MODULE
I'am getting this error: I cannot see the Filters botton in Filter back ends with URL query parameters. raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This my api_views.py file: from rest_framework.generics import ListAPIView from django_filters.rest_framework import DjangoFilterBackend from store.serializers import ProductSerializer from store.models import Product class ProductList(ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('id',) Here is my wsgi.py file: import os import sys from django.core.wsgi import get_wsgi_application path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if path not in sys.path: sys.path.append(path) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'store', ] REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } and the manage.py code: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Can anyone seem to understand the … -
How can I redirect the user to another template after a search?
I have a search form where the models an user searches are displayed bellow the search form but I want it to be shown in another page. I tried looking for a way to redirect the user to another url when the search is done and display the filtered data there but I wasn't able to do that. model: class Product(models.Model): author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=120, unique=True) date_posted = models.DateTimeField(default=timezone.now) ... view: def FilterView(request): qs = Product.objects.all() title_contains_query = request.GET.get('title_contains') title_or_author_query = request.GET.get('title_or_author') ... if is_valid_queryparam(title_contains_query): qs = qs.filter(title__icontains=title_contains_query) elif is_valid_queryparam(title_or_author_query): qs = qs.filter(Q(title__icontains=title_or_author_query) | Q(author__username__icontains=title_or_author_query)).distinct() ... context = { 'queryset': qs, ... } return render(request, 'main/form.html', context) template: <form method="GET"> <div> <input type="search" name="title_contains" placeholder="Title contains"> <span><div><i class="fa fa-search"></i></div></span> </div> <div> <input type="search" name="title_or_author" placeholder="Title or author"> <span> <div><i class="fa fa-search"></i></div> </span> </div> ... <button type="submit">Search</button> </form> <div> <ul> {% for product in queryset %} <li> {{ product.title }} <span>Author: {{ product.author.name }}</span> </li> <hr /> {% endfor %} </ul> </div> -
Django Conditional to remove css class if not on main url
Im wondering if someone could help me figure this out; Working on a web app using the django framework and for my navbar, I have a css class that makes it transparent on the main page. This of course worked on a static website, but does not in django. How can i write an if statement to only apply this class on a specific url - the home page? {% load static %} <header id="home"> <!-- Navbar --> <nav id="navbar" class="main-page"> <a href="{% url 'home' %}"><img src="{% static 'images/farmec-logo-2.png' %}" alt="" id="logo"></a> <ul> <li><a href="{% url 'home' %}" class="current">Home</a></li> <li><a href="{% url 'teams' %}">About</a></li> <li><a href="blog.html">Blog</a></li> <li><a href="suppliers.html">Suppliers</a></li> <li><a href="parts.html">Spare Parts</a></li> </ul> </nav> </header> #navbar { display: flex; justify-content: space-between; padding-top: 1rem; position: absolute; background: transparent; width: 100vw; z-index: 1; background: var(--dark-color); transition: 0.5s ease-in; } #navbar.main-page { background: transparent; } -
Celery (worker) getting tasks with producer (Django) shutdown
I am using Celery as a worker for Django API calls. My current stack is: Producer: Django app Message Broker: Redis server Consumer: Celery app The issue is: If my Django app is shutdown, and I have the redis-server running, and start the worker with: python3 -m celery -A b3 worker -l info It starts getting tasks, which doesn't make much sense since my producer isn't producing any tasks. Celery getting tasks My tasks.py: @shared_task() def fetch_stock_task(company_code: str): ... -
djangocms Currently installed Django version 3.2.15 differs from the declared 3.1
I am running an AWS Bitnami Django instance. Django 3.2.15 installed by default. Django documentation recommends version django 3.2 so all is good there. Once installed I am having a hard time getting djangocms to create a new project. I keep getting dependency errors when I issue the command djangocms -f -p . projectname I received the following: Currently installed Django version 3.2.15 differs from the declared 3.1. Please check the given `--django-version` installer argument, your virtualenv configuration and any package forcing a different Django version -
In django email autosave Doesn't work(all files in git)
i have created an study project, the aim of it to create website where you can recover your password, but after registration password doesn't save. https://github.com/ErikArabyan/Authentication I've try to find mistakes, but i couldn't, help me please. -
Django-filters do not work. Data do not changes
Can you help me ? Request is sending, but data returning the same. My url after hitting submit button changes to get request, but my list do not changes. logs.html - https://prnt.sc/kuIjkitL_PF7 https://prnt.sc/SLurDBigzwkQ views.py - https://prnt.sc/uxyvsAQrQb7C https://prnt.sc/UneurdsO-gsU filters.py - https://prnt.sc/D-zMk5MV3MQq -
in Django sql table with dots as a decimal separator but in the admin are displayed with commas
I have this error in Django error during template rendering .... argument must be int or float I wonder if it's because in my sql table I have columns with coordinates that have dots as a separator but when I look at the display in the admin these coordinates are displayed with commas my models : class VilleStation(models.Model): nomVille = models.CharField(max_length=255) adresse = models.CharField(max_length=255) cp = models.CharField(max_length=5) latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) def __str__(self): return self.nomVille in my settings LANGUAGE_CODE = "fr-fr" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True DECIMAL_SEPARATOR = True thank -
TypeError: '>' not supported between instances of 'CombinedExpression' and 'int'
I got this product model: class Product(models.Model): quantity = models.DecimalField(max_digits=10, decimal_places=2, default=0) price = models.DecimalField(max_digits=10, decimal_places=2, default=0) @property def value(self): return F('quantity') * F('price') when I call .value on product instance I got in return: product.value // returns 14 but when I check condition: for product in Product.objects.all(): while (product.value > 0): ... I got this error: TypeError: '>' not supported between instances of 'CombinedExpression' and 'int' I have not found an existing question about this problem. How to solve it? -
ImportError: Couldn't import Django. in my vscode terminal it's strange
(myenv) baeg-ingeol@baeg-ingeol-ui-MacBookAir mysite % python manage.py runserver Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (myenv) baeg-ingeol@baeg-ingeol-ui-MacBookAir mysite % pip list when i run my manage.py, compiler say error but i already pip django,, and i tryed check my django version in terminal and install django. It comes out in the code below. please help... (myenv) baeg-ingeol@baeg-ingeol-ui-MacBookAir practice % python -m django --version /usr/local/bin/python: No module named django (myenv) baeg-ingeol@baeg-ingeol-ui-MacBookAir practice % pip install django Requirement already satisfied: django in /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages (4.1.3) Requirement already satisfied: asgiref<4,>=3.5.2 in /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages (from django) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages (from django) (0.4.3) run manage.py, solve this problem -
Why my app is not find (ModuleNotFoundError: No module named '<app_name>')?
I'm trying to create an API for my blog with django rest framwork and when I execute the following command : python manage.py makemigrations posts This Error appears : Traceback (most recent call last): File "/Users/xxx/dev/api/blog/blog/../manage.py", line 22, in <module> main() File "/Users/xxx/dev/api/blog/blog/../manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/xxx/dev/api/blog/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/xxx/dev/api/blog/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/xxx/dev/api/blog/env/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/xxx/dev/api/blog/env/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/xxx/dev/api/blog/env/lib/python3.9/site-packages/django/apps/config.py", line 178, in create mod = import_module(mod_path) File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'posts' settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "posts.apps.PostsConfig", ] . ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-39.pyc │ ├── settings.cpython-39.pyc │ └── urls.cpython-39.pyc ├── asgi.py ├── posts │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── … -
I get 502 Bad Gateway nginx/1.22.0 (Ubuntu) when deploying django app to linode with gunicorn and nginx
I'm deploying a django app to linode with gunicorn and nginx. I have followed a few different tutorials, but for the setting up of gunicorn and nginx I followed this, which took me to the end with no errors, but at the end I got 502 Bad Gateway error from nginx when trying to open the url directly on my browser. The error.log I get when refreshing the page is the following: tail -f /var/log/nginx/error.log 2022/11/20 11:24:33 [crit] 4949#4949: *5 connect() to unix:/home/djangouser/djangoproject/djangoproject.sock failed (13: Permission denied) while connecting to upstream, client: 181.43.95.34, server: 555.555.55.555, request: "GET / HTTP/1.1", upstream: "http://unix:/home/djangouser/djangoproject/djangoproject.sock:/", host: "555.555.55.555" (The IP, user and project names have been changed, not sure if this is unsafe, but just in case) The relevant settings are as follows: ufw status on server: To Action From -- ------ ---- 22/tcp ALLOW Anywhere Nginx Full ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) Nginx Full (v6) ALLOW Anywhere (v6) /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=djangouser Group=www-data WorkingDirectory=/home/djangouser/djangoproject ExecStart=/home/djangouser/djangoproject/.venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/djangouser/djangoproject/djangoproject.sock polman_project.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/djangoproject server { listen 80; server_name 555.555.55.555; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangouser/djangoproject; } location / { … -
How Should i import the Model Class on django to other py file to use it?
I wanted to insert model instance to database from a file. i wrote a python program to do so by importing models. but every time i get this error; ModuleNotFoundError: No module named 'exams' i have tried putting the file in the same folder; then i got "Relative import error" the expected result was to save model instance in the database.