Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to create password protected folder with django?
I want to create an application where user can upload their secret documents. Secret means no one can see the document even the super admin of the server can't even see the document. In other words I want system level authentication. Is there a way to do it with Django? How should I overcome this problem? I have a VPS to store files but I want to create separate document folder for each user which can only be accessed by the user. Not even by me or by the server admin. Any idea would be appreciated. What should be my approach? -
Docker Compose ENTRYPOINT and CMD with Django Migrations
I've been trying to find the best method to handle setting up a Django project with Docker. But I'm somewhat confused as to how CMD and ENTRYPOINT function in relation to the compose commands. When I first set the project up, I need to run createsuperuser and migrate for the database. I've tried using a script to run the commands as the entrypoint in my Dockerfile but it didn't seem to work consistently. I switched to the configuration shown below, where I overwrite the Dockerfile CMD with commands in my compose file where it is told to run makemigrations, migrate, and createsuperuser. The issue I'm having is exactly how to set it up so that it does what I need. If I set a command (shown as commented out in the code) in my compose file it should overwrite the CMD in my Dockerfile from what I understand. What I'm unsure of is whether or not I need to use ENTRYPOINT or CMD in my Dockerfile to achieve this? Since CMD is overwritten by my compose file and ENTRYPOINT isn't, wouldn't it cause problems if it was set to ENTRYPOINT, since it would try to run gunicorn a second time … -
JWT Authentication with Django REST Framework
I am having some trouble authenticating requests to a Django REST endpoint. I have a token-auth URL which points towards rest_framework_jwt.views.obtain_jwt_token, e.g.: urlpatterns = [ path('token-auth/', obtain_jwt_token), path('verify-token/', verify_jwt_token), path('current_user/', CurrentUserView.as_view()), ] where CurrentUserView is: class CurrentUserView(APIView): def post(self, request): print(request.user) serializer = UserSerializer(request.user) return Response(serializer.data) if I create a token in the browser by visiting http://localhost/token-auth/, I can then verify it using the command: curl -X POST -H "Content-Type: application/json" -d '{"token":<MY_TOKEN>}' http://localhost/verify-token/ however the same request called to the http://localhost/current_user/ returns a 400 code: curl -X POST -H "Content-Type: application/json" -d '{"token":<MY_TOKEN>}' http://localhost/current_user/ {"detail":"Authentication credentials were not provided."} Framework settings are: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } And Django is being run in a container with the following Dockerfile: FROM python:3 WORKDIR /code COPY requirements.txt requirements.txt RUN pip install -r requirements.txt COPY . . ENV PYTHONUNBUFFERED=1 EXPOSE 8000 -
Django annotate and order by multiple fields
I have the following model: FileObject(models.Model): region = models.ForeignKey() include_in_lookup = models.BooleanField() date = models.DateField() ... I'm trying to fix a query that is supposed to grab the latest entry based on the region and date. The goal is for each region, return the latest (most recently dated) entry (via the datefield) I can achieve that when I use the following query: from django.db.models import Max obj.filter( include_in_source_lookup=True ).values("region__name").annotate(Max("date")).order_by("region__name") >>> [{'region__name': 'Alabama', 'date__max': datetime.date(2018, 8, 23)}, {'region__name': 'Alaska', 'date__max': datetime.date(2018, 10, 20)}, {'region__name': 'Arizona', 'date__max': datetime.date(2018, 11, 4)}, ... Curiously, when I don't include the order_by, It doesn't seem to work in that it returns all the entries in the database. I know this has to do w/ how order_by is used in conjunction with values but am unsure how that works exactly.. Furthermore, If I want to pass a list of values, how can I get consistency given the way order_by works? Eg: GROUP_FIELDS = ['region', 'date'] obj.filter( include_in_source_lookup=True ).values(*GROUP_FIELDS).annotate(Max("date")).order_by(*GROUP_FIELDS) I've tried many variations of .annotate, .values, and .order_by while trying to use a list of values, but can't get the result from the first QuerySet where theres just one region per latest date. What do I need to … -
How do I update a table column with Django?
I'm trying to create an app with a form that when submitted, updates a table in my database based on the info submitted, but I'm not sure how to go about it. Currently, I have a simple mode: class Client(models.Model): company_name = models.CharField(max_length=200) launchpad_id = models.PositiveIntegerField() client_email = models.EmailField() content_id = models.CharField(max_length=200) def __str__(self): return self.company_name + ' | ' + self.content_id and my databases configured like so: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_project', 'USER': 'xxx', 'PASSWORD': 'xxx', 'HOST': 'xxxx', 'PORT': 'xxx', }, 'info': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'reporting_database', 'USER': 'xxx', 'PASSWORD': 'xxx', 'HOST': 'xxx', 'PORT': 'xxx', } } What I want to happen is when I submit my fields through the Client model either in admin or a template, it updates my client_info table in the reporting_database. I cant seem to figure out how to make that connection work though. I would appreciate any direction you can give me. Thanks. -
Refactoring custom save method for a model
In the following model, I am overriding its save method to use field's default value instead of null whenever null is encountered. The method works, but is wordy. Is there a cleaner way of achieving the same? class Activity(models.Model): date_added = models.DateTimeField(auto_now_add=True) number = models.IntegerField(default=0) athlete = models.ForeignKey(Athlete, on_delete=models.CASCADE, default=None) start_date = models.DateTimeField(default=datetime.datetime.now) name = models.TextField(default="Unassigned") country = models.TextField(default="Unassigned") link = models.TextField(default="Unassigned") segment_efforts = models.TextField(default="Unassigned") distance = models.FloatField(null=True) average_speed = models.FloatField(null=True) def save(self, *args, **kwargs): # overriding model's save method to use default field value instead of null, when null is encountered in JSON fields = self._meta.get_fields() for field in fields: field_value = getattr(self, field.name) if field_value == None: field_att = self.__class__._meta.get_field(field.name) default_value = field_att.get_default() field_value = setattr(self, field.name, default_value) return super(Activity, self).save(*args, **kwargs) -
run command in node virtual enviorment inside other django viertual enviorment
I would like run a sh script from Django to create and install node virtual environment inside django virtual environment default for the project. In theory the steps will be, after press button in django template, get the request in a view and run a sh file with a subprocess django syntax tool. The sh file will contain node commands to create the environment. It’s possible ? If it’s yes, anybody could give me a simple guidelines. Thanks in advance. -
Django ManyToManyField.throug
i am pretty new to coding and stuck on this problem since many hours but i couldn't figure out what is the problem. As far as i understand my code well, it seems it should be identical to the one in the django docs, but i can't find my problem. I would like to have a model like the following An article can be bought by different Supplieres (manytomany) Each Supplier as different Articles (manytomany) And i would like to make this through the table 'Details' to get more information and there is the Problem. Since i have added the 'through' table it is not working anymore (sorry for my bad english and stupid question) With kind regards Thomas https://github.com/Val1dor/dj1/blob/master/tutorial/models.py -
Django Form Fields Appear Dynamically
I have a form in my Django app that contains an upwards of 20 fields. It has been requested that I have only the first few fields display. Once those fields are filled out, the next few fields should be displayed, in addition to the previous fields. How might I accomplish this? The following is my forms.py class QuoteForm(forms.Form): premium_station = forms.IntegerField(max_value=2000, min_value=0, required=False, widget = forms.NumberInput(attrs={'class' : 'form-control', 'placeholder' : '# Premium Admin Stations Needed'})) standard_station = forms.IntegerField(max_value=2000, min_value=0, required=False, widget = forms.NumberInput(attrs={'class' : 'form-control', 'placeholder' : '# Standard Admin Stations Needed'})) basic_station = forms.IntegerField(max_value=2000, min_value=0, required=False, widget = forms.NumberInput(attrs={'class' : 'form-control', 'placeholder' : '# Basic Admin Stations Needed'})) messaging_station = forms.IntegerField(max_value=2000, min_value=0, required=False, widget = forms.NumberInput(attrs={'class' : 'form-control', 'placeholder' : '# Messaging Stations Needed'})) auto_attendant = forms.IntegerField(max_value=2000, min_value=0, required=False, widget = forms.NumberInput(attrs={'class' : 'form-control', 'placeholder' : '# Auto Attendants Needed'})) toll_service = forms.IntegerField(max_value=2000, min_value=0, required=False, widget = forms.NumberInput(attrs={'class' : 'form-control', 'placeholder' : '# Toll-Free Services Needed'})) receptionist = forms.IntegerField(max_value=2000, min_value=0, required=False, widget = forms.NumberInput(attrs={'class' : 'form-control', 'placeholder' : '# Receptionist Clients Needed'})) group_paging = forms.IntegerField(max_value=2000, min_value=0, required=False, widget = forms.NumberInput(attrs={'class' : 'form-control', 'placeholder' : '# Group Paging Needed'})) FourG_backup = forms.IntegerField(max_value=2000, min_value=0, required=False, widget = forms.NumberInput(attrs={'class' : 'form-control', … -
Do I have to re-render my page after updating template data
First I have searched and seen another answer, but it doesn't address my need. I am trying to POST data using jQuery/AJAX from my HTML to update a list that is also on my HTML. When I first rendered my template, it had two list-group containers of which the left container is pre populated. two containers The choice made user makes on the left container determines the list group data of the right container. I wanted to send back to the backend Python (server) which selection the user made from the left container, so that I may populate the appropriate list for the second (right) container. This is why I used the POST method using jQuery/AJAX to send users selection. HTML Here is a Plnkr of the HTML Below is the jQuery/AJAX implementation which WORKS. It sends data back to Python (to my views.py): JS/jQuery/AJAX: <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script> $("#leftContainer > a").click(function(event){ event.preventDefault(); $("#leftContainer > a").removeClass("active"); $(this).addClass("active"); var leftDataSet = parseInt($(this).attr("data-set")); var item_selected = $(this).text(); var item_index = $(this).attr("id") //Users selection to send $.ajax({ type:'POST', url:"home/view_results/onclick/", data:{ selected_item:item_index, csrfmiddlewaretoken:"{{ csrf_token }}" }, dataType:"json", success: function(){$('#message').html("<h3>Data Submitted!</h3>") } }) }); $("#rightContainer > a").click(function(event){ event.preventDefault(); $(this).toggleClass("active"); }); </script> views.py #app/views.py from django.shortcuts import … -
How to create multiple card views without copy pasting
Im currently creating a website which shows tv series and movies, I've so far created a cardview which shows only one movie and i obviously want to add more which is where my dilemma is. Is there a way to create more than one cardview in HTML without having to copy and paste a bunch of times? Here is my parent class in Django; <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> {% if title %} <title> {{ Flix | title }} </title> {% else %} <title> Flix </title> {% endif %} <link rel="stylesheet" href="/static/Css/Parent.css"> </head> <div class="CardView"> <img src= '{% block Images %}{% endblock %}' alt=""> <h5> {% block MovieInfo %}{% endblock MovieInfo %} </h4> </div> <body> </div class="mainContent"> {% block content %}{% endblock %} </body> </html> Here is the HomePage where the movies are displayed; {% extends "Movies/Parent.html" %} {% block Images %} {% for Movie in Movies %} {{ Movie.Image }} {% endfor %} {% endblock Images %} {% block MovieInfo %} {% for Movie in Movies %} <h5> {{ Movie.Name }} </h5> <h5> Rating: {{ Movie.Rating }}</h5> <h5> Date: {{ Movie.Date_Posted }} </h5> {% endfor %} {% endblock MovieInfo %} {% block MovieName %} {% for … -
Django Multiple Categories And Sub Categories
View Page Unless I comment out Category Slug, the Designer slug errors "No Category matches the given query" from django.shortcuts import render, get_object_or_404 from .models import Category, Product, Designer from cart.forms import CartAddProductForm from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator def product_list(request, category_slug=None, designer_slug=None): category = None designer = None categories = Category.objects.filter() designers = Designer.objects.filter() products = Product.objects.filter(available=True) count_filter = Product.objects.filter().count() # Query Data From Database # Create Pagination Ability page = request.GET.get('page', 1) paginator = Paginator(products, 48) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) if designer_slug: designer = get_object_or_404(Designer, slug=designer_slug) products = Product.objects.filter(designer=designer) context = { 'category': category, 'categories': categories, 'designer': designer, 'designers': designers, 'products': products, 'count_filter': count_filter } return render(request, 'shop/product/list.html', context) from django.urls import path from . import views app_name = 'shop' urlpatterns = [ path('', views.product_list, name='product_list'), path('/', views.product_list, name='product_list_by_category'), path('/', views.product_list, name='product_list_by_designer'), path('//', views.product_detail, name='product_detail'), ] -
Serializing models polymorphically in django
I've a inheritance model like this, Base class, class PrivateMessage(Base): sender = models.ForeignKey(User, related_name='privatemessage_set', on_delete=models.CASCADE, null=True) room = models.ForeignKey(PrivateRoom, on_delete=models.CASCADE, related_name='message_set', null=True) message_type = models.CharField(max_length=255, null=True) Children. class PrivateTextMessage(PrivateMessage): body = models.TextField(null=True, blank=True) class PrivateImageMessage(PrivateMessage): image = models.ImageField(upload_to=attachment_images_path, null=True, blank=True) I'm serializing them polymorphically, class PublicMessageSerializer(serializers.ModelSerializer): class Meta: model = PublicMessage fields = '__all__' def to_representation(self, obj): if isinstance(obj, PublicTextMessage): return PublicTextMessageSerializer(obj, context=self.context).to_representation(obj) elif isinstance(obj, PublicImageMessage): return PublicImageMessageSerializer(obj, return super(PublicMessageSerializer, self).to_representation(obj) class PublicTextMessageSerializer(serializers.ModelSerializer): sender = UserSerializer(read_only=True) receiver = RoomSerializer(read_only=True) class Meta: model = PublicTextMessage fields = ('id', 'sender', 'receiver', 'body', 'message_type', 'created', 'modified',) class PublicImageMessageSerializer(serializers.ModelSerializer): sender = UserSerializer(read_only=True) receiver = RoomSerializer(read_only=True) image = serializers.ImageField(use_url=True) class Meta: model = PublicImageMessage fields = ('id', 'sender', 'receiver', 'image', 'message_type', 'created', 'modified',) The problem is that only the fields that are there in the base class are rendered by the serializer. For example the image field in the PublicImageMessage never gets rendered. Can someone help me with the conditional rendering where all fields of the class are rendered. PS: The classes have a PublicMessageType object. I've tried using that and serializing, but outside of that being clunky, in that case the fields are rendered with null value. -
Django and Postgres, OperationalError when deleting an object
I have a Django app and a Postgres DB deployed and dockerized. This is my docker-compose.yml version: '3' services: web: build: . container_name: web command: python manage.py migrate command: python manage.py runserver 0.0.0.0:8000 volumes: - ./src:/src ports: - "8000:8000" depends_on: - postgres postgres: image: postgres:latest container_name: postgres environment: POSTGRES_USER: my_user POSTGRES_PASSWORD: my_secret_pass! POSTGRES_DB: my_db ports: - "5432:5432" Everything works great, I can create, update or delete objects of any of my 10 apps, however, when I try to delete an object of the class Story, which is the following, it fails: class Story(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField(blank=True, null=True) image = models.ImageField(upload_to="stories", null=True, blank=True) There are also a few other classes that have a ForeignKey to Story, such as Like, View or Comment. My problem is that I get an operational error whenever I try to delete a Story. The funny fact is that I can create or update as many stories as I want, just not delete them. When I try to delete any story, I get the following exception: OperationalError: FATAL: the database system is in recovery mode If I look at the queries performed, I see nothing wrong: DELETE … -
Django: what is the right href to individual url?
I have a model Post. Each individual post extends post_detail.html and has it's own url: urlpatterns = [ path('news/<int:pk>/', views.PostDetailView.as_view(), name='news_page'), ... ] The model consists of title, description, image etc. On main.html I show the title and the image of the last post, the second last post, and the third last post. My views.py looks like class PostListView(ListView): model = Post template_name = 'html/main.html' def get_context_data(self, **kwargs): posts = Post.objects.all().order_by('-id') kwargs['last_post'] = posts[0] kwargs['second_last_post'] = posts[1] kwargs['third_last_post'] = posts[2] return super().get_context_data(**kwargs) Here I have the title of the last and the second last post in my template: <h5 href="#">{{ last_post.title }}</h5> <h5 href="#">{{ second_last_post.title }}</h5> Now I want to connect these titles to their own urls. I mean when I click on the title of the last post in main.html I want to open individual url of that post. How can I do that? -
django models many subclasses
I am trying to make two subclasses of a model and call it in the following way: base_class.sub. But I can not do it since I can not put "sub" as related_name to the two subclasses class BaseClass(models.Model): name = models.CharField(max_length=20) class SubClassA(BaseClass): base_class = models.OneToOneField(BaseClass, parent_link=True, related_name='sub') class SubClassA(BaseClass): base_class = models.OneToOneField(BaseClass, parent_link=True, related_name='sub') -
Django-import-export customization with related fields
I need to update my table every time a new value of "sku" is entered (not to create a new entry), but it does have to happen only if the "client" selected is the same. If the "client" is different, then the model should add a new object with the same "sku", but with different "clients". One StackOverflow user gave me the solution: class ProductList(models.Model): id_new = models.IntegerField(primary_key=True) sku = models.CharField(primary_key=False, max_length=200) client = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=256) description = models.CharField(max_length=1000) storage = models.CharField(max_length=256) cost_price = models.CharField(max_length=256) sell_price = models.CharField(max_length=256) ncm = models.CharField(max_length=256) inventory = models.IntegerField(null=True) class Meta: unique_together = (('sku', 'client'),) def save(self, *args, **kwargs): if self.pk: current_instance = self.__class__.objects.get(pk=self.pk) if current_instance.client != self.client: self.pk = None return super(ProductList, self).save(*args, **kwargs) After I added the save function the problem got solved. However, if I try to update an existing table I get the following problem for each field in my file: Line number: 1 - get() returned more than one ProductList -- it returned 2! 345, Teste 1, Descrição 1, 87654, 59,99, 180, 65, 884, 25 Traceback (most recent call last): File "/home/checkstore/.local/lib/python3.6/site-packages/import_export/resources.py", line 453, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/home/checkstore/.local/lib/python3.6/site-packages/import_export/resources.py", line 267, in get_or_init_instance … -
Can I use different account to send mail via Gmail
I have a question, I want to send email via Gmail. Below is django code: EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = 'xxxx' #my gmail password EMAIL_HOST_USER = 'aaa@gmail.com' #my gmail username EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = 'bbb@example.com' CanI use different domain or address on DEFAULT_FROM_EMAIL? My other mail bbb@example.com is still use Google service(Google G Suite) Thanks. -
Django - How to represent the view count of any post in post app via highchart.js according to date
I have a basic django post app which displays post and its details when clicked , it also counts the view count.But actually i am unable to associate a time to when the post was actually viewed. I want to represent data on highchart.js for each day that how many time a post was viewed. The chart want to be horizontal and at each instance it shows recent 7 days data relative to each day. total a screen representing a graph with 7 columns of how may time post was viewed each day. If you can , pls include views.py and models.py for better understanding. -
How to have React Dev debug info available when DRF serves React
During development using Django Rest Framework (DRF) and ReactJS, I build my React frontend (npm run build), and then have the Django dev server serve the frontend files, through Django a Django view/views. (So, this may be repetition, but I am not running the React Dev server.) Now, the nice thing about the React dev server is the abundant debugging info. This I am now missing. Main question: Is it possible to still have the debug info available in a setup similar to what I have currently? And if so, can anyone advice me on how to set that up? -
Generate Ipv4 address of a specific subnet with factory_boy and faker for django model
Gretings everyone! Below is a script to populate a model using faker. Faker allows using 'address_class' argument. Specifiying address_class='a' narrows in down but only to 10.0.0.0/8. How to adjust the generator further, for example to 10.10.10.0/24? import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") django.setup() from workplace.models import IpAddress import factory import faker from faker.providers import internet faker = faker.Factory.create() class IpAddressFactory(factory.django.DjangoModelFactory): class Meta: model = IpAddress django_get_or_create = ('ip_address',) ip_address = faker.ipv4_private(address_class='a') ip = IpAddressFactory() print(ip) -
Django pure controller functions
I am wondering on how to implement pure controller functions in a Django's' "biased" MVC scheme. Let me explain it on an example. Let's say I have a model of an Invoice, which has some attributes (say net, gross etc.). I can present it to the user using a view + template. And that's fine and easy. But now, I want to send this invoice to a client. This is a more complicated thing, inluding more models (i.e. create an addressed Package model, get a number and let's say few other thing including creating and modifying not only Invoice model itself, but also creating and updating few other model types and instances. I want this "action" to be available in multiple places of my web application, so going by the book I need to create a view with those actions implemented and bind it to some URL. Probably it should be implemented in POST action. My questions are: What kind of generic view should it be (just View? DetailView? other?). Where should this View redirect after succesfull "send"? The simplest answer would be to redirect to the same referring page, but is this a correct way? What if I want … -
Django format email django errors
hi i would like create a format for django email errors, the email is automatic send by django in this case get the typical error format: i would like get in the email report the project name, all type errors(404/500/etc)... This is my settings: ADMINS = ( ('Diego Avila', 'diego.loachamin@test.com'), ) #CONFIGURAR PARAMETROS EMAIL EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_SSL = True EMAIL_HOST = 'mail.test.com' EMAIL_HOST_USER = 'diego.loachamin@test.com' EMAIL_HOST_PASSWORD = 'dsdsad' EMAIL_PORT = 465 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } please someone suggest or idea.. thanks..!! -
Django views rendering just one page and wont render the rest
So im using django 1.8 on macosx and i have problem while configuring html, namely when i try to load another page except one that is set at default one(index is the default one), it just refreshes the default one i have set in urls.py and i cant access any other page except that one but in the url bar i can see that im accesing the proper html file because it says so but the page is not changing....heres my code: app/urls.py----------- urlpatterns = [ url(r'^contact/', views.contact, name='contact'), url(r'^projects/', views.projects, name='projects'), url(r'^services/', views.services, name='services'), url(r'^', views.index, name='index'), url(r'^about/', views.about, name='about'), these are all the pages im trying to install main urls.py------------- from app import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^',include('app.urls')), ] and this is my views.py----------- def contact(request): return render(request, 'app/template/contact.html',{}) def about(request): return render(request, 'app/template/about.html',{}) def projects(request): return render(request, 'app/template/projects.html',{}) def services(request): return render(request, 'app/template/services.html',{}) def index(request): return render(request, "app/template/index.html",{}) -
Import Error: No module named 'mysite' when trying to import django model
I have been trying to import a django model to my python script to extract its fields as below` #!/usr/bin/env python3 import sys sys.path.append("/home/tutorial/device_interfaces/mysite") import json import re import os.path import pathlib import uuid import subprocess from models.py import ConfigInfo def info(): creds=ConfigInfo.objects.first() SSID_name='SSID' psk_name='psk' sIP='sIP' netmask='netmask' ` but, when i python3 manage.py runserver 127.0.0.1:8000 i get File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ImportError: No module named 'mysite' I tried .models import ConfigInfo, but it brought the same traceback. I wonder if the file. I also tried import ConfigInfo but it also did not work. The two python files that are invloved are in the same folder. How do i import my models correctly to get access to its data?