Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
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_{{ …