Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django .update() with .get()
I have an invoice table # app/models.py class tbl_invoice(models.Model): invoice_id = models.IntegerField(blank=True, null=True) invoice_number = models.IntegerField(blank=True, null=True) quotation_id = models.IntegerField(blank=True, null=True) quotation_number = models.IntegerField(blank=True, null=True) invoiced = models.CharField(max_length=50, default='', blank=True, null=True) this table contains invoice and quotations records, system user has the option to convert any quotation to invoice, but the quotation record will still remain along with the newly generated invoice record and this is my views #views.py obj = tbl_invoice.objects.get(pk='someId') # getting existing record with pk obj.pk = None obj.invoice_id = 'someId' obj.quotation_id = None obj.invoice_number = 'someValue' obj.quotation_number = None obj.invoiced = 'no' obj.type_status = 'invoice' obj.save() above code is working fine, it creates a new invoice record and also maintains the old quotation record however, after converting quotation to invoice I also want to update the invoiced value on the quotation record to yes for that, I tried obj.update(invoiced = 'yes') but .update() doesn't work on .get() how can I create a new record from an existing record and update the old record at the same time or do I have to use multiple queries Thanks for any help. -
Using Q expression in Case When is not returning expected results in Django. Seems like an inner join is used, not left join
I am trying to build a complex filter with the Django ORM and am running into an issue where objects without a foreign key are not being included. This is due to an inner join that is being generated and I believe it should be a left outer join. I have two models Report and Message. Report has a reference to a particular Message but that could also be null. class Report(BaseModel): message = models.ForeignKey( Message, on_delete=models.SET_NULL, related_name="message_reports", null=True, ) created_at = models.DateTimeField() # other fields class Message(BaseModel): should_send_messages = models.BooleanField( default=True ) num_hold_hours = models.IntegerField( default=None, null=True, ) # other fields Here is the filter that I am trying to use. Report.objects.filter( Q(message__isnull=True) | Q(message__should_send_messages=True), created_at__lte= Case( When( Q(message__isnull=True) | Q(message__num_hold_hours__isnull=True), then=ExpressionWrapper( timezone.now() - timedelta(hours=1) * Cast( settings.NUM_HOURS_TO_NOTIFY , output_field=IntegerField()) , output_field=DateTimeField())), default=ExpressionWrapper( timezone.now() - timedelta(hours=1) * Cast( F('message__num_hold_hours') , output_field=IntegerField()) , output_field=DateTimeField()), output_field=DateTimeField()), ) Here is the sql that is generated as a result of that filter block. (I'm not sure why the datetimes look like that ugly) SELECT "report"."message_id" FROM "report" INNER JOIN "message" ON ( "report"."message_id" = "message"."id" ) WHERE ( ( "report"."message_id" IS NULL OR "message"."should_send_messages" = True ) AND "report"."created_at" <= ( CASE WHEN … -
Django StaticLiveServerTestCase cannot TRUNCATE and FLUSH
I try to implement TDD using: django version 3.0 Selenium version 3.141.0 with chromedriver.exe PgAdmin4 (Postgresql 13.0) Here is my test code from selenium import webdriver from selenium.webdriver.common.keys import Keys from django.contrib.staticfiles.testing import StaticLiveServerTestCase class NewUserTest(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Chrome("D:\chromedriver.exe") def tearDown(self): self.browser.quit() def test_success_login(self): self.browser.get(self.live_server_url) input_username = self.browser.find_element_by_id('id_username') input_password = self.browser.find_element_by_id('id_password') self.assertTrue(input_password.get_attribute('required')) input_username.send_keys('onesinus') input_password.send_keys('123') input_password.send_keys(Keys.ENTER) But when the test executed python manage.py test I have two error: 1. django.db.utils.NotSupportedError: cannot truncate a table referenced in a foreign key constraint DETAIL: Table "my_table_name" references "auth_user". HINT: Truncate table "my_table_name" at the same time, or use TRUNCATE ... CASCADE. 2. Traceback (most recent call last): File "D:\bidboxcms\venv\lib\site-packages\django\test\testcases.py", line 274, in __call__ self._post_teardown() File "D:\bidboxcms\venv\lib\site-packages\django\test\testcases.py", line 1009, in _post_teardown self._fixture_teardown() File "D:\bidboxcms\venv\lib\site-packages\django\test\testcases.py", line 1041, in _fixture_teardown call_command('flush', verbosity=0, interactive=False, File "D:\bidboxcms\venv\lib\site-packages\django\core\management\__init__.py", line 168, in call_command return command.execute(*args, **defaults) File "D:\bidboxcms\venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "D:\bidboxcms\venv\lib\site-packages\django\core\management\commands\flush.py", line 65, in handle raise CommandError( django.core.management.base.CommandError: Database test_bidbox-staging couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this … -
Django model datetime is different in template than the database
The date data added is normally added to the database. There is a 3 hour difference in appearance. This is my saved data on admin panel: The view of that data on a template: Settings: LANGUAGE_CODE = 'tr' TIME_ZONE = 'Europe/Istanbul' USE_I18N = True USE_L10N = True USE_TZ = True -
style django-form to save in pdf with wkhtmltopdf
I am developing app in python with django. I have some kind of surveys in my app. I use django-crispy for nice display on the site. I also have an option to download surveys to pdf. I use for that wkhtmltopdf (PDFTemplateResponse). And then, in a pdf, surveys appear a little like screenshots, it is hard to style them, the forms sometimes do not fit on the page. I wish it looked more like here: https://surveytemplates.org/wp-content/uploads/2019/11/pdf-customer-service-survey-form-template-2019-doc-pdf-formatted-free.jpg Are there any other forms besides django-crispy (I tried to find, but failed)? Or can cripsy forms be well divided into pdf pages in wkhtmltopdf? Best regards! -
no filter named 'localtime' [duplicate]
I am using localtime template filter to convert UTC to localtime but I am getting this error.` <td> {{ test.created_at|localtime }} </td>` but I am getting Template Assertion error. created_at is stored in utc in database. In setting.py USE_I18N = True USE_L10N = True USE_TZ = True -
Error while using "python manage.py runserver"
I am getting the following error. I had previously merged a branch but without success. I then used git reset to go back to a previous commit. After that, I tried to run my project but got the following error. Any help is appreciated. (oldenv) C:\New folder\Downloads\TECHTUREPS2\bimscoper-rest-api>python manage.py runserver Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\New folder\Downloads\TECHTUREPS2\oldenv\lib\site-packages\django\core\management_init_.py", line 364, in execute_from_command_line utility.execute() File "C:\New folder\Downloads\TECHTUREPS2\oldenv\lib\site-packages\django\core\management_init_.py", line 308, in execute settings.INSTALLED_APPS File "C:\New folder\Downloads\TECHTUREPS2\oldenv\lib\site-packages\django\conf_init_.py", line 56, in getattr self._setup(name) File "C:\New folder\Downloads\TECHTUREPS2\oldenv\lib\site-packages\django\conf_init_.py", line 41, in _setup self._wrapped = Settings(settings_module) File "C:\New folder\Downloads\TECHTUREPS2\oldenv\lib\site-packages\django\conf_init_.py", line 110, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\New folder\Softwares\Python 2.7\lib\importlib_init_.py", line 37, in import_module import(name) File "C:\New folder\Downloads\TECHTUREPS2\bimscoper-rest-api\bimscoper\settings\dev\dev.py", line 9 <<<<<<< HEAD ^ SyntaxError: invalid syntax -
Django pagination: redirect to specific page after edit (FBV)
I'm listing 300 of customers records using a pagination in Django. Each page contains 20 records. Suppose i'm on page 7 and selected a record to edit . After editing the record, successful url to redirect list view(which is first page). So I want , if I edit in ?page=7, when the edit in done by customer id it will come back to ?page=7. Here is my customer_list view in view.py: def customer_list(request): posts_list = Customer.objects.all() query = request.GET.get('q') if query: posts_list = Customer.objects.filter( Q(invoice__addresses__contact_number__icontains=query) | Q(invoice__addresses__address__icontains=query) | Q(shipping_method__icontains=query) ).distinct() page = request.GET.get('page') paginator = Paginator(posts_list, 20) # 20 posts per page try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context = { 'posts': posts, 'page': page } return render(request, "customers/customer_list.html", context) Here is update_customer_list view in view.py: def update_customer_list(request, id): """ Here, update single customer id form customer table :param request: :param id: :return: """ obj = get_object_or_404(Customer, pk=id) form = CustomerForm(request.POST or None, instance=obj) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Customer successfully Updated') return redirect('customer_list') return render(request, 'customers/customerUpdateForm.html', {'form': form}) Here is update_customer_list url in urls.py: path('update_customer_list/<int:id>/', views.update_customer_list, name='update_customer_list'), I am waiting for someones help and help will be highly appreciated... -
How to Convert SQL query to Django ORM?
this is the SQL query which I want to change to Django ORM please help? select 0 'bucket_id', 'Incomplete' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf is null union select 1 'bucket_id', 'Very Poor' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 0 and 1.999 union select 2 'bucket_id', 'Poor' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 2 and 2.999 union select 3 'bucket_id', 'OK' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 3 and 3.999 union select 4 'bucket_id', 'Good' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 4 and 4.599 union select 5 'bucket_id', 'Great' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 4.599 and 5 -
Ckeditor in local is not working due to the aws settings for static and media file in settings.py
I have installed the CKEditor package for my CRM backend, it was working perfectly fine. Now, I have put AWS settings in my settings.py file which contains STATIC & MEDIA root and URL settings. Due to this, my CKEditor has stopped working and I cant fill in the text data now. But, if I comment out again, CKEditor starts working again in local otherwise not. My AWS settings: DEFAULT_FILE_STORAGE = 'travel_crm.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'travel_crm.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'bonbonstage' S3DIRECT_REGION = 'ap-southeast-1' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' two_months = datetime.timedelta(days=61) date_two_months_later = datetime.date.today() + two_months expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") AWS_HEADERS = { 'Expires': expires, 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ), } My ckeditor settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "uploads/" #ckeditor configs #todo CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'width': 1000, 'height': 400 }, } My URLS settings: urlpatterns = [ path('admin/', admin.site.urls), path('', admin.site.urls), path('', include('apps.accounts.urls')), path('', include('apps.blogs.urls')), path('', include('apps.enquiry.urls')), path('', include('apps.packages.urls')), path('', include('apps.booking.urls')), path('ckeditor', include('ckeditor_uploader.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG is True: … -
How can I make API in django?
I have to create api in django using models.py that take data from models.py and make its api. Here is code that I have tried from rest_framework import serializers from .models import * class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ('line1','line2','city','state','country','postal code') But I am finding problem to do this. How can I do this? -
Django-Vue error "Failed to mount app: mount target selector returned null."
Thanks for looking into my problem, I am a beginner with Django and Vue your assistance with this wil be extremely helpful. I am working on a Job portal and created the job search functionality in Django as backend for the same I have an app called job into my Django project. For this app job, I am implementing a job search api with Vue but somehow the error that get's shown in browser's JS console is as follows Failed to mount app: mount target selector returned null. and the search results seem to be broken and not as expected, Here is the snap of my screen as you can see the results are not as expected, it was supposed to give me the company name, job title and a link to job description, also the exact same problem occurred with another html template, what is wrong here? Search.html template file {% extends 'core/base.html' %} {% block content %} <div class="search-app"> <h1 class="title"> Search</h1> <form v-on:submit.prevent="performsearch()"> <div class="columns"> <div class="column is-4"> <div class="field"> <label>Query</label> <div class="control"> <input type="text" name="query" class="input" v-model="query"> </div> </div> <div class="field"> <label>Company Size</label> <div class="control"> <div class="select"> <select name="company_size" v-model="company_size" id=""> <option value="" selected>All</option> <option value="size_1_9" … -
django-angular for Angular?
Just want to know that if there's something like this for Angular too? This is actually a wrapper around angularJS $http service which let's us call view methods from Javascript. Wondering if there's same for latest versions Angular. This is very convenient for AngularJS as I can call view methods from my controller. django-angular -
TemplateDoesNotExist: home.html, femat/law_list.html
Why I am getting the above error while I have not defined or requested "law_list.html"? Where does the law_list.html come from? It should be something wrong with model and class based view. I am using Django 3.1.3. #models.py from django.db import models class Law(models.Model): name = models.CharField(max_length=100) E = models.FloatField(null=False, blank=False, default=0) def __str__(self): return '{} {}'.format(self.name, self.E) #views.py from django.views.generic import ListView from .models import Law class HomeView(ListView): model = Law template_name = 'home.html' #urls.py from django.urls import path from .views import HomeView urlpatterns = [ path('', HomeView.as_view(), name='home'), ] -
Adding an annotation to django queryset to be used by django_tables2
I have a model that has (among other fields) one value for the current price of an item and one value for the usual price of an item. I'd like to include a field for the percentage saving. I've done this using the @property: @property def percSaving(self): aval = self.stickerprice bval = self.currentprice if self.stickerprice > 0: return "%0.2f" % ((aval-bval)/aval*100) + "%" elif self.currentprice == 0: return "Always Free" else: return "100% OFF" This works, I can add this column to my django_table2 table with: percSaving = tables.Column(verbose_name='% Saving') Super easy and all good. However, I am unable to sort by this column. This is because it's not one of the columns of data from the query set. So I've been trying to annotate the query set to allow for this ordering I've based by annotation attempt on this queryset api reference page and have produced this: annoed = products.objects.annotate(percSaving=((stickerprice)-(currentprice))/(stickerprice)) However this gives me an error of "name 'stickerprice' is not defined" which I thought might be because of not using inverted commas around the field names, but I tried that and got an error saying "unsupported operand type(s) for -: 'str' and 'str'" - basically using the inverted … -
What to do after learning basics of flask
I currently finished some courses with flask and made an application with fladk sqlserver for my company, but I'm stuck here, i want to work as a freelancer to improve my income but i don't know what to do next, some people told me to make more projects, but i don't have any ideas to create, And should i stick with flask or learn making rest api with flask and make other framework handle the api requests (The app i made for my company is a simple ticketing system, where employers make a support ticket for requesting help and at admin panel we have all users data and all of their printers , used flask, sql alchemy, and for the templates html css js bootstrap jquery alongside jinja2 within some templates No real hobbies) , please give me your advice -
What should I use Django Non-Global Middlewares or Django triggers
My problem is basically that I am currently making a customized management system based on Django(3.1) Python(v3.7.9) in which I am pulling the data from a third-party tool. The tool is not giving me the webhooks of every data that I want for visualization and analysis. The webhook is giving me bits of information and I have to perform a GET request to their API to fetch the rest details if those are not in my database. They are asking for a successful response of webhook within 5 secs otherwise it will trigger a retry. If I try to do a get request within the function of webhook the time of 5 second will get exceeded the solutions that I came up with was to Django Middleware or Django Triggers so which would be best suitable for my problem I am bit confused. Note: I can not lower the Django version as I have to use Async Functions -
django how to add logo in admin site
cant override the django admin site page, i just want to put a logo in my admin page, did i miss something in my code? TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates/')], 'APP_DIRS': True, template {% extends "admin/base.html" %} {% load staticfiles %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"> <a href="{% url 'admin:index' %}"> <img src="{% static 'logo.png' %}" height="40px" /> </a> </h1> {% endblock %} {% block nav-global %}{% endblock %} -
Why can Django handle multiple requests?
According to Django is synchronous or asynchronous. Django is synchronous. However I tested a blocking view with python manage.py runserver 8100: import time @action(detail=False, methods=['get']) def test(self, request): time.sleep(5) return {} and triggered two requests with postman at 0s, 1s, and they returned at 5s, 6s. That seems not blocking/synchronous. Where am I wrong? -
Getting error on Heroku for "Django DisallowedHost at / Invalid HTTP_HOST header:" even after adding the url to ALLOWED_HOST
So I'm trying to deploy my django project to heroko, and I got this. I know what is the issue here, so I have added the url the-yogify.herokuapp.com to the ALLOWED_HOST in the settings.py file of my django project. ALLOWED_HOSTS = ['http://the-yogify.herokuapp.com/', 'https://the-yogify.herokuapp.com/', 'the-yogify.herokuapp.com', 'the-yogify.herokuapp.com/', '127.0.0.1'] But the error is still persistent. What am I doing wrong here? I thought the actual error might be something else. So I printed out the heroku logs, it also shows same error. 2020-11-24T04:10:53.978271+00:00 app[web.1]: [2020-11-24 04:10:53 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-11-24T04:10:53.979367+00:00 app[web.1]: [2020-11-24 04:10:53 +0000] [4] [INFO] Listening at: http://0.0.0.0:25352 (4) 2020-11-24T04:10:53.979552+00:00 app[web.1]: [2020-11-24 04:10:53 +0000] [4] [INFO] Using worker: sync 2020-11-24T04:10:53.991703+00:00 app[web.1]: [2020-11-24 04:10:53 +0000] [10] [INFO] Booting worker with pid: 10 2020-11-24T04:10:54.026534+00:00 app[web.1]: [2020-11-24 04:10:54 +0000] [11] [INFO] Booting worker with pid: 11 2020-11-24T04:10:54.200285+00:00 heroku[web.1]: State changed from starting to up 2020-11-24T04:10:57.847722+00:00 app[web.1]: Invalid HTTP_HOST header: 'the-yogify.herokuapp.com'. You may need to add 'the-yogify.herokuapp.com' to ALLOWED_HOSTS. 2020-11-24T04:10:58.083555+00:00 app[web.1]: Bad Request: / 2020-11-24T04:10:58.092696+00:00 app[web.1]: 10.11.198.97 - - [24/Nov/2020:04:10:58 +0000] "GET / HTTP/1.1" 400 59515 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36 Edg/86.0.622.51" 2020-11-24T04:10:58.099353+00:00 heroku[router]: at=info method=GET path="/" host=the-yogify.herokuapp.com request_id=dafb2e9e-fd1c-49d7-8375-fb0b707ef5bc fwd="42.111.13.118" dyno=web.1 connect=1ms service=2796ms status=400 bytes=59767 … -
Problem working in models rendering admin add page
i tried so many things like .formate and using id explicit in the model now i dont know what to do :( class Horas_medica(models.Model): id_boxes = models.ForeignKey(Boxe, on_delete=models.CASCADE) id_medico = models.ForeignKey(Medico, on_delete=models.CASCADE) id_paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE) descripcion = models.TextField() diagnostico = models.TextField() created_date = models.DateTimeField( default=timezone.now) def __str__(self): return str(self.id) Error in console is error TypeError: str returned non-string (type tuple) -
Django, Can tokens be used to verify user rights?
admin account test account setting.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } model.py class TestList(models.Model): key = models.AutoField(primary_key=True) pid = models.CharField(max_length=200) name = models.CharField(max_length=300) gender = models.CharField(max_length=50) age = models.IntegerField() birth_date = models.CharField(max_length=100) view.py class ListTest(generics.ListCreateAPIView): permission_classes = [permissions.DjangoModelPermissions, ] queryset = TestList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = TestListSerializer Sorry First of all, I am not good at English. I want to check if I have permission or not via token value. admin account has the "view" permission and the test account does not. However, despite the different permissions, both accounts were able to "view". What I want is to make sure that only users who have permission for that task can work with that permission. Thanks in advance to those who help me. Please let me know if you have any related sites or posts for that question! I am currently using tokens using knox. -
Get Input data perform calculation store in different field of same model
i have a models.py class DateConverterModel(models.Model): input_date = models.CharField(max_length=256, null=False) output_date = models.CharField(max_length=256) and a form forms.py class DateConverterForm(forms.ModelForm): class Meta: model=DateConverterModel fields=['input_date'] where im taking only input_date, now i'm performing calculation on it say converting date-string to date in views.py from django.shortcuts import render from .models import DateConverterModel from .forms import DateConverterForm from django.http import HttpResponseRedirect from dateutil import parser def date_converter(request): form = DateConverterForm() if request.method == 'POST': form = DateConverterForm(request.POST) if form.is_valid(): input_string = form.cleaned_data['input_date'] try: data = search_dates(input_string) except Exception as msg: print('Exception :', msg) else: try: for i in data: output_date = parser.parse(i[0]).strftime('%d/%m/%Y') DateConverterModel.objects.update(output_date=output_date) except TypeError as msg: print("String does not contain any day or dates") form.save() return HttpResponseRedirect('/response') return render(request, 'DateTimeConverter/dateconverter.html', context={'form':form}) how should i store calculated data in same field, im stuck can anyone help. -
Django unable to find javascript static files, not rendering any styling
Feels like I'm missing something basic. I'm just trying to make an django application of currently nothing but a login page using an html template that has its own css and js. But I'm having weird issues with the statements for linking my static files. No CSS styling is being rendered in my browser, and all of the javascript links get 404 file not found errors on my django server. This is the <head> of auth-login.html. {% load static %} <!doctype html> <html lang="en"> <head> <title>Login template from online</title> <!-- these aren't giving errors --> <link rel="shortcut icon" href="{% static 'assets/images/favicon.ico' %}"> <link href="{% static 'assets/css/bootstrap.min.css' %}" id="bootstrap-style"/> <link href="{% static 'assets/css/icons.min.css' %}" type="text/css" /> <link href="{% static 'assets/css/app.min.css' %}" id="app-style" type="text/css" /> <!-- these are giving errors for some reason --> <script src="{% static 'assets/libs/jquery/jquery.min.js' %}"></script> <script src="{% static 'assets/libs/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <script src="{% static 'assets/libs/metismenu/metisMenu.min.js' %}"></script> <script src="{% static 'assets/libs/simplebar/simplebar.min.js' %}"></script> <script src="{% static 'assets/libs/node-waves/waves.min.js' %}"></script> <script src="{% static 'assets/js/app.js' %}"></script> </head> In settings.py, this is how I'm specifying the static files location: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # lpbs_demo/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticAssets') The Django project is currently structured with a project app called lpbs_demo and an … -
ServerSelectionTimeoutError when using MongoClient
In my current project, I tried to connect to a MongoDB database on our server in one of my view functions. Here is my code: 260 context = {} 261 client = MongoClient() 262 db = client.lichess 263 puzzles = db.puzzle.find().limit(5) 264 265 try: 266 player = models.Player.objects.get(player_user_id=request.user) 267 logger.debug('found player') 268 except: 269 logger.debug('player doesn\'t exist!') 270 player = models.Player(player_user_id=request.user, player_isconsented=True, player_isactive=True, player_deactivated_ts=None) 271 player.save(force_insert=True) 272 273 puzzle_record_count = len(models.PR.objects.filter(PR_player_id=player.player_id)) 274 logger.debug('puzzle record count: ' + str(puzzle_record_count)) 275 # some puzzles are attempted 276 if puzzle_record_count > 0: 277 logger.debug('puzzle id: ' + str(puzzles[puzzle_record_count-1]['_id'])) 278 most_recent_puzzle_record = models.PR.objects.get(PR_puzzle_id=puzzles[puzzle_record_count-1]['_id']) However, when I tried to access puzzles[puzzle_record_count-1]['_id'](on line 277), I encountered this ServerSelectionTimeoutError: Could it be caused by my lab's server change that I didn't know? This code worked fine before, and it started causing such error about 2 days ago. Thanks in advance!