Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Send an Email by passing an URL from anchor tag in Django
enter image description hereTo track email has opened or not I want to call an API whenever I will click the image from the email. My question is how to pass the URL in href, inside the anchor tag (check the below code I have provided). ** My problem is in the second last line : new_message = message + ' ' #<----My problem is on this line class SendEmailView(View): def post(self, request): # get data email_template_id = request.POST.get('email_template') recipient_email = request.POST.get('recipient_email') created_by = request.user email_template = Email.objects.get(id=email_template_id) recipient_instance = Recipient.objects.get(email=recipient_email) # Send_mail args subject = email_template.subject.replace('{name}', recipient_instance.name) message = email_template.email_body.replace('{name}', recipient_instance.name).replace('{email}', recipient_instance.email) from_email = "saadi.techlogicinas@gmail.com" recipient_list = listify(recipient_email) # Track Email email_id = email_template.id recipient_id = recipient_instance.id base_url = "http://127.0.0.1:8000/email/track/" **final_url = f'{base_url}/{email_id}/{recipient_id}/'** new_message = message + '<a href= final_url > <img src="#" /> </a>' #<----My problem is on this line # send_mail send_mail(subject, message, from_email=from_email, recipient_list=recipient_list, html_message=new_message) -
How can I pass in a CSRF token with my API requests if I don't have a user login for my Django site?
Using the Django rest framework, I have an API endpoint I created that I call within my static files that I would like to pass a CSRF token into so that I'm the only one who can access the API. My Django site does not have users with logins. I essentially want to do something like this in my API endpoint: @api_view(['POST']) def payment(request, *args, **kwargs): if (("Authorization" not in requests.headers) or (request.headers["Authorization"] != "token")): return Response({"Error": "Not authorized for access."}) ... Do I need to generate a token one time and use that repeatedly? Or can I generate one every time the script is used? And how can I access this csrf token in my HTML file? I'm using class-based views and I assume I would pass it in to get_context_data, but how would I set up the API endpoint to accept this CSRF token? -
Polymorphic relationship in Django
I have this relationship between my models: The model called MyModel might have a foreign key to model A or model B, How can I do this in Django? I heard that the solution called Polymorphic relationship but could not find the correct way to implement it. My code: from django.db import models class A(models.Model): email = models.EmailField() national_id = models.IntegerField() class B(models.Model): name = models.CharField(max_length=255) age = models.IntegerField() class MyModel(models.Model): name = models.CharField(max_length=255) provider = models.ForeignKey(to=A, on_delete=models.CASCADE) -
Integrating Nuxt Js in Django "GET /_nuxt/bed9682.js HTTP/1.1" 404 2918
I am trying to integrate my Nuxt application inside Django. I have my Nuxt application and django application inside the same folder. I have set up the settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'(Name of the nuxt application folder)/dist') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), #'admin-dashboard/' path('',TemplateView.as_view(template_name='index.html')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But It's failling to load this files in index.html GET http://localhost:8000/_nuxt/3433182.js net::ERR_ABORTED 404 (Not Found) GET http://localhost:8000/_nuxt/369ee37.js net::ERR_ABORTED 404 (Not Found) GET http://localhost:8000/_nuxt/aad44e2.js net::ERR_ABORTED 404 (Not Found) GET http://localhost:8000/_nuxt/bed9682.js net::ERR_ABORTED 404 (Not Found) GET http://localhost:8000/_nuxt/img/page-background.74b6577.png 404 (Not Found) -
How can I show my images through JsonResponse in Django's view?
I have a question, my collaborator's code works well, it shows some images that were previously uploaded through an input through a modal. The problem is that I want to display the images in a detail view. I modified it and I can only show one of the 10 that were uploaded. How can I show all 10? I have no idea how to handle that JSON he used views.py class detail_carro(DetailView): template_name = 'carros/carros-detail.html' queryset=Carro.objects.all() context_object_name = 'carros' def create_carros_picture(request): if request.FILES['files']: file = request.FILES['files'] fs = FileSystemStorage() # defaults to MEDIA_ROOT new_name = "picture" new_name = fs.get_valid_name(new_name)+".jpg" filename = fs.save(new_name, file) return JsonResponse({filename:file.name},safe=False) else: form=CarroForm() return render(request, "carros/carros-form-add.html",{'form':form}) def create_carros_warranty(request): if request.FILES['files']: file = request.FILES['files'] fs = FileSystemStorage() # defaults to MEDIA_ROOT ext = file.name.split('.')[-1] new_name = "warranty" new_name = fs.get_valid_name(new_name) + '.' + ext filename = fs.save(new_name, file) return JsonResponse({filename: file.name}, safe=False) else: form = CarroForm() return render(request, "carros/carros-form-add.html", {'form': form}) carros-detail.html {% if carros.new_name %} <a data-id="{{carros.id}}" class="btn_view_gallery"> <img src="{% get_media_prefix %}{{carros.new_name}}" height="300"> </a> {% endif %} -
How to create a dynamic form in htmx and Django?
I'm creating a form that sends a request back to Django via POST method using htmx to get the search results without having to reload the page. I have already tried to create a form with Django and htmx but without success. Htmx being new, I can't seem to find solid sources for learning. Every time I submit my form, the page reloads despite me. Here is my source code: <form method="POST" action="search"> ... <input type="search" name="search" hx-post="/search" hx-target="#results" hx-trigger="keyup changed delay:500ms" value="{{form.search.value}}" placeholder="Search here..." autofocus x-webkit-speech/> </form> When the user submits this form, the keywords entered are sent to Django views.py file via the POST method and this is responsible for returning the results. -
Unable to start Django server within Docker container - TypeError: argument of type 'NoneType' is not iterable
So I've created a dev-container within Docker using VSCode's Remote - Container extension. The config looks as follows: devcontainer.json file: // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: // https://github.com/microsoft/vscode-dev-containers/tree/v0.238.0/containers/python-3-postgres // Update the VARIANT arg in docker-compose.yml to pick a Python version { "name": "Python 3 & PostgreSQL", "dockerComposeFile": "docker-compose.yml", "service": "app", "workspaceFolder": "/workspace", // Configure tool-specific properties. "customizations": { // Configure properties specific to VS Code. "vscode": { // Set *default* container specific settings.json values on container create. "settings": { "python.defaultInterpreterPath": "/usr/local/bin/python", "python.linting.enabled": true, "python.linting.pylintEnabled": true, "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8", "python.formatting.blackPath": "/usr/local/py-utils/bin/black", "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf", "python.linting.banditPath": "/usr/local/py-utils/bin/bandit", "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8", "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy", "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle", "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle", "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint", "python.testing.pytestPath": "/usr/local/py-utils/bin/pytest" }, // Add the IDs of extensions you want installed when the container is created. "extensions": [ "ms-python.python", "ms-python.vscode-pylance" ] } }, // Use 'forwardPorts' to make a list of ports inside the container available locally. // This can be used to network with other containers or the host. "forwardPorts": [5000, 5432, 8000], // Use 'postCreateCommand' to run commands after the container is created. "postCreateCommand": "pip install --user poetry" // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. // "remoteUser": "vscode" } docker-compose.yml file: > version: … -
Iterating over a list from an object in Django template
I am trying to iterate over a list that is below an object in a Django template. Unfortunately I am not getting anywhere. This is the object: {'Value1': [8, 5, 4, 7, 4, 5], 'Value2': [], 'Value3': []} I am doing in the template something like: {% for entry in data %} <tr> <td>{{ entry }}</td> <td>{{ entry.0 }}</td> </tr> {% endfor %} or {% for entry in data %} <tr> <td>{{ entry }}</td> {% for i in entry %} <td>{{ i }}</td> {% endfor %} </tr> {% endfor %} But all I am getting is just the first letter of the key. -
Displaying D3.js Chart with Django Backend
I am learning to build dashboard using Django as backend and D3.js for visualization. Following is my index.html: {% load static %} <html> <script src="https://d3js.org/d3.v7.min.js"></script> <body> <h1> Hello! </h1> <script src={% static "js\linechart.js" %}> var data = {{ AAPL|safe }}; var chart = LineChart(data, { x: d => d.date, y: d => d.close, yLabel: "↑ Daily close ($)", width, height: 500, color: "steelblue" }) </script> </body> </html> Data AAPl is extracted from database and the views.py is as follows: from django.shortcuts import render from django.http import HttpResponse from cnxn import mysql_access import pandas as pd # Create your views here. def homepage(request): sql = ''' select Date, Close from tbl_historical_prices where ticker = 'AAPL' ''' cnxn = mysql_access() conn = cnxn.connect() df = pd.read_sql(sql, con=conn) context = {'AAPL':df.to_json()} return render(request, 'index.html', context=context) Function line chart can be viewed here which is being used in js\linechat.js in index.html file. I can see the Hello! being displayed on the page but can't see the line chart. I am unable to debug the problem. No errors found in console tab either. How can I display the line plot? I've added the current page display in attached image. -
How to remove "Unresolved refernce" errror in PyCharm I have changed python interpreter so many times but not working
enter image description here enter image description here enter image description here Guys please help me what should I do? I tried so many times to change the Python Interpreter path also I have reinstalled my python and pycharm but this error is not resolving please help me :( -
Rendering phone numbers in flask jinja2 urlize filter
By using the 'urlize' filter in jinja2 in flask templates; every text website link gets rendered into clickable. But I can't make phone numbers turn <a href='tel:+966850766817'> "phone number" <a/> but they don't render this way. any suggestions? -
django-import-export how to deal with the import_id_fields is unique_together key?
the parentmodel is class Work(models.Model): po = models.ForeignKey(Po, verbose_name="合同号", on_delete=models.CASCADE) remark = models.CharField(max_length=100, verbose_name="备注说明") create_time=models.DateField(verbose_name="日期") class Meta: verbose_name = "工作清单" verbose_name_plural = verbose_name unique_together=("po","remark") def __str__(self): return self.remark and the children model is class Acceptance(models.Model): work = models.ForeignKey(Work, on_delete=models.CASCADE, verbose_name="工作清单") detail=models.ForeignKey(Detail,on_delete=models.CASCADE,verbose_name="验收物品") accecpt_time = models.DateField(verbose_name="验收日期") num = models.IntegerField(verbose_name="验收数量", validators=[MinValueValidator(1)]) person = models.CharField(max_length=100, verbose_name="验收人员") class Meta: verbose_name = "验收清单" verbose_name_plural = verbose_name unique_together=("accecpt_time","work") I want to ask about how to defind the Acceptance Resource when the work foreign_key is unique_together key? my test code is class AcceptanceSource(resources.ModelResource): work = fields.Field(attribute="work", widget=ForeignKeyWidget(Work, 'remark'), column_name="工作清单") detail = fields.Field(attribute="detail", widget=ForeignKeyWidget(Detail, "name"), column_name="物料清单") po = fields.Field(attribute="work__po", column_name="合同号", widget=ForeignKeyWidget(Po, "po_num")) num = fields.Field(attribute="num", column_name="验收数量") accecpt_time = fields.Field(attribute="accecpt_time", column_name="验收时间") person = fields.Field(attribute="person", column_name="验收人员") but it get error like this: 行号: 1 - get() returned more than one Work -- it returned 2! -
How to do simple arithmetic calculator in django template?
I want to show two sets of number from model in the django template for the same. I am using for loop to get each row data of the table to show in template as below : {% for a in vis %} {a.numone} {a.numtwo} {% endfor %} its working fine!. Now, I want to do simple arithmetic calculation by using this numbers. say for example add, sub, div, multiply this two number and show it in template. How to do it? -
unable to post item to database, Django
I have a model called CurrentBestSellersListItem, with an integer field, some CharFields, and a URLField. I also have a serializer for the given model. I am able to create instances of the CurrentBestSellersListItem in the database manually from http://127.0.0.1:8000/admin/lists/currentbestsellerslistitem/add/, i.e. from the admin panel, but am unable to create them on another route. The other route I have (in urls.py) is: path('list-items-create/', views.create_saved_list_item, name='create_saved_list_item'), and the create_saved_list_item function in views.py is: @api_view(['POST']) def create_saved_list_item(request): json_object = json.dumps(request.data, indent = 1) serializer = CurrentBestSellersListItemSerializer(data=json_object) if serializer.is_valid(): serializer.save() return Response(serializer.data) If I go to http://127.0.0.1:8000/api/list-items-create/ and POST the following data: { "rank": 555, "weeks_on_list": 555, "publisher": "a", "description": "b", "title": "c", "author": "d", "amazon_product_url": "amazon.com/books/5" } then I get back this response: HTTP 200 OK Allow: OPTIONS, POST Content-Type: application/json Vary: Accept {} and the item is NOT added to the connected database, as expected. Can any of you spot where the error is? -
Djangochannelsrestframework custom action doesn't work
I want to create custom action like in documentation but it answer that Method doesn't allow Documentation: https://pypi.org/project/djangochannelsrestframework/ "Adding Custom actions" block other websocket urls worked correctly My source code: consumers.py: from games.models import GameLaunchers, GamesCategories, Games, Tournires from news.models import News from games.serializers import GamesCategoriesSerializer, GameLaunchersSerializer, GameSerializer, TourniresSerializer from news.serializers import NewsListSerializer from market.models import MarketCategory, MarketProductsType, MarketProducts, MarketOrders from market.serializers import MarketCategoriesSerializer, MarketProductsTypeSerializer, MarketProductsSerializer, MarketOrdersListSerializer from django.core import serializers from djangochannelsrestframework.settings import api_settings from django.http import Http404 from djangochannelsrestframework.generics import GenericAsyncAPIConsumer from djangochannelsrestframework.consumers import AsyncAPIConsumer from djangochannelsrestframework.decorators import action from djangochannelsrestframework.mixins import ( ListModelMixin, RetrieveModelMixin, PatchModelMixin, UpdateModelMixin, CreateModelMixin, DeleteModelMixin, PaginatedModelListMixin ) class GamesLaunchersAddConsumer( CreateModelMixin, GenericAsyncAPIConsumer, ): serializer_class = GameLaunchersSerializer class GameLaunchersConsumers(GenericAsyncAPIConsumer): queryset = GameLaunchers.objects.all() serializer_class = GameLaunchersSerializer @action async def send_email(self, request_id, some=None, **kwargs): # do something async return {'response_with': 'some message'}, 200 routing.py from django.urls import path from socketapp import consumers # from socketapp.views import GamesViewSet from django.urls import re_path from djangochannelsrestframework.consumers import view_as_consumer # from djangochannelsrestframework.consumers import view_as_consumer # from games.views import GameLaunchersAddView, GameLaunchersView websocket_urlpatterns = [ re_path(r'ws/games/launchers/add', consumers.GamesLaunchersAddConsumer.as_asgi()), re_path(r'ws/games/launchers', consumers.GameLaunchersConsumers.as_asgi()), ] Sending message: { "action": "send_email", "request_id": 42, "some": "value passed as keyword argument to action" } I got this error: { "errors": [ "Method … -
python get KEY from hmac.hexdigest()
I have method getting signature from key: def get_signature(request, key: str): request_str = f'{request.method}\n{request.path}' return hmac.new(key.encode(), request_str.encode(), hashlib.sha256).hexdigest() Let's say we have some request and some key in string format sign = get_signature(request, key) Can I get the KEY from sign? That is, decode and get the original string (key) -
Compiling .less with .png assets with webpack for Django project
I have a folder for .less files that contains an img folder: less | `-- img | `-- good-boy-cleaning.png `-- index.less the contents of index.less: html { body { background-image: url("img/good-boy-cleaning.png"); max-width: image-width("img/good-boy-cleaning.png"); } } As part of a Django project, I would like to compile this into a css file in ./myapp/static/myapp/css/ that references image files in ./myapp/static/myapp/img/. Is this possible? The closest I've gotten is the following webpack.config.js file: const path = require('path'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { entry: { myappcss: "./less/index.less", }, mode: "development", output: { path: path.resolve("./myapp/static/myapp/"), }, plugins: [ new MiniCssExtractPlugin({ filename: 'css/[name].[contenthash].css', }), ], module: { rules: [{ test: /\.(png|jpg)$/, use: [{ loader: "file-loader", options: { name: "[path][name].[ext]", context: path.resolve('./less') } }] }, { test: /\.less$/, use: [{ loader: MiniCssExtractPlugin.loader, options: { publicPath: "../" } }, { loader: "css-loader", options: { // url: false, importLoaders: 1 } }, 'less-loader' ] } ] } } which copies ./less/img/good-boy-cleaning.png to ./myapp/static/myapp/img/good-boy-cleaning.png and creates a css file in ./myapp/static/myapp/css/myappcss.03ee...97.css, however, the content of the css file is: html body { background-image: url(../f2215e467af7ba27555f.png); max-width: 264px; } the referenced png file is created, but it contains only: export default __webpack_public_path__ + "img/good-boy-cleaning.png"; which isn't especially useful. If … -
Django auto save the current user in the model on save
I am trying to save the user automatically when saving new data. It's working if I hard-coded the user-id get(id=2). How can I make the id dynamic? If it's not possible how can I do it in views or serializer without using forms? models.py class Feedback(models.Model): . . author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, editable=False, ) def save(self, *args, **kwargs): self.author = get_user_model().objects.get(id=2) @@@@@@@@@@@@@@@@@ return super().save(*args, **kwargs) -
Getting Error in Heroku when Deploying Django
I'm trying to Deploy the Django backend in Heroku through the GitHub repo (which I have committed in main Branch). I'm getting the following error below when deploying it. -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt ! Python has released a security update! Please consider upgrading to python-3.10.5 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.10.4 -----> Installing pip 22.1.2, setuptools 60.10.0 and wheel 0.37.1 -----> Installing dependencies with Pipenv 2020.11.15 Installing dependencies from Pipfile.lock (79baf8)... Ignoring tzdata: markers 'sys_platform == "win32"' don't match your environment -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_6bcdc97f/manage.py", line 22, in <module> main() File "/tmp/build_6bcdc97f/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/app/.heroku/python/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' ! … -
TypeError: AsyncConsumer.__call__() missing 1 required positional argument: 'send'
consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name= self.scope['url_route']['kwargs']['room_name'] self_room_group_name='chat_%s' % self.room_name await self.channel_layer.group_add ( self.room_group_name, self.channel_name ) await self.accept() await self.channel_layer.group_send( self.room_group_name, { 'type':'tester_message', 'tester':'Hello world', } ) async def tester_message(self,event): tester =event['tester'] await self.send(text_data=json.dumps({ 'tester':tester, })) async def disconnect(self, code_close): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) pass -
How to make query in django serializers many to many objects filter?
Info: I want to filter the candidate by party id Candidates.objects.filter(party_id_in=1).filter(party_id_in=4) How can i pass this queryset in ConstituenciesSerializer. I don't understand where and how i defined and get the candidates by party id. i want to get only two parties candidates in Constituencies serializers. My code is working fine but it is getting all candidates data. Models.py class Party(models.Model): name = models.CharField(max_length=255) class Candidates(models.Model): name = models.CharField(max_length=100, verbose_name=_('English name')) party = models.ForeignKey(Party, on_delete=models.SET_NULL, null=True)) class Constituencies(models.Model): candidates = models.ManyToManyField(Candidates)) serializers.py class PartySerializer(serializers.ModelSerializer): class Meta: model = Party fields = ['name'] class CandidateSerializer(serializers.ModelSerializer): party = PartySerializer(required=False, read_only=True) class Meta: model = Candidates fields = [ 'name', 'party', ] class ConstituenciesSerializer(serializers.ModelSerializer): candidates = CandidateSerializer(many=True) class Meta: model = Constituencies fields = ['candidates'] views.py class CandidateVSRetrive(generics.RetrieveAPIView): queryset = Constituencies.objects.all() serializer_class = ConstituenciesSerializer -
Django REST Framework UniqueTogetherValidator fails with FK from kwargs
I've got myself into a trouble with UniqueTogetherValidator. The problem is that ReviewSerliazer unlike CommentSerializer which is almost identical does unique together validation before actually getting a title value from kwargs and sends back 400 answer with title field being required. I've tried to identify it as a HiddenField, but although serializer validation goes fine within tests, model validation does not. And I receive django.db.utils.IntegrityError: UNIQUE constraint failed: reviews_review.author_id, reviews_review.title_id Any ideas how to fix this without catching exceptions in the viewset, which is obviously wrong? models.py class BasePost(models.Model): text = models.TextField() author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='%(class)ss') pub_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-pub_date', ) abstract = True def __str__(self): return self.text[:30] class Review(BasePost): score = models.IntegerField( default=0, validators=[MaxValueValidator(10), MinValueValidator(1)]) title = models.ForeignKey( Title, on_delete=models.CASCADE, related_name='reviews') class Meta(BasePost.Meta): constraints = [ models.UniqueConstraint( fields=('author', 'title', ), name='unique_title_review')] class Comment(BasePost): review = models.ForeignKey( Review, on_delete=models.CASCADE, related_name='comments') urls.py router_v1.register( r'^titles/(?P<title_id>\d+)/reviews', ReviewViewSet, basename='review') router_v1.register( r'^titles/(?P<title_id>\d+)/reviews/(?P<review_id>\d+)/comments', CommentViewSet, basename='comment') views.py class ReviewViewSet(BasePostViewSet): serializer_class = ReviewSerializer def get_queryset(self): return self.get_title().reviews.all() def perform_create(self, serializer): serializer.save(author=self.request.user, title=self.get_title()) def get_title(self, key='title_id'): return get_object_or_404(Title, id=self.kwargs.get(key)) class CommentViewSet(BasePostViewSet): serializer_class = CommentSerializer def get_queryset(self): return self.get_review().comments.all() def perform_create(self, serializer): serializer.save(author=self.request.user, review=self.get_review()) def get_review(self, key='review_id'): return get_object_or_404(Review, id=self.kwargs.get(key)) serializers.py class ReviewSerializer(BasePostSerializer): title … -
Create a dynamic datatable dashboard with dynamic values in cells
I am actually making a project on python. The goal is to display a dashboard (made of a datatable) on a webpage, in which the datas will evolve really quickly (each 1 to 2 seconds). The datas are received from a rabbitmq. I actually have successfully achieved it with Dash. Everything works well, but I have one major problem. Dash seems to be really slow when we have a huge amount of datas (approximately 300 columns for 5000 rows in my case) that are regularly actualized. As far as I went, I think that the major lack of speed comes from the fact that the values pushed in the datatables are in a dictionary and not dynamic (not an in-cell modification), so all the javascript loads slowly and is not that stable. Which leads me to this question : what would be the best way to achieve the goals mentioned below ? I thought that using Django and creating a custom javascript datatable could do the job but I would like to get some advices and ideas before starting to code that (really) time consuming solution. Thanks to all ! -
AttributeError-module 'urllib.request' has no attribute 'META'
i just started django here is my view from django.shortcuts import render from django.http import HttpResponse from urllib import request def homepage(*args,**kwargs): return render(request,'home.html') # Create your views here. def requestpage(*args,**kwargs): return render(request,'req.html') which givesenter image description here -
Django - OpenCV Display output in HTML
So I make an attendance system with face recognition on Django. Right now my code will open up the python window, detect face and record name, date and time on CSV file. I want to display name, time and date on the HTML once the face is detected. How can I do that?. views.py from django.shortcuts import render import cv2 import numpy as np import face_recognition import os from datetime import datetime from django.core.files import File from django.template.loader import render_to_string path = 'attendancesystem/file/faces' images = [] className = [] imgList = os.listdir(path) print(imgList) #read image from images folder for cl in imgList: curImg = cv2.imread(f'{path}/{cl}') images.append(curImg) className.append(os.path.splitext(cl)[0]) print(className) This is the function to mark the attendance once the face is detected. #mark attendance function def markAttendance(name): with open('attendancesystem/static/attendancesystem/Attendance.csv', 'r+') as f: attendList = f.readlines() nameList = [] for line in attendList: entry = line.split(',') nameList.append(entry[0]) if name not in nameList: now = datetime.now() dateString = now.strftime('%d/%m/%Y') timeString = now.strftime('%H:%M:%S') f.writelines(f'\n{name},{dateString},{timeString}') This is the function to encode the image that is inserted in the faces folder. #encode image def findEncoding(images): encodeList = [] for img in images: img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) encode = face_recognition.face_encodings(img)[0] encodeList.append(encode) return encodeList encodeListKnown = findEncoding(images) print("Encoding Complete") …