Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have deleted the registration from site-packages but still it is not showing me import error
urls.py in my main app my project structure, it can be seen that there is no module named registration Still when i run the server it doesn't give me any error any runs as it was before deleting. Please help me to resolve this issue. -
What is the purpose of defualt=False in django management command
I'm trying to write a management command in django. According to the documentation default is set to False. I would assume that the default is the default value of the argument that is being passed. Make django custom management command argument "Not Required" What's the benefit of stating that deafult=False class Command(BaseCommand): help = "helps in doing stuff" def add_arguments(self, parser): parser.add_argument( 'name', type=str, default=False help="The name of the folder to be created") def handle(self, *args, **options): pass -
Celery task.delay blocked in docker container
I use celery in my django project. It works well on my MacBook and in a CentOS VM. When I run it in a docker container, the request which contains add.delay(add is a task) method is always blocked. I created a demo project on github: https://github.com/fengyouchao/proj_test My task: @shared_task def add(x, y): return x + y My view: def index(request): a = int(request.GET.get('a', 1)) b = int(request.GET.get('b', 2)) add.delay(a, b) return HttpResponse("Hello world") def hello(request): return HttpResponse("hello") In the demo project I created three services in docker-compose.yml: web - The service which run "manage.py runserver 0.0.0.0:8000" celery - The service which run "celery" rabbitmq - The service wich run rabbitmq-server Run services docker-compose up Test curl localhost:8000 # blocked curl localhost:8000/hello # OK Run the django project in current system(use the same rabbitmq-server in docker container) manage.py runserver 0.0.0.0:18000 Test curl localhost:18000 # OK , and the "celery" service printed task logs This problem has been bothering me for a long time, and I don't know where the problem is. I hope someone can help me. Thanks! -
Apps aren't loaded yet exception occurs when using multi-processing in Django
I'm doing a Django project and try to improve computing speed in backend. The task is something like a CPU-bound conversion process Here's my environment Python 3.6.1 Django 1.10 PostgreSQL 9.6 And I stuck with following errors when I try to parallel a computing API by python multi-processing library. File "D:\\project\apps\converter\models\convert_manager.py", line 1, in <module> from apps.conversion.models import Conversion File "D:\\project\apps\conversion\models.py", line 5, in <module> class Conversion(models.Model): File "C:\\virtenv\lib\site-packages\django\db\models\base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "C:\\virtenv\ib\site-packages\django\apps\registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "C:\\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") look like each process import Conversion model and Conversion model is like from django.db import models Conversion(model.Model): conversion_name = models.CharField(max_length=63) conversion_user = models.CharField(max_length=31) conversion_description = models.TextField(blank=True) ... Below is my sample function which I want to parallel, each iteration is independent but will access or insert data into SQL. Class ConversionJob(): ... def run(self, p_list): list_merge_result = [] for p in p_list: list_result = self.Couputing_api(p) list_merge_result.extend(list_result) and I'm try to do is from multiprocessing import Pool Class ConversionJob(): ... def run(self, p_list): list_merge_result = [] p = Pool(process=4) list_result = p.map(self.couputing_api, p_list) list_merge_result.extend(list_result) In computing_api(), it'll try to get current conversion's info which has completed and … -
Pass xml file from directory to javascript using django
I'm creating an .xml file and then trying to pass this file to javascript, so I could use it there. Here's the output in browser's console: Failed to load file:///D:/Geoinformation%20systems/Maps/Markers/static/Markers/data.xml: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. Here is my view function: def index(request): markers_set = Marker.objects.all() root = Element('markers') tree = ElementTree(root) for m in markers_set: name = Element('marker') name.set('id', str(m.id)) name.set('name', m.name) name.set('address', m.address) name.set('lat', str(m.lat)) name.set('lng', str(m.lng)) name.set('type', m.type) root.append(name) tree.write(open(r'Markers\static\Markers\data.xml', 'wb')) return render_to_response('index.html', {'xmldata' : r'D:\Geoinformation systems\Maps\Markers\static\Markers\data.xml'}) Here is a piece of template "index.html" where javascript code is located: <html> <body> <div id="map"></div> <script> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: new google.maps.LatLng(-33.863276, 151.207977), zoom: 12 }); var infoWindow = new google.maps.InfoWindow; <!--Here I'm taking data that is passed--> downloadUrl('{{ xmldata }}', function(data) { var xml = data.responseXML; var markers = xml.documentElement.getElementsByTagName('marker'); ... function downloadUrl(url, callback) { var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest; request.onreadystatechange = function() { if (request.readyState == 4) { request.onreadystatechange = doNothing; callback(request, request.status); } }; request.open('GET', url, true); request.send(null); } }); } </script> </html> How should I pass/get the file, so not to failing loading it? I know … -
TypeError: save() missing 1 required positional argument: 'self'
this is views class RegisterView(View): def get(self,request): register_form = RegisterForm() return render(request,'register.html',{'register_form':register_form}) def post(self,request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get("email", '') pass_word = request.POST.get("password", '') user_profile = UserProfile user_profile.username = user_name user_profile.email = user_name user_profile.password = make_password(pass_word) user_profile.save() #error send_register_email(user_name,"register") I want to save user_profile to mysql,But user_profile.save() has an error, TypeError: save() missing 1 required positional argument: 'self',How should I solve it? -
Django admin cannot load data from database
After I create feature translate use Django model translation and then I was deployed Django project to the server and get I problem, My code was running well, in local development, Django admin can load data from the database without any problem. But the problem is when code deployed to server data in Django admin cannot load, they load blank data without error or any problem. But in database data is still available. models.py: from django.db import models from base.models import BaseModel class Platform(BaseModel): name = models.CharField(max_length=255) icon = models.ImageField(upload_to='gopay_platformicon') order = models.PositiveIntegerField(default=1) class Meta: ordering = ['order'] def __str__(self): return self.name class Method(BaseModel): name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) platform = models.ForeignKey(Platform) note = models.TextField(blank=True, null=True) picture = models.ImageField(upload_to='gopay_method', blank=True, null=True) order = models.PositiveIntegerField(default=1) class Meta: ordering = ['order'] def __str__(self): return self.name class TopupStep(BaseModel): name = models.TextField() method = models.ForeignKey(Method) picture = models.ImageField(upload_to='gopay_topupstep', blank=True, null=True) order = models.PositiveIntegerField(default=1) class Meta: ordering = ['order'] def __str__(self): return self.name translation.py: from modeltranslation.translator import translator, TranslationOptions from . import models class MethodTranslationOptions(TranslationOptions): fields = ('name', 'description', 'note', ) class TopupStepTranslationOptions(TranslationOptions): fields = ('name', ) translator.register(models.Method, MethodTranslationOptions) translator.register(models.TopupStep, TopupStepTranslationOptions) admin.py : from django.contrib import admin from base.admin import BaseAdmin from gopay … -
Django Roles and permissions
I am working on django roles and permissions, for this i am using django-role-permissions library. Issue : Create one role 'Director', director role assign user able to login into django admin area and view ( only view permissions ) filter data ( just like that : student which have 90% and above ) . Note : I already have two roles 1. Teacher 2. Student. -
Using django app config to change model.Meta.managed
Given the following architecture of django projects apps and database schemas: There is a django app which I want to share between several django projects. Each project has it's own postgresql schema in behind. All schemas live in the same postgresql database. One project is owner of the apps data, this project is responsible to run migrations and the data should live in its schema. All other projects may access the data from the other projects schema, because they have a proper postgresql search path set. We already use this concept with an app that has all models set to unmanaged, which works. But database changes always needs to be done manually. I'd like to benefit from django migrations and therefore I want my models either managed or unmanaged. Do you think app config is good place to change the models meta? Any other suggestions and approaches on how to solve the requirement are also welcome. -
Not able to make a ajax request in django using postgresql
So i've developed a django app,and i'm trying to POST something to Postgresql,i understand that CSRF token is necessary during an ajax request made to a view,which i have done,this is my csrf.js,which i've included in my header template // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); and this is my ajax request being made in a template $.ajax({type: 'POST', url: '/sample/saveData/', // some data url data: {param: workHours.length, param1: $(getDayName[i]).text(),param2: bla,param3: bla1,param4: bla2}, // some params success: function (response) { // callback if (response.result === 'OK') { if (response.data && typeof(response.data) === 'object') { // do something with the successful response.data // e.g. response.data can … -
Uncaught TypeError: Cannot read property 'weight' of undefined [D3.js jquery-3.2.1.slim.min.js]
I am using Django framework and D3.Js to render some svg graphs. Everything works fine when i test in my local system. But while I deploy to the production server, the "Uncaught TypeError", pops in and fails to render. Following are the things I have tried, 1. commented the google analytics to get more detail bug report [no luck] 2. disabled the force in JS, the figures renders but the graph messed up. [do not want to do this] 3. Tried changing the name of property, but the error still persists for property like "name". Is there any permission issue I should check? Any help to get the bug will be very helpful. -
Django - filtering queryset with optional FormFields
Let's say I have a model: class House(models.Model): (...) price = models.DecimalField(decimal_places=2, max_digits=8) area = models.DecimalField(decimal_places=2, max_digits=6) And I have a Form for searching of Houses: class SearchHouseForm(forms.Form): price_min = forms.DecimalField(required=False, initial=0, decimal_places=2, max_digits=8) price_max = forms.DecimalField(required=False, initial=999999, decimal_places=2, max_digits=6) And the view function: def search_for_houses(request): queryset = House.objects.all() if request.method == 'GET' and 'search-submit-button' in request.GET: form = SearchHouseForm(request.GET) if form.is_valid(): queryset = queryset.filter( price__lte = form.cleaned_data['price_max'], price__gte = form.cleaned_data['price_min'] ) else: (...) return render(request, template, {'house_list': queryset, 'form': form}) I have a problem with the .filter()-ing. I want to apply the filter if and only if the user provides any value in the form field. If the price_max field is left blank, only the price__gte = form.cleaned_data['price_min'] should be applied. If both price_max and price_min are left blank, all House objects should be returned. Currently I get ValueError Cannot use None as a query value Is there a clean way to do that? The only thing I can think of is a long list of if statements for all such optional fields: if form.cleaned_data['price_max'] is not None: queryset = queryset.filter((...)) if form.cleaned_data['price_min'] is not None: queryset = queryset.filter((...)) (...) This does not seem as a good idea, especially … -
Paginator Number of Pages does not update in HTML after filtering results - Django
Paginator Number of Pages does not update in HTML after filtering with django_filter. html file <span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.</span> The page_obj.paginator.num_pages is the initial number (without any filters) of all results in the table (example: I got 12 results and showing 3 results/page => 4 pages) views class SearchBookView(ListView): template_name = "booksearch.html" paginate_by = 3 model = Book def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) book_qs = Book.objects.all() book_filter = BookFilter(self.request.GET, queryset=book_qs) paginator = Paginator(book_filter.qs, self.paginate_by) print(paginator.num_pages) ### Prints the correct num pages everytime even after filtering page = self.request.GET.get('page') try: book_list = paginator.page(page) except PageNotAnInteger: book_list = paginator.page(1) except EmptyPage: book_list = paginator.page(paginator.num_pages) context['book_list'] = book_list context['book_filter'] = book_filter return context After adding a filter (let's say after filtering it shows 5 results) page_obj.paginator.num_pages should be 2 in my HTML, right? Although in my view in print(paginator.num_pages) it shows 2, in the HTML it stays the original 4 pages. How can I pass this to the HTML file? WORKAROUND I did a workaround but it is kind of ugly: in my view I added a context['num_pages'] = paginator.num_pages and pass it my HTML: <span>Page {{ page_obj.number }} of {{ num_pages }}.</span> Any suggestions on how to … -
How to encrypt the Django website?
Our company has developed a website system using Django, and we can sell to other merchants (set up the website on the merchant's servers), the merchants can show the website to their users. But our company does not want to let merchants see the website source code, is there some way to encrypt the Django website? Or some other way that the merchants cannot access the website source code? -
MultipleObjectsReturned: get() returned more than one Feed -- it returned 2
I'm writing some simple test for an django-model and I'm just using assertEqual and assertNotEqual for it. Now I'm not fully grasping how to test BooleanField in this case. I have a model field like this: duplicate = models.BooleanField(default=False) and I'm writing this test for it, just to check is it equal ` def test_feed_duplicate_create(self): stefan_feed_duplicate = Feed.objects.get(duplicate='False') milan_feed_duplicate = Feed.objects.get(duplicate='False') self.assertEqual( stefan_feed_duplicate.duplicate, 'False') self.assertEqual( milan_feed_duplicate.duplicate, 'False')` But the error that I'm facing is: (venv) vagrant@jessie:/var/www/vhosts/bspotted.net/app$ ./manage.py test --keepdb socialmedia nosetests socialmedia --verbosity=1 Using existing test database for alias 'default'... ............E.................... ====================================================================== ERROR: test_feed_duplicate_create (app.socialmedia.tests.test_feed_model.CommentsTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/var/www/vhosts/bspotted.net/app/socialmedia/tests/test_feed_model.py", line 225, in test_feed_duplicate_create stefan_feed_duplicate = Feed.objects.get(duplicate='False') File "/var/www/vhosts/bspotted.net/venv/lib/python3.4/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/var/www/vhosts/bspotted.net/venv/lib/python3.4/site-packages/django/db/models/query.py", line 338, in get (self.model._meta.object_name, num) socialmedia.models.feed.MultipleObjectsReturned: get() returned more than one Feed -- it returned 2! ---------------------------------------------------------------------- Ran 33 tests in 0.159s Can someone explain me what is the proper way of testing BooleanField in this case. Thanks. -
Django - Is this possible that the add default values when model is creating?
I want to add some default values in my database when the related model is creating with makemigrations command. For example I have this as model; class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created Date') modified_at = models.DateTimeField(auto_now=True, verbose_name='Update Date') is_deleted = models.BooleanField(default=False, verbose_name='Deleted') class Meta: abstract = True class ModelType(BaseModel): description = models.CharField(verbose_name='Name', max_length=225 ) and as I said before I want to add some default values ("value1", "value2", "value3", "value4") for my ModelType table. Is that possible? -
How to get data from a Formdata object in my views?
My AJAX call sends a FormData object with an uploaded image data inside it: $(document).on('submit', '#profileImageForm', function(e){ e.preventDefault(); var form_data = new FormData(); var image = document.getElementById('id_banner_image').files[0].name; form_data.append('file', image); $.ajax({ type:'POST', url: '/change_banner_image/', data : { form_data: form_data, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), }, traditional: true, cache: false, success: function(response){ console.log('Success'); }, }); }); and I succesfully receive the call in my views: def change_banner_image(request): if request.is_ajax(): data = request.POST.get('form_data') profile = get_object_or_404(Profile, user=request.user) profile.image = data profile.save() print(data) return HttpResponse() print(data) prints: [object FormData]. So how would I get the uploaded image from this FormData object? Which will then be the value of profile.image (which is a FileField). -
Django: return old data
I deleted the database - to update the new version of the data psql -U postgres - drop my_db created new with same name 'my_db' added new data: psql -U postgres -d my_db < my_db.sql after it in admin page i see new data - my_site/admin but on client side - i see data which i saw before drop database I clean cache, all data for this site what could it be? did anyone come across this? -
Django how to merge query results
I have an ArrayField with choices and i'm trying to filter the choices: PAYMENT_CASH = '0' PAYMENT_CARD = '1' PAYMENT_BANK = '2' PAYMENT_ONLINE = '3' PAYMENT = ( (PAYMENT_CASH, _('Cash')), (PAYMENT_CARD, _('Card')), (PAYMENT_BANK, _('Bank')), (PAYMENT_ONLINE, _('Online')), ) options = ArrayField(models.CharField(max_length=1, choices=PAYMENT, default='0'), size=4) When i use Location.objects.filter(city__id='683506').values_list('options', flat=True) it returns me <QuerySet [['0'], ['0', '1', '2', '3'], ['0', '1', '2'], ['0', '1'], ['0', '1', '2', '3']]> I wish to get all the options that are used. How can i merge the query or make them into a list and merge them? This is what i wish to get ['0', '1', '2', '3'] -
StreamBlock instance throws exception "AttributeError: 'str' object has no attribute 'block'"
I am using the example project provided by Wagtail. The StreamField gets as argument A DemoStreamBlock class DemoStreamBlock(StreamBlock): h2 = CharBlock(icon="title", classname="title") h3 = CharBlock(icon="title", classname="title") h4 = CharBlock(icon="title", classname="title") intro = RichTextBlock(icon="pilcrow") paragraph = RichTextBlock(icon="pilcrow") aligned_image = ImageBlock(label="Aligned image", icon="image") pullquote = PullQuoteBlock() aligned_html = AlignedHTMLBlock(icon="code", label='Raw HTML') document = DocumentChooserBlock(icon="doc-full-inverse") Then in the Page class I'm instantiating a variable e.g. class BlogPost(Page): blog_text = StreamField(DemoStreamBlock()) content_panels = Page.content_panels + [ StreamFieldPanel('blog_text') ] The first time I run the migrations Django doesn't want me to put a default value because of the non-nullable field that I am adding. However, if I want to add another StreamField field I am prompted to add a default value: class BlogPost(Page): blog_text = StreamField(DemoStreamBlock()) blog_short_text = StreamField(DemoStreamBlock()) content_panels = Page.content_panels + [ StreamFieldPanel('blog_text'), StreamFieldPanel('blog_short_text'), ] You are trying to add a non-nullable field 'blog_short_text' to blogpost without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a > null value for this column) 2) Quit, and let me add a default in models.py I am choosing 1 and then enter … -
Ubuntu service Upstart or SystemD, Django development server as Service
I've been working around with Python & Django Framework for a while with Ubuntu 16.01. Since I used Django with Q system (Celery) and some others Enhancement Apps. When I try to run all the apps each time, I need to run development server "{python manage.py runserver}", then running Celery Worker "{celery -A filename worker -l info}". Each time I working, it takes me minutes to enter the directory and start it up. I surf around and come up with the idea of setup it as service. Example, service name: "pyd". I just need to run "{sudo pyd start}" -> then Django Development Server and Celery will start, and if I run "{sudo pyd stop}" -> then Django & Celery will stop. I try to search around, and things start to confuse me between "Upstart" and "Systemd". Could any one suggest, me how to make both Django and Celery as Service run in Ubuntu ? between "Upstart" & "Systemd" which one is better ?? Source code to indicate sample is appreciated. Thank -
Nested serializer with custom queryset
I am trying to display the custom query values to the nested serializer . But its not displaying serializer.py class TueRangeSerializer(serializers.ModelSerializer): class Meta: model = SubnetRange fields = ('type', 'id', 'begin', 'end') class TueSubnetSerializer(serializers.ModelSerializer): range = TueRangeSerializer(required=False,read_only=False,many=True) class Meta: model = Subnet fields = ('name','base_address','bits','range') def create(self,validated_data): print(validated_data) And in the api file api.py class SubnetList(APIView): def get(self, request, format=None): query = 'SELECT ss.id ,ssr.id, ssp.id , ' \ ' ss.name as name, ss.bits as bits, ssr.begin as begin FROM subnets_subnet ss' \ ' inner join subnets_subnetphysical ssp on ssp.subnet_id = ss.id' \ ' inner join subnets_subnetrange ssr on ssr.subnet_physical_id = ssp.id' subnets = Subnet.objects.raw(query) serializer = TueSubnetSerializer(subnets,many=True) return Response(serializer.data) SQL query is correct. But on the response of the serializer its displaying only the data from subnets table Result [ { "name": "First subnet", "base_address": "192.100.30.0", "bits": 24 }, { "name": "Second subnet", "base_address": "192.100.30.0", "bits": 24 } ] Its not displaying the range output -
unable to access django website from URL but accessible from IP address
I have installed django on Amazon lightsail, I can access my website through the static server IP address. My domain is hosted on Godaddy. I change the Name Server in GoDaddy. But still when I try to access my website through domain name it shows me Nignx welcome page. Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. In my django settings.py I have given only the IP address ALLOWED_HOSTS = ['YOUR_AMAZON_LIGHTSAIL_IP'] And in Nginx file, I also added only the IP address. server { listen 80; server_name YOUR_AMAZON_LIGHTSAIL_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/django_project; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/django_project/django_project.sock; } } I am using Gunicorn and Nginx on my hosting server. -
Django deadline alert
I am building a management application for a company. One of the things the application can do is start new projects. The model here for is: ` class Project(models.Model): employees = models.ManyToManyField(settings.AUTH_USER_MODEL) division = models.ForeignKey(Division) client = models.ForeignKey(Company) description = models.CharField(max_length=120) timestamp = models.DateTimeField(auto_now_add=True) deadline = models.DateField(blank=True) active = models.BooleanField(default=True) ` As you can see in the model a employee can set a deadline for their project. I need to able to send the user notifications if they are close to their deadline. For example, if the deadline is in two days, the user will get a notification like "Your deadline for projectname is over two days". So basically what I need is a deadline timer. What is the logic for this? I don't really know where to start with this? -
NameError: name 'base' is not defined(haystack search)
I wanted to include full text search in my django application. I am using whoosh-haystack for this.When I include whoosh and haystack in my installed apps,and execute the command ./manage.py, I am getting an import error. Can anyone sort this out. settings.py INSTALLED_APPS = { 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'search', 'whoosh', 'haystack', } when I make migration in my model the error which I got is: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python \Python36\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 303, in execute settings.INSTALLED_APPS File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 48, in __getattr__ self._setup(name) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Users\Samad Talukder\Desktop\django-env\search\search\settings.py", line 80, in <module> 'PATH': os.path.join(base(), 'whoosh_index') NameError: name 'base' is not defined my haystack connection: HAYSTACK_CONNECTIONS = { …