Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Error during WebSocket handshake: Unexpected response code: 500
I have been following this tutorial to build a chat application. I have been facing WebSocket connection to 'ws://127.0.0.1:8000/ws/lobby/' failed: Error during WebSocket handshake: Unexpected response code: 500 error. I checked other solutions too but they don't seem to work. The console displays the error at (room.html) 'ws://' + window.location.host + '/ws/' + roomName + '/' ); in the console. The following is displayed in the terminal: HTTP GET /favicon.ico/ 200 [0.01, 127.0.0.1:53842] HTTP GET /lobby/?username=darsh 200 [0.01, 127.0.0.1:53842] WebSocket HANDSHAKING /ws/lobby/ [127.0.0.1:53844] HTTP GET /favicon.ico/ 200 [0.01, 127.0.0.1:53842] Exception inside application: No route found for path 'ws/lobby/'. Traceback (most recent call last): File "/home/darsh/.local/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/routing.py", line 168, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/lobby/'. WebSocket DISCONNECT /ws/lobby/ [127.0.0.1:53844] I am attaching the … -
Weasyprint failed to load image at url: Name or service not known
I am working with weasyprint after I migrated from xhtml2pdf, and I am finding some issue with getting static files. I get the following error: 2021-12-03 14:45:50,198 [ERROR] Failed to load image at "http://api.dashboard.localhost:8000/static/logos/logo.png" (URLError: <urlopen error [Errno -2] Name or service not known>) but when I access the same URL weasyprint couldn't, either on my browser or curl, I am able to view/ access the file. Here is my code: from io import BytesIO import mimetypes from pathlib import Path from urllib.parse import urlparse import logging from django.conf import settings from django.contrib.staticfiles.finders import find from django.core.files.storage import default_storage from django.urls import get_script_prefix from django.template.loader import render_to_string import weasyprint from weasyprint import HTML logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.FileHandler("debug.log"), logging.StreamHandler() ] ) # https://github.com/fdemmer/django-weasyprint/blob/main/django_weasyprint/utils.py def url_fetcher(url, *args, **kwargs): # load file:// paths directly from disk if url.startswith('file:'): mime_type, encoding = mimetypes.guess_type(url) url_path = urlparse(url).path data = { 'mime_type': mime_type, 'encoding': encoding, 'filename': Path(url_path).name, } default_media_url = settings.MEDIA_URL in ('', get_script_prefix()) if not default_media_url and url_path.startswith(settings.MEDIA_URL): media_root = settings.MEDIA_ROOT if isinstance(settings.MEDIA_ROOT, Path): media_root = f'{settings.MEDIA_ROOT}/' path = url_path.replace(settings.MEDIA_URL, media_root, 1) data['file_obj'] = default_storage.open(path) return data elif settings.STATIC_URL and url_path.startswith(settings.STATIC_URL): path = url_path.replace(settings.STATIC_URL, '', 1) data['file_obj'] = open(find(path), 'rb') return data … -
AttributeError when trying to return Id from queryset
I'm building a API to get some informations from a Chess board in Django, I have a model with fields: id, piece_name, color, initial_position. MODEL class ChessB(models.Model): class Meta: db_table = 'chess' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) piece_name = models.CharField(max_length=200) color = models.CharField(max_length=200) initial_position = models.CharField(max_length=200) SERIALIZERS class ChessBSerializer(serializers.ModelSerializer): class Meta: model = ChessB fields = '__all__' VIEW class ChessBList(generics.ListCreateAPIView): serializer_class = ChessBSerializer def get_queryset(self): queryset = ChessB.objects.all() piece_name = self.request.query_params.get('piece_name') if piece_name is not None: queryset = queryset.filter(piece_name=piece_name) queryset = queryset.values_list('id', flat=True) return queryset What i'm trying to do is: informing my piece_name as paramether, should return just my Id For example: call http://127.0.0.1:8000/chessb/?piece_name=queen should return: { "id":"id-from-queen-here" } But when I tried to use values_list('id') on my View, I got a error as follow: Internal Server Error: /chessb/ Traceback (most recent call last): File "C:\Users\luizg\Python\Python310\lib\site-packages\rest_framework\fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "C:\Users\luizg\Python\Python310\lib\site-packages\rest_framework\fields.py", line 97, in get_attribute instance = getattr(instance, attr) AttributeError: 'UUID' object has no attribute 'piece_name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\luizg\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\luizg\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\luizg\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in … -
document the debugging process -Logical Error
How I can document the debugging process for a Django? I mean if I have a Logical Error and I have been asked to document it how I can do so, where I don't know How to solve this error -
Why doesn't Django does recognise an app?
I an new to Django and I wrote a program which should print a text in the browser page. I therefore wrote urls.py and views.py, but the browser only shows the welcome page ("The install worked successfully"). What can the mistake be? -
SSL connect to mysql from django
We just had a migration from a "unsecured" mysql DB to a SSL mysql but my Django application cannot connect anymore. content of settings.py DATABASES = { "default": { "ENGINE": 'django.db.backends.mysql' "NAME": env("DATABASE_NAME"), "USER": env("DATABASE_USER"), "PASSWORD": env("DATABASE_PASSWORD"), "HOST": env("DATABASE_HOST"), "PORT": env.int("DATABASE_PORT"), "CONN_MAX_AGE": env.int("DATABASE_CONN_MAX_AGE", default=0), }, "OPTIONS": { "timeout": env.int("DATABASE_CONN_TIMEOUT", default=60), "ssl": { "ca": CA_ROOT_PATH }, } } and when I execute this Django command line : python3 manage.py dbshell (which used to work with the pre-migration DB), I receive the error message : ERROR 2026 (HY000): SSL connection error: unknown error number subprocess.CalledProcessError: Command '['mysql', '--user=user', '--password=password', '--host=host', '--port=3306', 'db']' returned non-zero exit status 1. As you can see, the executed mysql command does not contain anything related to SSL connection. I tried also to modify the OPTIONS in settings.py with these values : "OPTIONS": { "timeout": env.int("DATABASE_CONN_TIMEOUT", default=60), "ssl": { "ssl-ca": CA_ROOT_PATH, "ca": CA_ROOT_PATH }, "ssl-ca" : CA_ROOT_PATH, } Still the same output. It does not seem to use the SSL options in any way... Any idea what I should look for ? -
Django Heatmap showing name once
Am trying to make a Heatmap but am getting this result where similar name with different value is presented once on the Heatmap. The printing down is to show me the results . The heatmap should look like squares EXAMPLE: My code is, <script> ... data = [{% for Bindll in tarname %} {group: '{{ Bindll.targetnameassignedbycuratorordatasource }}', variable:'{{ Bindll.zincidofligand}}', value: {{Bindll.ki_nm}} }, {% endfor %}]; var myGroups = [{% for Bindll in tarname %} "{{ Bindll.targetnameassignedbycuratorordatasource }}", {% endfor %}] var myVars = [{% for Bindll in tarname %} "{{ Bindll.zincidofligand}}", {% endfor %}] // Build X scales and axis: var x = d3.scaleBand() .range([0, width]) .domain(myGroups) .padding(0.01); svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)) .selectAll("text") .attr("y", 0) .attr("x", 9) .attr("dy", ".35em") .attr("transform", "rotate(60)") .style("text-anchor", "start"); // Build Y scales and axis: var y = d3.scaleBand() .range([height, 0]) .domain(myVars) .padding(0.01); svg.append("g") .call(d3.axisLeft(y)); // Build color scale var myColor = d3.scaleLinear() .range(["#ffffff", "#c60606"]) .domain([d3.min(data, function(d) { return d.value}), d3.max(data, function(d) { return d.value})]) //Read the data and add squares svg.selectAll() .data(data, function(d) { return d.group + ':' + d.variable; }) .enter() .append("rect") .attr("x", function(d) { return x(d.group) }) .attr("y", function(d) { return y(d.variable) }) .attr("width", x.bandwidth()) .attr("height", y.bandwidth()) .style("fill", function(d) … -
TypeError: academic() missing 1 required positional argument: 'request'
I can not pass request to views.py to serializers.py. Views.py def academic(request): is_superuser = request.user.is_superuser getdata = is_superuser return getdata serializers.py class SohanSerializer(serializers.ModelSerializer): is_name = True is_academic = views.academic //Here I call the academic fuction from views if is_academic: academic = Academic(many=True,read_only=True) else: academic = serializers.HiddenField(default=None) if is_name: pass else: name = serializers.HiddenField(default=None) class Meta: model = Student fields = ['name','studentID','email','image','phone','blood','address','academic'] is_academic = views.academic //Here I call the academic fuction from views Server is running but I can't get exact result. When I pass is_academic = views.academic() It's returned TypeError: academic() missing 1 required positional argument: 'request' I think I need to pass request inside the function as like is_academic = views.academic(request) but this not working. Please help me to pass the request inside the is_academic = views.academic(request) Or tell me any way to pass the request. -
Github Actions running 0 tests
I have three tests in my Django project which get executed running "python manage.py test appname" locally. However, Github Actions runs zero tests, returning no errors. How can I fix this? I would prefer not to use any more libraries if possible. I am using the default Django workflow. name: Django CI on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.7, 3.8, 3.9] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Tests run: | python manage.py test appname I tried using "python manage.py test" both with and without the appname, neither work. -
django.template.exceptions.TemplateDoesNotExist: documents/project_confirm_delete.html
I used Django 3.2.9 and used a class in order to delete a project. Here is my code. from django.views.generic.edit import CreateView, DeleteView, UpdateView class ProjectDeleteView(DeleteView): http_method_names = ['get'] model = Project pk_url_kwarg = "pk" def get_success_url(self): return reverse("documents:draftdocumentview") When I called it said like this; django.template.exceptions.TemplateDoesNotExist: documents/project_confirm_delete.html I am not sure about the project_confirm_delete.html. Should I make the html file? Or it is supported from Django Template? -
creating an email-defined user in django
I am creating a simple web app in django in which users are identified by their email and not a username. I've been following the guide: https://www.fomfus.com/articles/how-to-use-email-as-username-for-django-authentication-removing-the-username/ And it works fine! Yet, if I choose to have two other required fields the creation of the superuser fails, while the creation of a normal user does not. Can someone help me understand why? user app - models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, first_name, last_name, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user = self.model(first_name=first_name, **extra_fields) user = self.model(last_name=last_name, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, first_name, last_name, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, first_name, last_name, password, **extra_fields) def create_superuser(self, email, first_name, last_name, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: … -
Decode pako deflate, gzip in python
Encoded data should be sent from my front server to reduce data weight, I want to use pako deflate or gzip for this. const compressed = deflate(JSON.stringify({ project: projectId, title: screen.title, }, {to: "string"})); const res = await fetch( screensApiConfg.SCREENS_PATHS.create(), { credentials: "include", method: "POST", body: JSON.stringify(compressed), headers: { "Content-Type": "application/json", }, }, ); After coding, I get this: Uint8Array(43) [120, 156, 171, 86, 42, 40, 202, 207, 74, 77, 46, 81, 178, 50, 50, 212, 81, 42, 201, 44, 201, 73, 85, 178, 82, 114, 43, 74, 204, 77, 85, 176, 52, 52, 55, 84, 170, 5, 0, 205, 0, 10, 190, buffer: ArrayBuffer(43), byteLength: 43, byteOffset: 0, length: 43] I transfer this data to my django backend. How can I decode this data back, I tried using zlib.decompress but it didn't work for me. class CreateScreenApi(generics.CreateAPIView): serializer_class = ScreenSerializer def post(self, request, *args, **kwargs): print(request.data) data = list(request.data.values()) print(data) First, I get the data in the form of a dictionary and then translate it into a list. Dict: {'0': 120, '1': 156, '2': 171, '3': 86, '4': 42, '5': 40, '6': 202, '7': 207, '8': 74, '9': 77, '10': 46, '11': 81, '12': 178, '13': 50, '14': 50, … -
Django running port 8000 but image port is 80 in production
I have Serialized my model and it's working well except an issue This is my serializers.py class AuthorSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("first_name", "last_name", "avatar",) this is what i am seeing in browser, Please have a look at this, the address bar port and image port are not same. It's working well, the issue occures when i run the project on Docker using nginx and gunicorn Here you go for my nginx config. server { listen 8000; location /static { alias /backend/staticfiles; } location /media { alias /backend/media; } location / { proxy_pass http://backend:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } and this is my docker-compose.yml version: '3.7' services: backend: build: context: . volumes: - static_data:/backend/staticfiles - "./dist/media:/backend/media" # map to local machine env_file: # if .env in root, we have to show .env here must - ./.env depends_on: - db proxy: build: context: ./proxy volumes: - static_data:/backend/staticfiles - "./dist/media:/backend/media" # map to local machine ports: - "8000:8000" env_file: # if .env in root, we have to show .env here must - ./.env depends_on: - backend - db db: image: postgres volumes: - database:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - "5432:5432" … -
django collectstatic picking files from wrong location
I am beginner in Python and Django. I am using Windows10 and I have installed Python 3.10.0 and pip 21.3.1. I installed Django using following commands pip install virtualenvwrapper-win mkvirtualenv firstdjango pip install django django-admin startproject demo then I created APP for just simple static HTML page and now I am trying to use static files. I created a folder having name "static" on root and placed all css, js etc files in it and in settings.py, I mentioned following. STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') Now when I hit python manage.py collectstatic then it is not copying, what is in my static folder to assests folder. When I tried to check from where collectstatic is trying to copy using following command python manage.py findstatic -v 3 dummy then I got following C:\Users\dell\Envs\firstdjango\lib\site-packages\django\contrib\admin\static but my project location is E:\django\demo I am not getting, why collectstatic is not able to copy correct files and hence I do not get correct paths of my css, js and images in my web page. -
How to avoid that Django adds url link to every html element that follows the link
i would like to achieve something very basic in Django but can't find out what I am doing wrong. On my apps "index.html", I would like to add a button which redirects to another html template ("site.html") with other content. I added the following to "index.html" which is working: <body> <h2>foo</h2> {% block content %} <button><a href="{% url 'site' %}"/>Click</button> {% endblock %} <p>bar</p> </body> Clicking on the button gets me to "site.html", however all html items which I add on "index.html", for example the paragraph "bar" would also get rendered as hyperlink. I tried creating different Django blocks or making different html sections but that doesn't fix it. Thank you for your help. -
is it possible to use celery with sqs without django
I am following the celery tutorial, trying to have a local celery worker connect to an SQS queue that I have running on AWS (I am a complete noob on SQS/Celery). This is my task.py: from celery import Celery from kombu.utils.url import safequote # fake keys here and in the rest of the question, I am using actual valid creds aws_access_key = safequote("ABCDEFGFHIKJ:") aws_secret_key = safequote("abcdefgjk12345678/abcd/123/secretkey") broker_transport_options = {'region': 'us-west-2'} broker_url=f"sqs://{aws_access_key}:{aws_secret_key}@" app = Celery('tasks', broker=broker_url) @app.task def add(x, y): return x + y but according to the logs, it seems this is not trying to reach AWS at all: [2021-12-03 12:59:46,358: WARNING/MainProcess] No hostname was supplied. Reverting to default 'None' [2021-12-03 12:59:46,359: INFO/MainProcess] Connected to sqs://ABCDEFGHIJK:**@localhost// [2021-12-03 12:59:47,203: INFO/MainProcess] celery@ac78958533de ready. I tried specifying the hostname for the queue inside the broker url (I assumed this would work, but it doesn't) # setting the host after the @ without https fails broker_url=f"sqs://{aws_access_key}:{aws_secret_key}@"sqs.us-west-2.amazonaws.com/123456788/my-queue" # errors with Unrecoverable error: ClientError("An error occurred (SignatureDoesNotMatch) when calling the ListQueues operation: Credential should be scoped to a valid region, not 'us-east-1' Above error is kinda weird, because my queue lives in us-west-2 as I set in the broker_transport_options specifically to us-west-2. I also tried passing … -
django validate values for calculation
Hej! I need to do some simple calculations of filtered data in my django view. This works just fine when having values in the chosen filter. If the value is 0 or None I get an server error and the site collpases. Therefore I need a validator to make sure the given value is not 0 and not None. (my attempt is at the bottom) Currently if the validator is added it gives me the message that 'float' object is not callable, even before getting to the filter option/template. And: in my model is a m2m to the model where I get the values from. For each value can a unit be chosen and I only want to calculate if the units are identical, otherwise I want to get a warning. Does anyone knows how to achieve that? Or where to look? Any help is appreciated! :) # validators.py def validate_values(value): if value == 0: raise ValidationError(_('One of the given values is 0 or empty and the calculation therefore cannot be proceeded.'), code='notinrange') # views.py def process_mass_intensity(request): plants = Plant.objects.all() myFilter = PlantsNameFilter(request.GET, queryset=plants) plants = myFilter.qs total_m = plants.aggregate(Sum('used_in_plant__value'))['used_in_plant__value__sum'] product_m = plants.aggregate(product_mass=Sum('used_in_plant__value', filter=Q(used_in_plant__input_or_output='OUT')))['product_mass'](validators=[validate_values]) pmi = (total_m / product_m)(validators=[validate_values]) context … -
How to update django vairable inside javascript
Like we can access a variable in the JS part like "{{vaiable_name}}". How can we update the value of variable_name inside the javascript? -
time data 'Fri, 03 Dec 2021 11:43:35' does not match format '%a, %b %Y %H:%M:%S'
I have the following string:"Fri, 03 Dec 2021 11:43:55". I want to convert it to datetime with python.I am using strptime to convert it to datetime but it doesn't work. Here is my code from datetime import datetime dte_str = "Fri, 03 Dec 2021 11:43:55" dte = datetime.strptime(dte_str,"%a,%d %b %Y %H:%M:%S") time data 'Fri, 03 Dec 2021 11:43:35' does not match format '%a, %b %Y %H:%M:%S' How to solve the problem please! -
is there any way or package by which we can perform filters(searching) on custom raw sql query in django?
I read the below document : https://docs.djangoproject.com/en/3.2/topics/db/sql/ in model there are lots of filter lookup available like field__gt, field__lt, field__range, field__contains but i want to use these into raw sql like suppose query = SELECT * FROM customers WHERE customers.name like '%name%' and age < 30 and status IN ('active','pending') Here : customers.name like '%name%' name would be user input so i want to protect it from sql injection as well as filter it using % operator age < 30 30 would be user input, and want to perform < > = also IN ('active','pending') want to pass list of string using IN operator is there any proper way/package available by which we can run raw sql preventing sql injection as well as filtering data using %, IN, <, >, = operators. -
how to automatically redirect the user to a specific language in django
I have added new languages to my website and now it is available in English, French and Arabic Everything works fine, I couldn't figure out how to change the default language Currently when the user does not select any language, the site is displayed in English. Some users are complaining that English is not widely used in my country and the site should be in Arabic instead, so I want to do this: if the user does not select any language it will be redirected automatically to arabic. So when i visit my website like this: http://127.0.0.1:8000/ i will be automatically redirected to: http://127.0.0.1:8000/ar/ Is it possible to do something like this or do I have to change the default code for the whole website. i have this code in urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('core.urls')), path('user/',include('users.urls')), path('dashboard/',include('dashboard.urls')), path('wallet/',include('wallet.urls')), path('administration/',include('administration.urls')), path('chaining/', include('smart_selects.urls')), path('__debug__/', include(debug_toolbar.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += i18n_patterns ( path('',include('core.urls')), path('user/',include('users.urls')), path('dashboard/',include('dashboard.urls')), path('wallet/',include('wallet.urls')), path('administration/',include('administration.urls')), ) and this is my settings from django.utils.translation import gettext_lazy as _ LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGE_CODE = 'en' LANGUAGES =( ('en', ('english')), ('ar', ('Arabic')), ('fr', ('french')) ) -
Django webpack loader vuejs+typescript Refused to execute script frombecause its MIME type ('text/html') is not executable
I am using Django as backend and Vue3 as frontend in my application. In development server i did not have problem but now in production i am having problems to render the page. I have followed all the documentations but cannot find a solution. I am using django-webpack-loader to render the bundle which I formed using webpack5. But now i am getting an error hence thinking that django is trying to render fallback page. Refused to execute script from 'https://medtourism.uk/app-a7abdc6b502c1335fd69.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. My webpack.config.js module.exports = { mode:'production', entry:{ app: path.resolve(__dirname, './src/main.ts'), }, output: { filename: '[name]-[hash].js', path: path.resolve(__dirname, './assets/dist'), clean: true, }, module: { rules: [ { test: /\.vue$/, use: 'vue-loader' }, { test: /\.ts$/, loader: 'ts-loader', options: { appendTsSuffixTo: [/\.vue$/], } }, { test: /\.css$/i, use: [ "style-loader", "css-loader"], }, { test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i, // More information here https://webpack.js.org/guides/asset-modules/ type: "asset", }, ] }, resolve: { extensions: ['.ts', '.js', '.vue', '.json'], alias: { 'vue': '@vue/runtime-dom', 'bulma': 'bulma/css/bulma.css', } }, plugins: [ new VueLoaderPlugin(), new BundleTracker({ filename: './webpack-stats.json', publicPath: '/' }) ] }; my typescript config: { "compilerOptions": { "allowJs": true, "allowSyntheticDefaultImports": true, "declaration": false, "esModuleInterop": true, … -
Time Difference in Django Model
I am making a Django Software for a flight school to be made. I am trying to work on time difference between Arrival Time and Departure time to give me an Actual Elapsed Time. I post the code here: Models class LogEntry(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) from_aerodrome = models.ForeignKey( Aerodrome, on_delete=models.PROTECT, related_name='from_aerodrome') to_aerodrome = models.ForeignKey( Aerodrome, on_delete=models.PROTECT, related_name='to_aerodrome') departure_time = models.TimeField() arrival_time = models.TimeField() pilot = models.ForeignKey( Pilot, on_delete=models.PROTECT, related_name='pilot') instructor = models.ForeignKey( Pilot, on_delete=models.PROTECT, related_name='instructor', blank=True, null=True) date = models.DateField(auto_now_add=True) remarks = models.CharField(max_length=1000, blank=True, null=True) eet = models.CharField(max_length=255) @property def get_eet(self): aet = self.arrival_time - self.departure_time return aet def save(self, *args, **kwargs): self.eet = self.get_eet super(LogEntry, self).save(*args, **kwargs) class Meta: ordering = ('-arrival_time',) verbose_name_plural = 'Log Entries' Views: def insert_flight(request): aircraft = Aircraft.objects.all() aerodrome = Aerodrome.objects.all() pilot = Pilot.objects.all() if request.method == 'POST': aircraft_id = request.POST.get('aircraft') from_aerodrome = request.POST.get('from_aerodrome') to_aerodrome = request.POST.get('to_aerodrome') departure_time = request.POST.get('departure_time') arrival_time = request.POST.get('arrival_time') pilot = request.POST.get('pilot') instructor = request.POST.get('instructor') log_entry = LogEntry(aircraft_id=aircraft_id, from_aerodrome_id=from_aerodrome, to_aerodrome_id=to_aerodrome, departure_time=departure_time, arrival_time=arrival_time, pilot_id=pilot, instructor_id=instructor) log_entry.save() context = { 'aircraft': aircraft, 'aerodrome': aerodrome, 'pilot': pilot, } return render(request, 'flight/insert_flight.html', context) The error I am getting is: Error: TypeError: unsupported operand type(s) for -: 'str' and 'str' What am I doing wrong? … -
Python unittest change mock patch value on fly
I'm having trouble while dealing with patching. I'm using mock from unittest library. While testing check_codes() view I would like to set another values to db.find_one() api.utils.py from pymongo import MongoClient import os def get_share_code_collection(): client = MongoClient(os.getenv("DB_HOST")) db_handle = client[os.getenv("DB_NAME")] return db_handle["share_codes"] views.py def check_codes(self, request): db = get_share_code_collection() data = db.find_one({"specialist_id": {"$exists": True}}) test_views.py from unittest import mock @mock.patch("api.utils.get_share_code_collection") def test_share_code_correct_no_share_types( self, mocked_collection, mocked_share_code, user_model ): mocked_collection().find_one.return_value = True ... @mock.patch("api.utils.get_share_code_collection") def test_share_code_no_start_time( self, mocked_collection, user_model ): mocked_collection().find_one.return_value = False ... The only workaround I found is setting mocked_collection().find_one.side_effect = [True,False] but once it is initialized I can't add values. How can I deal with the problem? -
How do I limit read permissions of django media files stored on digitalocean only to my frontend?
I have a django project with react.js frontend deployed to DigitalOcean where users can upload their files. I'm using S3Boto3Storage. I know I can make media files public by setting default_acl = "public-read", but I want to grant read access to these files only to the requests from my frontend domain name, while keeping them private from all others. How can I do that?