Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Embedding multiple RTSP ip cameras on django page
I am hitting a roadblock trying to convert and embed a RTSP address to a django template. I have a working dashboard but have not implemented anything regarding RTSP as I have not come across any helpful information. I have seen solutions using HTML and Javascript and some django projects on github but most are unfinished or outdated and not working. If anyone can direct me one how to do this using a view model container type setup that would be very much appreciated. -
Django Channels: Event loop is closing when using thread
I want to show a countdown and then later start a game loop. The code is getting excuted and the messages are send but i always get a RuntimeError. I would be interested in a fix or a maybe better solution that i can apply. I was also thinking about splitting things into two Consumers but i dont know how this would fix this. Thanks in advance. This error message is popping up multiple times. Task exception was never retrieved future: <Task finished name='Task-60' coro=<Connection.disconnect() done, defined at D:\Programming\Fullstack\geogame\geogame_backend\env\lib\site-packages\redis\asyncio\connection.py:819> exception=RuntimeError('Event loop is closed')> Traceback (most recent call last): File "D:\Programming\Fullstack\geogame\geogame_backend\env\lib\site-packages\redis\asyncio\connection.py", line 828, in disconnect self._writer.close() # type: ignore[union-attr] File "C:\Program Files\Python310\lib\asyncio\streams.py", line 337, in close return self._transport.close() File "C:\Program Files\Python310\lib\asyncio\selector_events.py", line 698, in close self._loop.call_soon(self._call_connection_lost, None) File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 753, in call_soon self._check_closed() File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 515, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed This is my consumer class LobbyConsumer(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.players = None self.game_finished = None self.host = None self.user = None self.lobby_code = None self.lobby_group_code = None self.lobby = None def connect(self): self.lobby_code = self.scope['url_route']['kwargs']['lobby_code'] if Lobby.objects.filter(code=self.lobby_code).exists(): self.lobby = Lobby.objects.get(code=self.lobby_code) else: print("DOESNT EXIST") self.accept() self.send(json.dumps({"type": "error", … -
Django: Popup for FK CRUD form inside another form
I'm learning Django, so I'm trying to create a mini-app for practice. I've 2 tables on DB: By one side webapp_domicilio, where is a PK for the ID and some varchars for address info. By the other side, webapp_persona, where is a PK for the ID, some varchars for person info and a FK referencing the address ID (webapp_domicilio.id) I created the webpage for adding new item to webapp_persona, inheriting ModelForm and now I want to add the option to create, edit and delete an address without exiting this page, just like the Django Admin page. Searching on stackoverflow I found this article: Creating front-end forms like in Django Admin but the accepted answer get me to a 404 page on Django documentation. Then I tried what's in https://django-addanother.readthedocs.io/en/latest/index.html and I managed to insert the 'add' button but it doesn't open in a popup using CreatePopupMixin from django_addanother.views. There is a point where they explain how to make the view popup compatible but I don't really understand it. I also tried to insert the 'edit' button but it doesn't work neither. I let my code here: views.py: def nueva_persona(request): if request.method == 'POST': formulario_persona = PersonaForm(request.POST) if formulario_persona.is_valid(): formulario_persona.save() return … -
How to exclude empty values when querying a DRF endpoint [Django]
Similar to an exclude filter that looks like this: MyObject.objects.exclude(my_field="") So something like this: /api/object?my_field__isempty=False I know that I can modify the view to exclude the value in the queryset: def get_queryset(self): return Client.objects.exclude(my_field="") -
How to work with Django media files in data attribute of <object> html tag?
I'm trying to embed svg file in Django template. It works fine with file from static folder. Exmaple: <object id="external_svg_map" data="{% static 'svg/plan.svg' %}" width="900" height="900"> </object> But when I'm trying to use files from media folder, object doesn't show anything. <object id="external_svg_map" data="{{map.svg_map_file.url}}" width="900" height="900"> </object> In the same time, it works great with img tag. <img src="{{ map.svg_map_file.url }}" alt=""> What I do wrong? -
App Insights in Django OpencensusMiddleware issue '_is_coroutine'
I am trying to use Azure App Insights for my Django application. I have followed the tutorial here: https://learn.microsoft.com/en-us/azure/azure-monitor/app/opencensus-python-request So far, I have only added the middleware and the OPENCENSUS change to my settings.py file in the app. I installed all necessary dependencies, including the asgiref package that was recommended in a similar post. I am getting the following error: 'OpencensusMiddleware' object has no attribute '_is_coroutine' I don't have anything else to work off and it does not seem like this is a common problem. Has anyone encountered it before or knows more about App Insights than I do? Thanks in advance! -
django queryset. How do i set a columns null value to bool false
i'm using a model based on a table view. When returned some column is off course null. But i want to assign all empty/null to bool value False. Maybe there is another django way to assign all null/none to a bool False for a var used in filter view.py rows = Vbase.objects.all().values(*db_sel_columns) rows_filter = baseFilter(request.GET, queryset=rows) models.py inRU = models.CharField(_("inRU"), blank=False, null=False, max_length=10) filters.py inRU = django_filters.CharFilter(lookup_expr='iregex', label='', widget=forms.Select(attrs={'onchange': 'this.form.submit();','color': 'navy','class': 'form-select'},choices=CHOICES_trueFalse)) When selecting in my template i can fine chose true, false, any. But i need to make all "none" to false. can you help on this? Thanks -
django structure: what is the best (large app or many little apps Django)
Hello I hope my question is clear because I am absolute beginner Suppose that I want to make a site that includes different commercial sectors such as shops and laboratories, and all sectors are separate from the other, but they are linked to each other when I want to get profit only. Is it good to put them in one application or in separate applications and make links between them to get profit, knowing that in this case The number of tables will be quite large -
Sankey chart in plotly: need to arrange my nodes as columns. Is this possible without messing with x and y?
Could someone with knowledge of Sankey-charts please help? I am creating a sankey-chart that has nodes of 4 different categories. I need the 1st group of nodes to be displayed on the left one under another, then the 2nd group should be to the right, etc. This actually works like a charm out of the box, but ONLY if my nodes are interconnected in such a way that a line can be drawn to trace links from node-of-category1 -- > to node-of-category2 --> to node of category3 --> to node of category 4. Unfortunately it's not always the case with my data. Some of the connections are "shorter" and include only 2 or 3 nodes. What happens as a result is that if there's no link between some node from 3rd-column & node from 4th-column, that node is shifted to the very right , and becomes aligned to 4th column. I tried different things and found that I could accomplish it with providing x and y coordinates for each node. That's fine, but i feel that my implementation of this will be messy, because the underlying data is different each time, hence i need to do a lot work to … -
No module named 'blog.slugs'
I am trying to create a blog website.but when i try to import generate_unique_slug from .slugs django throws an error No module named 'blog.slugs'. can you help me fix this? models.py from django.db import models from user_profile.models import User from django.utils.text import slugify from ckeditor.fields import RichTextField from .slugs import generate_unique_slug # Create your models here. class Category(models.Model): title = models.CharField(max_length=150, unique=True) slug = models.SlugField(null=True, blank=True) created_date = models.DateField(auto_now_add=True) def __str__(self) -> str: return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Blog(models.Model): user = models.ForeignKey( User, related_name='user_blogs', on_delete=models.CASCADE ) category = models.ForeignKey( Category, related_name='category_blogs', on_delete=models.CASCADE ) title = models.CharField( max_length=250 ) slug = models.SlugField(null=True, blank=True) banner = models.ImageField(upload_to='blog_banners') description = RichTextField() created_date = models.DateField(auto_now_add=True) def __str__(self) -> str: return self.title def save(self, *args, **kwargs): updating = self.pk is not None if updating: self.slug = generate_unique_slug(self, self.title, update=True) super().save(*args, **kwargs) else: self.slug = generate_unique_slug(self, self.title) super().save(*args, **kwargs) admin.py from django.contrib import admin from .models import * # Register your models here. admin.site.register(Category) admin.site.register(Blog) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'user_profile', 'ckeditor', ] when i delete this code from .slugs import generate_unique_slug the error disappears.maybe I'm importing it wrong?I will be very grateful … -
django add public key to image url
this is my setting.py in Django AWS_STORAGE_BUCKET_NAME="test" AWS_S3_ENDPOINT_URL="https://eu2.contabostorage.com/" and it works fine when uploading an image but when I click on the image it gives me error {"message":"Unauthorized"} https://eu2.contabostorage.com/test/public/Forde/front2.png that means I must add the key to the link to be like this https://eu2.contabostorage.com/757f09dfdc5ss4ff8a61360:test/public/Forde/front2.png I tried to add it to the endpoint but give an error so how can I add the key to the URL? -
Django form. Why is my queryset showing undefined even though my model is linked in the meta?
I'm attempting to change the way the many to many selections on my Django form is displayed. I attempted to follow this guide. https://medium.com/swlh/django-forms-for-many-to-many-fields-d977dec4b024. The code I am attempting to recreate is below. class CreateMealForm(forms.ModelForm): class Meta: model = Meal fields = [‘name’, ‘date’, ‘members’] name = forms.CharField() date = forms.DateInput() members = forms.ModelMultipleChoiceField( queryset=Member.objects.all(), widget=forms.CheckboxSelectMultiple ) However when I recreate this I get the error that "users" is not defined. The code I am using is below. from dataclasses import fields from django import forms from boat.models import Mission from .models import Sortie class FinalSortie(forms.ModelForm): class Meta: model = Sortie fields = ['start_date', 'start_time', 'end_time', 'notable_events', 'server_name', 'server_pass', 'mission', 'Sortie_name', 'users'] user = forms.ModelMultipleChoiceField( queryset=users.objects.all(), widget=forms.CheckboxSelectMultiple) I have attempted to Google, YouTube, and Stack overflow search but I am not sure what I am doing wrong. Any guidance or help would be greatly appreciated. EDIT: attaching error NameError: name 'users' is not defined -
Django - Merge jsonfield's new data with the old data
So let's assume that I have a model with a jsonfield while using Postgres as a database class Baum(models.Model): myjson = models.JSONField(...) Now I'd like to know what would be the best way to edit the model fields saving behaviour/interaction with the database myjson stores nested api responses, so dicts&lists When new data comes into myjson, dont delete/overwrite the old by calling save() -> Instead keep the old data and just add the new data, (if a func which proves that the data is new returns True) I need the merged data together, in one myjson field. I am thankful for tips! -
aioredis.errors.ConnectionClosedError: Reader at end of file in heroku
2022-10-12T15:16:02.498083+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/aioredis/commands/sorted_set.py", line 306, in zremrangebyscore 2022-10-12T15:16:02.498083+00:00 app[web.1]: return self.execute(b'ZREMRANGEBYSCORE', key, min, max) 2022-10-12T15:16:02.498083+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/aioredis/commands/init.py", line 51, in execute 2022-10-12T15:16:02.498083+00:00 app[web.1]: return self._pool_or_conn.execute(command, *args, **kwargs) 2022-10-12T15:16:02.498084+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/aioredis/connection.py", line 322, in execute 2022-10-12T15:16:02.498084+00:00 app[web.1]: raise ConnectionClosedError(msg) 2022-10-12T15:16:02.498084+00:00 app[web.1]: aioredis.errors.ConnectionClosedError: Reader at end of file 2022-10-12T15:16:02.499275+00:00 app[web.1]: 10.1.93.215:32430 - - [12/Oct/2022:11:16:02] "POST /api/stripe/webhook" 500 134013 I am using python3.6, django 2.2, channels 2.4 -
My css styling cannot be found when ran locally
I am trying to link my html to the corresponding css styling in file style.css. <link rel="stylesheet" type="text/css" href="style.css"> Both the html file and the css file are in the same folder, however, if I launch my server and show the web page I keep getting this error: Not Found: /style.css "GET /style.css HTTP/1.1" 404 2272 Opening the file from the file directory as a web page, it works fine. It only gets this error when I try launch the server page using django framework. Any idea how to fix this? -
Can't I open django admin panel in pydroid 3
I tried it for a whole day.But it's not opening Django admin panel.I use android as os and pydroid 3 as IDE. -
How to create a custom ordered list in python?
Lets say 3 users have 2 tweets a piece. There usernames are @red, @blue, @yellow. The current list looks like tweets = ["@red", "@red", "@blue", "@yellow", "@yellow", "@blue"] But I want the order to be: tweets = ["@red", "@blue", "@yellow", "@red", "@blue", "@yellow"] my current method was to loop through Users and append a list with their image, like: total_images = len(images) list = [] i = 0 while i < total_images: for user in users: if user.tweet: list.append(user.tweet) i += 1 but thats not working. Thank you! -
Issues with Rendering Python Script in Django
Here are two functions I have in my views.py function in Django. def test(): return "Hello World" def HelloWorld(request): return render(request, test()) This should correctly render the python script in django, however I get this error: TemplateDoesNotExist. I'm not sure what's wrong here. -
AttributeError: 'Service' object has no attribute 'total_views'
I'm putting a ManyToManyField with a related_name and when I make queries it just doesn't recognize the related_name. I even tried without the related_name and it didn't work anyway. The model: from ipadresses.models import UsersIpAddresses class Service(models.Model): title = models.CharField(max_length=50, unique=True, blank=False, null=False) slug = models.SlugField(editable=False, unique=True, blank=False, null=False) description = models.TextField(max_length=200, blank=False, null=False) main_image = models.CharField(max_length=200, blank=False, null=False) url = models.CharField(max_length=500, editable=False, unique=True, blank=False, null=False) ip_addresses_views = models.ManyToManyField(to=UsersIpAddresses, related_name="total_views",) def __str__(self): return self.title def save(self, *args, **kwargs) -> None: self.slug = slugify(self.title) self.url = f"/{self.slug}" self.main_image = f"img/{self.main_image}" return super().save(*args, **kwargs) The view: class ServicesRetrieveView(RetrieveAPIView): serializer_class = ServiceSerializer def get_queryset(self, slug): try: return Service.objects.get(slug=slug) except ObjectDoesNotExist: raise Http404 def get(self, request, slug): serializer = self.serializer_class(self.get_queryset(slug=slug), many=False).data serializer["products"] = ProductSerializer(self.get_queryset(slug=slug).product_set.all()[::-1], many=True).data if request.user.is_authenticated: for product in serializer["products"]: product["message_for_queries"] = Product.message_for_queries(user_name=request.user.username, product_name=product["title"]) try: # UsersIpAddresses.objects.get(request.META["REMOTE_ADDR"]) query_set = self.get_queryset(slug=slug) query_set.total_views.get(ip = request.META["REMOTE_ADDR"]) except ObjectDoesNotExist: # UsersIpAddresses.objects.create(ip = request.META["REMOTE_ADDR"]) ip = None try: ip = UsersIpAddresses.objects.get(request.META["REMOTE_ADDR"]) except ObjectDoesNotExist: ip = UsersIpAddresses(ip=request.META["REMOTE_ADDR"]) ip.save() self.get_queryset(slug=slug).total_views.add(ip) print(len(self.get_queryset(slug=slug).total_views.all())) return Response(data=serializer, status=200) the exception: AttributeError at /services/diseno-grafico/ 'Service' object has no attribute 'total_views' I really don't get why this is happenig. -
HTMX and collapse div, laggy transition
I have built an item hierarchy, that renders out all items, subitems, subitem subitems and so on when the parent item button is clicked. I have used htmx for this and it seems to work quite well. At least gets the job done. My desired end result would be to be able to build as large hierarchy as the user wants to and which would still look good and feel great great to navigate in. Now it is pretty much ruined with the poor transition. What I would like to fix is the transition of the collapse container that subitem is rendered to. Now it works only when collapsing but not when expanding. I guess rendering the data messes it up and when the container expands, it just pops in without any transition. Once the data is there, collapse and expand works as should and the transition is smooth. Here is the code: {% if items %} <ul class="list-group list-group-flush mt-3" id="items-list-group"> <li class="list-group-item items-list-item"> {% for item in items %} <button class="nav-link btn items-list-button" data-toggle="collapse" data-target="#collapse_{{ items.id }}" hx-get="/items/subitems-list/item={{ items.id }}" hx-target="#subitems-list_{{ items.id }}" hx-swat="innerHTML">{{ items.order }} {{ items.name }}</button> <div class="collapse" id="collapse_{{ items.id }}"> <div class="container-fluid subitems-container" id="subitems-list_{{ … -
django Procfile for heroku deployment using gunicorn
According to this documentation, the Procfile format is <process type>: <command> For example: web: gunicorn djforms.wsgi --log-file - However, I found a Django project where the Procfile was missing : after web. i.e. web gunicorn djforms.wsgi --log-file - It also worked correctly when I tried to deploy to heroku. Any Idea on why it works or issues it may cause? Any help will be appreciated! -
Django - How to add extra fields to User model?
I need to add new fields to the " real Django User model ". Why? Because I have two forms in my template with post methods in two different pages. And I created two models, each one saves the corresponding form data in the database. In my views I had to write two different functions for the forms pages. The 1st one: when there is a post request, it saves the data in the 1st Model. The 2nd one: Does the same as 1st but it saves the data in the 2nd Model. I tried to create another new model3 which contains model1 + model2 fields (Didn't delete the previous models)! But when I submit the 1st form it saves data in an object, and when I submit the 2nd form data in another new object of model3 ! So I canceled this method and now I have to try another way to do the task, So I saved the 1st form data ( which are a login info ( email, pass ) and when a user submits the form, it creates a new user with user = User.objects.create_user(request.POST.get("email"),request.POST.get("email"),password) That worked fine, and now I can modify the credentials in … -
django-taggit get number of posts that use a particular tag
What I want to do is to get the number of posts for a particular tag, kind of like how Instagram and Twitter do, I found some solutions this and this. I want to clarify if this is the only way to achieve what I want. Wouldn't it be bad to calculate the number of posts every time someone tries to access a tag? So, I created a custom tag by following these instructions, and have added a num_posts field. class Hashtag(TagBase): num_posts = models.IntegerField(default=0, blank=False, null=False) class Meta: verbose_name = _("Tag") verbose_name_plural = _("Tags") So, how do I increase the num_posts value whenever a new post uses this tag? Or when a post creates a new tag, automatically assign the value of 1 to num_posts. I tried to look into the source code of django-taggit, specifically the TaggableManager, to see if I can override something there and get the intended results. So far I was not able to do anything. Can someone please give me some assistance? -
Chart.js- Dates not displaying correctly on chart and axis labels not showing
I'm trying to label my axes on my chart. I'm using chart.js v3.9.1 and I believe I've followed the documentation, however the labels aren't showing up (see below): health_hub_tracker.html: {% extends 'base.html' %} {% load static %} {% block content %} <h1>Weight Tracker</h1> <canvas id="myChart" width="400" height="200"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: [{%for stat in date%}{{stat}},{%endfor%}], datasets: [{ label: 'Weight (lbs)', data: [{%for stat in weight%}{{stat}},{%endfor%}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { x: { title: { display: true, Text: 'Date' } }, y: { beginAtZero: true, title: { display: true, Text: 'Weight (lbs)' } } } } }); </script> {% endblock content %} views.py: def health_hub_tracker(request): serialized_weight = [] serialized_date = [] for stats in HealthStats.objects.filter(user=request.user): serialized_weight.append(int( stats.weight, )) date_only = stats.date.date() serialized_date.append(str( date_only )) print(serialized_weight) print(serialized_date) context = { "weight": serialized_weight, "date": … -
Trying to deploy Django app on Elastic Beanstalk: "process docker is not registered"
Trying to deploy a Django app to Elastic Beanstalk. I'm using the "Docker running on 64bit Amazon Linux 2" platform and the EB CLI. My configuration is: Dockerfile docker-compose.yml, configuring both the Django app and the NGinx server When I run eb deploy, the process runs and the environment health check is green, but nothing is actually deployed. So, when I go see the eb-engine logs, this is the error I see: [INFO] Running command /bin/sh -c systemctl show -p PartOf docker.service [ERROR] An error occurred during execution of command [env-launch] - [Start Docker]. Stop running the command. Error: startProcess Failure: process "docker" is not registered I searched online for a few hours but was unable to find a hint as to what might be wrong 😟 Files The Dockerfile is in charge of compiling static assets: # Dockerfile ARG PYTHON_VERSION=3.10-slim-buster # STAGE 1: Compile static assets # ---------------------------- FROM node:17-slim as client-builder ARG APP_HOME=/code WORKDIR ${APP_HOME} COPY . ${APP_HOME} RUN npm install && npm cache clean --force # STAGE 2: Add python dependencies # ---------------------------- FROM python:${PYTHON_VERSION} as python-build-stage ARG APP_HOME=/code \ USERNAME=pages ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ POETRY_NO_INTERACTION=1 \ POETRY_VIRTUALENVS_CREATE=false \ POETRY_CACHE_DIR="/var/cache/pypoetry" \ POETRY_HOME="/usr/local" RUN mkdir ${APP_HOME} && …