Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM multiple chained JOIN equivalent and aggregation
Given the following Django models (lots shown just as an example, could be more or less nested): class ModelA(models.Model): value = models.IntegerField() class ModelB(models.Model): modelA = models.ForeignKey(ModelA, on_delete=models.CASCADE) value = models.IntegerField() class ModelC(models.Model): modelB = models.ForeignKey(ModelB, on_delete=models.CASCADE) value = models.IntegerField() class ModelD(models.Model): modelC = models.ForeignKey(ModelC, on_delete=models.CASCADE) value = models.IntegerField() class ModelE(models.Model): modelD = models.ForeignKey(ModelD, on_delete=models.CASCADE) value = models.IntegerField() # etc... How can we use the Django ORM to do the following operations: e.g. all ModelE for a given modelA, SQL equivalent: SELECT ModelE.* FROM ModelA JOIN ModelB ON ModelB.modelA = ModelA.id JOIN ModelC ON ModelC.modelB = ModelB.id JOIN ModelD ON ModelD.modelC = ModelC.id JOIN ModelE ON ModelE.modelD = ModelD.id WHERE ModelA.id = 1 e.g. group all records by some model, SQL equivalent: SELECT ModelC.*, SUM(ModelE.value) FROM ModelA JOIN ModelB ON ModelB.modelA = ModelA.id JOIN ModelC ON ModelC.modelB = ModelB.id JOIN ModelD ON ModelD.modelC = ModelC.id JOIN ModelE ON ModelE.modelD = ModelD.id WHERE ModelA.id = 1 GROUP BY ModelC.id The specific query I'm trying to get is equivalent to the following: SELECT ModelC.value * SUM(ModelE.value) FROM ModelA JOIN ModelB ON ModelB.modelA = ModelA.id JOIN ModelC ON ModelC.modelB = ModelB.id JOIN ModelD ON ModelD.modelC = ModelC.id WHERE ModelA.id = 1 AND ModelD.value … -
How to make django form.errors display only error and not input field affected
Basically, what i am trying to achieve is to remove the name of the input field which in this case is tel and display only the error message using {{ form.errors }} -
AJAX request returns HTML file instead of data. ( Django & Python )
I have a profile page with user posts. People can like/dislike the posts. It works well but it reloads the page, that is why I am implementing AJAX. The route goes like this. Inside the profile view is the "like POST" request ending with a data = { 'likes':post.likes.all().count() } return JsonResponse(data,safe=False)" When clicking on the like button, I can see the data on a blank page if I want to. So I know it is receiving it. Unfortunately, when using AJAX, instead of returning the data. it returns the profile view's return render(request, "profile.html", context) Here is my AJAX code const post_id = $(this).attr('id') const likeText = $( `.like_button${post_id} `).attr('name') const trim = $.trim(likeText) const url = $(this).attr('action') let res; const likes = $(`.like_count${post_id}`).text() || 0 const trimCount = parseInt(likes) $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), 'post_id':post_id, }, success: function(data){ console.log('success', data) }, error: function(data){ console.log('error', data) } }) Any help would be much appreciated. First time using AJAX, so as much details would be appreciated. -
Django Filtering between dates
I am creating a filter in heatmap where the filter will only extract the date from and to date transaction only. I am not sure with the codes on the filter date but I have not received an error, It only goes top of the page. My HTML for date is MM/DD/YYYY. I am not sure if it helps. But how can I embed filter between dates? Thank you Views def index_map(request): if request.method == "POST": fromdate = request.POST.get('fromdate') todate = request.POST.get('todate') df = pd.DataFrame(IncidentGeneral.objects.filter(user_report__date__date__range=(fromdate, todate)).values('user_report__latitude', 'user_report__longitude', 'accident_factor')) print(df) # coordenadas = list(IncidentGeneral.objects.values_list('user_report__latitude','user_report__longitude'))[-1] map1 = folium.Map(location=[14.676208, 121.043861], zoom_start=12, ) # df = df.dropna(axis=0, subset=['user_report__latitude', 'user_report__longitude', 'accident_factor', 'user_report__date']) # mapquestopen fg3=folium.FeatureGroup(name='Map with Markers', show=True) map1.add_child(fg3) # marker_cluster = MarkerCluster().add_to(fg) folium.TileLayer(('openstreetmap'), attr='openstreetmap').add_to(map1) # folium.TileLayer('mapquestopen', attr='mapquestopen').add_to(map1) # folium.TileLayer('MapQuest Open Aerial', attr='MapQuest Open Aerial').add_to(map1) folium.TileLayer('cartodbpositron', attr='cartodbpositron').add_to(map1) folium.TileLayer('cartodbdark_matter', attr='cartodbdark_matter').add_to(map1) plugins.Fullscreen(position='topright').add_to(map1) folium.LayerControl().add_to(map1) for id,row in df.iterrows(): folium.Marker(location=[row['user_report__latitude'],row['user_report__longitude']], icon=folium.Icon(icon="car", prefix='fa') ,popup=row['accident_factor']).add_to(fg3) # folium.Marker(coordenadas).add_to(map1) # df['user_report__date'] = df['user_report__date'].sort_values(ascending=True) # data = [] # for _, d in df.groupby('user_report__date'): # data.append([[row['user_report__latitude'], row['user_report__longitude'], row['accident_factor']] for _, row in d.iterrows()]) map1 = map1._repr_html_() context = { 'map1': map1 } return render(request, 'index1.html', context) Views class UserReport(models.Model): PENDING = 1 APPROVED = 2 REJECTED = 3 STATUS = ( (PENDING, 'Pending'), (APPROVED, … -
Invalid block tag on line 4: 'endblock'. Did you forget to register or load this tag?
I am getting an error Invalid block tag on line : 'endblock. Did you forget to register or load this tag? {% extends 'main/base.html' %} {% block title %} Home {% endblock %} {% block content %} <h1>Home Page</h1> {% endblock %} #This is tag that the error is referring to This is my base.html in which it inherits from <html> <head> <title>{% block title %} My Site {% endblock %}</title> </head> <body> <div id="content" , name="content">{% block content %}{% endblock %}</div> </body> </html> -
Adding an extra field in a forms.ModelForm
I am trying to create a modelForm in django, however when i try to add an extra field, i get a field error: django.core.exceptions.FieldError: Unknown field(s) (select_file_path) specified for ProjectFile My form is as follows: class ProjectFileForm(forms.ModelForm): select_file_path = forms.Select() class Meta: model = ProjectFile fields = ["project", "form_type", "select_file_path", "file_name", "full_file_path", "author"] widgets = {"author": HiddenInput()} field_order = ["project", "form_type", "select_file_path", "file_name", "full_file_path"] Not too sure whats going wrong here as a model form is defined the same way in the docs: https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#overriding-the-default-fields -
Problem with Back-end DB connection: React + Django + MySQL setup with Docker
I am trying to configure a docker-compose for this stack setup. I am having trouble understanding the whole volume principle and thus made a lot of trial and error. I would like to make my database persistent, of course. I would also very much want my Django container to connect to the MySQL DB. Thank you in advance for your answers. Currently, my docker-compose.yml looks like this: version: '3.8' name: scout services: front-end: container_name: front-end build: context: front-end dockerfile: Dockerfile command: npx serve build restart: always environment: NODE_ENV: production expose: - 3000 ports: - 3000:3000 db: container_name: db image: mysql:latest restart: always env_file: - .env back-end: container_name: back-end build: context: back-end dockerfile: Dockerfile command: python3 manage.py runserver 0.0.0.0:8000 restart: always env_file: - .env expose: - 8000 ports: - 8000:8000 depends_on: - db My .env file: MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_ROOT_HOST=% MYSQL_DATABASE=scout_db MYSQL_USER=guillaume MYSQL_PASSWORD=password MYSQL_ROOT_PASSWORD=password My Back-end Dockerfile: FROM python:3.10 ENV BACKEND_HOME /home/app/back-end RUN mkdir -p $BACKEND_HOME WORKDIR $BACKEND_HOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY . ./ EXPOSE 8000 RUN python3 -m pip install --upgrade pip RUN pip install -r requirements.txt And within my settings.py in the Django setup, the DATABASES variable is the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', … -
Why am I receiving KeyError: 'django' when running python manage.py runserver
I get an error when I try to start my server. I'm using Django in a virtual environment. I've spent hours searching for this & can't find an answer Here is the error that I received: Traceback (most recent call last): File "C:\Users\jaiso\.virtualenvs\storefront2-4TwSyq5h\lib\site-packages\django\template\utils.py", line 69, in __getitem__ return self._engines[alias] KeyError: 'django' Here is my installed packages: Package Version asgiref 3.5.2 Django 4.1.2 django-debug-toolbar 3.7.0 django-rest-framework 0.1.0 djangorestframework 3.14.0 drf-nested-routers 0.93.4 mysqlclient 2.1.1 pip 22.2.2 Python-Rest-Framework 0.3.14 pytz 2022.4 setuptools 65.3.0 six 1.16.0 sqlparse 0.4.3 tzdata 2022.4 wheel 0.37.1 -
how to build a get_absolute_url with year, month, day and slug on Djano Rest Framework
I'm building a blog aplication with DRF, and I want it to be able to get my get_absolute_url method for wach post, like: http://127.0.0.1:8001/blog/posts/2022/10/11/my-post And not the default: http://127.0.0.1:8001/blog/posts/1 Here's my model: class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.SlugField(unique_for_date='publish', max_length=250) body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts') publish = models.DateTimeField(default=timezone.now) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') category = models.ForeignKey(Category, on_delete=models.SET_NULL, related_name="posts" ,blank=True, null=True ) objects = models.Manager() published = PublishedManager() tags = TaggableManager() feature_image = models.ImageField(upload_to="uploads/", null=True, blank=True) class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug], ) And my serializer: class BlogSerializer(serializers.HyperlinkedModelSerializer): author = serializers.ReadOnlyField(source='author.username') url = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Post fields = ['url', 'id', 'title', 'slug', 'body', 'author', 'publish', 'created_at', 'updated_at', 'status', 'category', 'feature_image'] Somebody help how to do that, please. thanks! -
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.