Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to integrate Opencv in Django rest frame
I have a simple opencv file that converts frames to video. I fetch video from Django db and convert to frame. Now my question is how can I save the converted frames in the directory where my video is.? I get this error when I try to use the uoload_to function as a save path in the video_to_frame function cv2.imwrite(os.path.join(upload_to,'new_image'+str(i)+'.jpg'),frame) TypeError: expected str, bytes or os.PathLike object, not function Upload directory def upload_to(instance, filename): base, extension = os.path.splitext(filename.lower()) return f"SmatCrow/{instance.id}/{filename}" Model.py from .utils import video_to_frame class MyVideo(models.Model): name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) videofile= models.FileField(upload_to=upload_to) def __str__(self): return self.name + ": " + str(self.videofile) def save(self, *args, **kwargs): super(MyVideo, self).save(*args, **kwargs) tfile = tempfile.NamedTemporaryFile(delete=False) tfile.write(self.videofile.read()) vid = video_to_frame((tfile.name)) Opencv def video_to_frame(video): today = date.today() d = today.strftime("%b-%d-%Y") cap= cv2.VideoCapture(video) i=1 while(cap.isOpened()): ret, frame = cap.read() if ret == False: break if i%10 == 0: cv2.imwrite(os.path.join(upload_to,'new_image'+str(i)+'.jpg'),frame) i+=1 cap.release() cv2.destroyAllWindows() -
Ignoring a Django signal with a test mock
I have a function setup to hook the pre_delete on a model and I want to ignore this during testing using unittest.mock.patch, but this only works when I use the signal name from Django or if I disconnect it by dispatch_uid. The prototype looks like: @receiver(pre_delete, sender=MyModel, dispatch_uid="pre_delete_my_model") def pre_delete_my_model(sender, instance, *args, **kwargs): ... in my tests this works: @patch("django.db.models.signals.pre_delete") def test_something_that_triggers_pre_delete(self, pre_delete_mock): ... but I'd like something that's a bit more explicit, eg. @patch("my_app.signals.pre_delete_my_model") def test_something_that_triggers_pre_delete(self, pre_delete_mock): ... this doesn't work though, I assume because that's not the signal that's being raised, it's just set up to receive it. I have found a way that works using pre_delete.disconnect(...), but I'm an annoying person that doesn't like the way that looks with those calls spread around my tests. Is there a way to do this so that it can use something specific to the model or the handler in the decorator? -
Displaying tabular data using columnar with python
I have the structure as follows. I show it as a table with the columnar library. It works just fine. But because the incoming json data is "dict", it does not show it as a single line. How can I show the above json data in single print (table) print screen? from time import sleep from django.views.decorators.http import require_POST import json from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import django_filters.rest_framework import requests from columnar import columnar from tabulate import tabulate @require_POST @csrf_exempt def webhook(request): while True: get_active_position() return HttpResponse(request, content_type='application/json') def get_active_position(): print("get_active position") data = "{'symbol': 'BCHUSDT', 'positionAmt': '0.001', 'entryPrice': '266.85000', 'markPrice': '259.99000000', 'unRealizedProfit': '-0.00686000', 'liquidationPrice': '0', 'leverage': '20', 'maxNotionalValue': '250000', 'marginType': 'cross', 'isolatedMargin': '0.00000000', 'isAutoAddMargin': 'false', 'positionSide': 'LONG'} {'symbol': 'ETHUSDT', 'positionAmt': '0.001', 'entryPrice': '385.88000', 'markPrice': '381.85854735', 'unRealizedProfit': '-0.00402145', 'liquidationPrice': '0', 'leverage': '10', 'maxNotionalValue': '2000000', 'marginType': 'cross', 'isolatedMargin': '0.00000000', 'isAutoAddMargin': 'false', 'positionSide': 'LONG'} " for sym in data: if sym['positionAmt'][:1] == "-" and sym['positionAmt'] <= str("0.00000"): headers = ["Symbol", "EntryPrice", "positionSize", "Side"] symbols = [ [sym['symbol'], sym['entrypPrice']] ] table = columnar(symbols, headers=headers) print(table) # Long position elif sym['positionAmt'] >= str("0.00000"): headers = ["Symbol", "EntryPrice", "positionSize", "Side"] symbols = [ [sym['symbol'], sym['entrypPrice']] ] table = columnar(symbols, headers=headers) print(table) return … -
ImportError: attempted relative import with no known parent package while running code
Code: from django.shortcuts import render, redirect from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from .forms import BookForm from .models import Book from django.db import models On running code i am getting this error **Output: ** Traceback (most recent call last): File "/media/programmer/New Volume/Projects/TradeCred/backend.py", line 6, in <module> from .forms import BookForm ImportError: attempted relative import with no known parent package -
How to make no-reply@company.com in Django
i have a problem, when i sent email, my host user email is the sender, i want no-reply@company.com is the sender if customer see the email, #views.py email_body = 'Hallo '+user.username + 'Silahkan login akun anda, dan print surat yang anda ajukan' email_subject = 'Pengajuan Surat Diterima' email = EmailMessage( email_subject, email_body, 'Kecamatan Bintan Utara <noreply@kantorkecamatanbintanutara.com>', [user.profile.email], ) email.send(fail_silently=False) context = { 'form3':form3, 'form4':form4, 'code':code } #setting.py EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = 'akuntest1291@gmail.com' EMAIL_HOST_PASSWORD = 'krnhbjfcczgrfutp' EMAIL_USE_TLS = True EMAIL_PORT = 587 -
Newer Django requires applying migration, what are the changes in database
I'm working on upgrading a legacy project, currently still on Python 2.7.18 as the highest Python-2 before upgrade to 3. After upgrading Django from 1.8.13 to 1.11.29, the project seems to be running OK, but with message saying: ... Performing system checks... System check identified no issues (0 silenced). You have 5 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, authtoken, sites. Run 'python manage.py migrate' to apply them. ... Following the message, I applied the migrations by command python manage.py migrate, and the message disappeared when starting again. The legacy project is already running on an existing database for production, so I'm wondering: What changes did the migrate make into database? Is there some way to compare (MySQL) database before and after applying the migration? I'm new to Python upgrade, so is there any important things to check for this type of migrate upon existing database? Any thoughts will be highly appreciated. More details, if interesting to you: Screenshot of applying migration: " (venv) [appuser@testserver PROJECT]$ python manage.py migrate /data/EBC-dev/venv/lib/python2.7/site-packages/arrow/arrow.py:28: DeprecationWarning: Arrow will drop support for Python 2.7 and 3.5 in the upcoming v1.0.0 release. Please upgrade to Python 3.6+ … -
Django - Adding text from dictionary in a static tag
In Django, I have this line in my HTML file which adds an image using the static tag. However, it seems like {{ dictionary.key }} is not working in this case. <img src="{% static 'Image/Portfolio/{{article.slug_title}}/{{article.imageFile}}.jpg' %}"> Is there any method to solve this problem or it is possible to like with the absolute route? Thank you. -
Problemas para usar el FilteredSelectMultiple de Django
soy algo nuevo con django, y tengo el problema de que cuando utilizo FilteredSelectMultiple de django en mis propias vistas, no se muestra como cuando se asignan permiso en el admin de django, sino mas bien esto:enter image description here En mi Forms.py tengo esto: class GroupForm(forms.ModelForm): permissions = forms.ModelMultipleChoiceField(queryset=Permission.objects.all(), required=True, widget=FilteredSelectMultiple("Permissions", is_stacked=False)) class Media: css = {'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n/',) class Meta: model = Group fields = '__all__' En mi Views.py: class GrupoRegistrar (LoginYSuperStaffMixin, ValidarPermisosMixin, CreateView): model = Group form_class = GroupForm template_name = "Grupos/registrar_grupos.html" permission_required = ('', ) def post(self, request, *args, **kwargs): if request.is_ajax(): form = self.form_class(data= request.POST, files= request.FILES) if form.is_valid(): form.save() mensaje = f'{self.model.__name__} registrado correctamente' error = 'No existen errores' response = JsonResponse({'mensaje': mensaje, 'error': error}) response.status_code = 201 return response else: mensaje = f'{self.model.__name__} no se ha podido registrar!' error = form.errors response = JsonResponse({'mensaje': mensaje, 'error': error}) response.status_code = 400 return response return redirect ('empleado:grupos_inicio') en mi html: <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h2 class="modal-title">Registro de Grupos de permisos</h2> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {{ form.media }} <form id="form_creacion" action="{% url 'empleado:grupo_registro' %}" method="POST"> {% csrf_token %} <div class="modal-body"> <div id="errores"> </div> {{form}} … -
Accessing a public text file by passing a key in Django
I am looking to host a text file that will be publicly accessible on a Django application: http://www.example.com/textfile However, when someone is accessing this text file, they need to to pass an access key, e.g http://www.example.com/textfile?accesskey=123456 The access key is only known to members who are allowed access to this file. The reason for doing it this way is that I have a 3rd party legacy device that can only read text files, and I need to protect the file somehow. Is it possible to run this in Django urls.py? Any help is really appreciated. -
API Django Rest Framework on Cloud Run shutting down
I have implemented an API DRF on Cloud Run. The Dockerfile is the following: # Use the official lightweight Python image. # https://hub.docker.com/_/python FROM python:3.7-slim # Allow statements and log messages to immediately appear in the Cloud Run logs ENV PYTHONUNBUFFERED True # Prevents Python from writing pyc files to disc (equivalent to python -B option) ENV PYTHONDONTWRITEBYTECODE True ARG REQFILE=base.txt ENV REQFILE ${REQFILE} # install dependencies RUN pip install --upgrade pip # Copy application dependency manifests to the container image. # Copying this separately prevents re-running pip install on every code change. COPY requirements/*.txt ./ # Install production dependencies. RUN pip install -r ./${REQFILE} # Copy local code to the container image. ENV APP_HOME /app WORKDIR $APP_HOME COPY . ./ # Run the web service on container startup. Here we use the gunicorn # webserver, with one worker process and 8 threads. # For environments with multiple CPU cores, increase the number of workers # to be equal to the cores available. CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app It is the same as described in the documentation : https://codelabs.developers.google.com/codelabs/cloud-run-django#6 But since a few days, without any significative change on my code, I have … -
onclick how to toggle button and fa icons?
Here I have a post detail view ,where i want to toggle the color of like button, <li> <button style='margin-top:-20px' class="btn btn-link text-dark p-0 border-0 btn-outline-light" id="like-button" value="{{post.id}}">{% csrf_token %} <i class="fa fa-heart"></i> <span class="" id="like_count">{{post.likes.count}}</span> </button> </li> jscript: $(document).on('click', '#like-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "posts:like" %}', data: { postid: $('#like-button').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("like_count").innerHTML = json['result'] }, error: function (xhr, errmsg, err) { } }); }) </script> I simply want to change the color of heart icon ; on click heart filled with red color and onclick heart become blank or white. -
Cannot Import Include From Django
After running the command from django.urls import include I get the error freduah@freduah:~/Desktop/DjangoReactTodo/todo$ ./manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7fd1e13a4a50> Traceback (most recent call last): File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/freduah/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 256, in check for pattern in self.url_patterns: File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/freduah/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/freduah/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/freduah/Desktop/DjangoReactTodo/todo/todo/urls.py", line 18, in <module> from django.urls import include ImportError: cannot import name include Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7f2db9839a50> Traceback (most recent call last): File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check … -
Report building in Django
I am trying to build a system which will enable my users to create their own reports based on the model of their choosing without me having to code them every time they need updating. In order to do this, I've come up with the following models:- from django.db import models from django.contrib.contenttypes.models import ContentType class ReportField(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) data_method = models.CharField(max_length=100) def get_value_for(self, object): return getattr(object, self.data_method) class Report(models.Model): name = models.CharField(max_length=200) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) data_fields = models.ManyToManyField(ReportField) The idea is that users can create a Report based on the model they're interested in. They can then add any number of ReportFields to that report and, when the report runs, it will call the data_method (the name of a property) on each instance of the model in the db. The bit I'm having trouble with is defining which properties the users can have access to. I need to have a way of creating a load of ReportFields with certain data_methods for each model. But I don't want to create them by hand - I want it to work in a similar way to the way Permissions work in Django, if that's possible, like this:- class MyModel(models.Model): … -
Handling database connection errors / operational error exceptions in Python / Django?
I am running multiple databases and I need to handle this exception. How can I do it either in the view or a more general approach ? I am using PostgreSQL. It's a bit ugly to wrap my whole code like below. import psycopg2 def Main(request): try: myqs = customers.objects.all() except psycopg2.OperationalError as e: print('operational error, handle this') return render(request, 'core/main/main.html', {'qs': myqs}) -
Calling a python function via AJAX in Django
I am sending a request via AJAX upon a button (whose id="transcript") click to trigger a function called transcript. AJAX document.querySelector('#transcript').addEventListener('click', () => { fetch(`transcript/${CNIC}`); views.py def transcript (request, cnic): form = TranscriptForm() return render (request, "certificates/transcripts.html", { "form": form, "cnic": cnic }) The fetch request works fine, but the new page i.e. transcripts.html does not render. I have to manually type the URL to update the view. Why is it happening, can anybody please explain? The output in console: views.js:62 Fetch finished loading: GET "http://127.0.0.1:8000/transcript/1530660001979". -
How create a project in Django path
I would like create my first project in Django. I have installed Python (Version 3.7.2) and Django (Version 3.1.2). In my PC I run a command py -m django startproject mysite, however there is no mysite file in C:\Users\misak\AppData\Local\Programs\Python . The mysite file has been created in C:\Users\misak . How can I create mysite file by default in C:\Users\misak\AppData\Local\Programs\Python , please? Because than I want to run the sever using a command py manage.py runserver, which is not possible now, because of an error "C:\Users\misak\AppData\Local\Programs\Python\Python38\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory" Thanks a lot! -
Storing File in Json Field, Django
I'm working on a project which requires users to submit posts of various forms. There are posts that require images and others that require videos. To deal with this and other complexities, I was thinking of using jsonfields. My current issue is handing files, that is images and videos. I was hoping to be able to store the file url in a field in the json field but I haven't come across anything like that on the internet. Is it possible or advisable to go on with this approach? If so, how can it be done? -
Main matching query does not exist
enter image description here main.models.Main.DoesNotExist: Main matching query does not exist. -
How to slice in django template by a string
I just want to slice a string on django in two parts, passing a caracter like "|" Example: 2007-007134|10003L Part 1: 2007-007134 Part 2: 10003L I tried somethings but without success Someone can help me? -
Django channels testing weird database behaviour
Django/channels newbie: I'm trying to write unit tests for my application, but I'm getting some weird behaviour from tests. I suspect it has something to do with either asynchronous code or django testing database but I'm lost. My consumer has this kind of structure: class GameConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['gameID'] self.room_group_name = 'game_%s' % self.room_name # check something from database to decide if this connection should be rejected if not await self.does_game_exists(): await self.close(4001) else: await self.accept() await self.channel_layer.group_add( self.room_group_name, self.channel_name ) # insert data into db await self.add_player_to_game() @database_sync_to_async def does_game_exists(self): .... @database_sync_to_async def add_player_to_game(self): .... This works when using the application normally; the data is inserted in the db. Now the unit test: class WSConsumerTest(TransactionTestCase): fixtures = ['test-data.yaml'] @database_sync_to_async def get_num_players(self): ... @database_sync_to_async def create_test_game(self): ... async def test_player_is_added_on_successful_connection(self): game = await self.create_test_game() application = URLRouter([ url(r'ws/game/(?P<gameID>[a-zA-Z0-9]{6})', consumers.GameConsumer), ]) communicator = WebsocketCommunicator(application, f"/ws/game/{game.gameID}") connected, _ = await communicator.connect() player_count = await self.get_num_players() self.assertEqual(player_count, 1, "Player is not added in database after successful connection") communicator.disconnect() This fails. get_num_players returns the number of player in the game instance created by create_test_game. I'm sure this two functions are correct, they are standard django ORM queries. I tried running test … -
Django rest framework, empty request.data when using UUID as id
I'm working on an API which can allow user to remove Project belonging to some specific Workspace. I used to do it by calling this URL with this JSON as data and it worked pretty fine. URL : .../my_api/workspaces/[workspace_id]/projects JSON : { "id": [project_id_to_remove] } But since I've replaced the default generated id to models.UUIDField, the same call raise a KeyError because request.data turn out to be an empty dict. I cannot figure what goes wrong since my others use cases works correctly even with the use of UUID as id. models.py: class Workspace(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True) class Project(models.Model): workspace = models.ForeignKey('Workspace',related_name='workspace_projects',on_delete=models.CASCADE,blank=True, null=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True) serializers.py class ProjectSerializer(serializers.ModelSerializer): def __custom_validator__(self, data): method = self.context['request'].method if method in ['DELETE']: projects_id = [project.id for project in self.instance] if data['id'] not in projects_id: raise serializers.ValidationError( "Action canceled: Not a Workspace project.") def validate(self, data): data = super().validate(data) self.__custom_validator__(data) return data class Meta: model = Project fields = ['id', 'workspace'] views.py class WorkspaceProjectViewSet(viewsets.ModelViewSet): serializer_class = ProjectSerializer def destroy(self, request, pk): instances = Project.objects.filter(workspace=workspace) serializer = self.get_serializer(instances, data=request.data) serializer.is_valid(raise_exception=True) # Perform deletion. project = get_object_or_404( Project, pk=serializer.validated_data['id']) self.perform_destroy(project) return self.__get_response__(workspace) -
How to best update the Django website from version 1.10 to the latest 3.1?
I'm just considering an update of an old website based on an old Django's wedding, still written in Python 2. It's a simple landing page with a couple of subpages. I would like to make an upgrade to the latest version 3.1. Unfortunately, the attempt to upgrade to version 2 failed (the previous developer created the site using so many additional modules that I don't see the possibility of meeting all the dependencies, because some of them are no longer expandable and supported. Is there any faster way to upgrade than to move the front-end to the latest version and write back-end again ? -
Django and snipcart product crawling
I'm using django and I've managed to implement dynamic discounts like this: Http request contacts the endpoint -> endpoint checks the request object to see if the user is authenticated -> if the user is authenticated, the view function checks the corresponding User object in the database to see if the user is eligible for a discount -> If he is, it takes the discount rate from the User object and uses it to change the price(s) in the queryset without touching the actual price in the database -> this queryset is then sent as a context to the template where it is rendered and picked up by snipcart's javascript. My question is this: When snipcart then crawls the URL, will it not do so with a different set of Http headers which would change the execution flow of the view function to display undiscounted prices as the request object that snipcart sends to crawl the URL would be un-authenticated? I suppose my question could be generalized like this: how does snipcart crawl protected URLs? https://docs.snipcart.com/v3/security -
What is the best practice while renaming Django Models? [Database: MySQL, PostgreSQL or SQLite]
I really want to know what is the best practice that could be done while renaming Django Models and Models Fields. Is there are preferred method or we should directly rename and migrate each FIELD or MODEL inside Django. -
Working with different Bokeh components from server_document() in Django View
I have a bokeh server running containing a graph and dropdown menu. I displayed these components in a Django app using server_document("url to the bokeh app") in the view. I managed to display the figure and the dropdown in the html through {{ script | safe }}, but I would like to split the dropdown menu from the graph for styling purposes. I tried {{ embed(roots.graph) }} but Django doesn't allow this. How do I split the different components, so I can display them separately?? Maybe process the script returned by server_document() in the view?? Many thanks in advance! Django View: def BokehView(request): context = dict() # server_document connects to bokeh server and returns a <script> tag with the components context['script'] = server_document("http://localhost:5006/visualization") return render(request,'map.html',context) HTML: <div class="container-fluid"> {{ script | safe }} </div>