Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot import from or debug models.py
I've created 5 classes in a models.py inside my app city. I successfully created a db in postgres by importing each class inside the console accordingly. Next, I created a jobs.py script inside the city app so I can automatically scrape data using bs4 and populate/update a db accordingly. The problem occurs when I try to import each class from models.py at the top of my jobs.py script: from city.models import restaurants, barbers, apartments, bars, parks Generates: 'Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.' Any idea why I'm unable to import the classes from models.py into the jobs.py script? I also created a python package utils inside my project. Inside utils is a name_directory.py script that I'm also unable to import into my jobs.py script. Also, I just tried debugging my models.py file and it generated the same error! -
How to deploy tailwind flowbite and django application on Heroku server
I'm a tailwind CSS fanatic and a Django developer. On my own system, I was able to successfully install flowbite using django. On my local system, I ran correctly, however when I launched to a Heroku server, nothing happened. On the internet, I was unable to locate a useful tutorial on how to do it. Would you kindly direct me to a blog post or instructional video that describes how to host a Django and Flowbite application on a development server like Heroku? -
Django / How to refer to a specific news in views so that it is possible to leave a comment on the site through the form?
When submitting a form on the site, the "news_id" value is not pulled into the database (into the table with comments). Accordingly, it is not clear to which news a comment was left so that it could be published later. There are Russian symbols in the code, but they do not affect the essence of the problem in any way. models: class News(models.Model): title = models.CharField(max_length=255, verbose_name="Заголовок") slug = models.CharField(max_length=255, unique=True, db_index=True, verbose_name="URL") content = models.TextField(verbose_name="Содержимое") photo = models.ImageField(upload_to="news/%Y/%m/%d/", verbose_name="Изображение") video = models.URLField(max_length=255, blank=True, null=True, verbose_name="Ссылка на видео") time_update = models.DateTimeField(auto_now=True, verbose_name="Время изменения") category = models.ForeignKey("NewsCategories", on_delete=models.PROTECT, verbose_name="Категория") def __str__(self): return self.title def get_absolute_url(self): return reverse("show_news", kwargs={"news_slug": self.slug}) class Meta: verbose_name = "Новость" verbose_name_plural = "Новости" ordering = ["-time_update"] class Comments(models.Model): news = models.ForeignKey( News, on_delete=models.CASCADE, related_name='comments_news', verbose_name="Новость" ) user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Автор комментария") time_create = models.DateTimeField(auto_now_add=True, verbose_name="Время создания") content = models.TextField(verbose_name="Содержимое") status = models.BooleanField(verbose_name="Публикация комментария", default=False) def __str__(self): return self.content class Meta: verbose_name = "Комментарий" verbose_name_plural = "Комментарии" ordering = ["-time_create"] forms: class CommentForm(forms.ModelForm): content = forms.CharField( label='Добавить комментарий', widget=forms.Textarea(attrs={'rows': '4', 'class': 'form-control'})) class Meta: model = Comments fields = ['content'] utils: class DataMixin: def get_user_context(self, **kwargs): context = kwargs cats = NewsCategories.objects.annotate(Count('news')) context["cats"] = cats if "category_selected" … -
I can't get the posts to be in the position I want
<!DOCTYPE html> <!-- Created by CodingLab |www.youtube.com/CodingLabYT--> <html lang="en" dir="ltr"> {% load static %} <head> <meta charset="UTF-8"> <title>EBOT Maintenance </title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- Boxiocns CDN Link --> <link href='https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div class="sidebar close"> <div class="logo-details"> <i class='bx bx-menu'></i> <span class="logo_name">EBOT</span> </div> <ul class="nav-links"> <li> <a href="{% url 'home' %}"> <i class='bx bx-grid-alt' ></i> <span class="link_name">Anasayfa</span> </a> <ul class="sub-menu blank"> <li><a class="link_name" href="{% url 'home' %}">Anasayfa</a></li> </ul> </li> <li> <div class="iocn-link"> <a href="{% url 'userSettings' %}"> <i class='bx bx-collection' ></i> <span class="link_name">Kullanıcı Ayarları</span> </a> <i class='bx bxs-chevron-down arrow' ></i> </div> <ul class="sub-menu"> <li><a class="link_name" href="{% url 'userSettings' %}">Kullanıcı Ayarları</a></li> <li><a href="{% url 'register' %}">Kullanıcı Ekle</a></li> <li><a href="{% url 'delete' %}">Kullanıcı Sil</a></li> <li><a href="#">Şifre Reset</a></li> </ul> </li> <li> <div class="iocn-link"> <a href="{% url 'users' %}"> <i class='bx bx-collection' ></i> <span class="link_name">Kullanıcılar</span> </a> <i class='bx bxs-chevron-down arrow' ></i> </div> <ul class="sub-menu"> <li class="list-group-item"><a href="{% url 'users' %}"> {% for user in users %} <div> <a href="">{{ user.username }}</a> </div> {% endfor %} </a></li> </ul> </li> <li> <div class="iocn-link"> <a href="{% url 'parameters' %}"> <i class='bx bx-book-alt' ></i> <span class="link_name">Parametreler</span> </a> </div> <ul class="sub-menu"> <li><a … -
Docker couldn't start properly throwing error: web_1 | /usr/bin/env: ‘python\r’: No such file or directory Django
I got error: web_1 | /usr/bin/env: ‘python\r’: No such file or directory after running docker-compose up on windows 10. -
Styling comments in Django
I found this tutorial on Django and Making a Hacker News Clone. Figure it'd be a good starting point as it's an pretty good break down with the Django and some concepts like comment parenting https://www.askpython.com/django/hacker-news-clone-django I thought cool and got through it, started learning more on Django Got my own search implemented into this too. However the comments on this were not great. So I wanted to improve things on it to make commenting prettier than the big colored blocks. However I've been stuck trying to make comment styling more Hacker News or Reddit style. I went searching and found https://css-tricks.com/styling-comment-threads/ though it it still didn't work the way I was figuring and wanted to have a more simplistic style though I'm running into a few issues. My idea would be to having it |Parent comment | Child Comment | Grandchild Comment | Child Comment2 |Parent Comment2 etc My commentpost.html comments section I modified {% for comment in comments %} {% if comment.identifier %} <div class="comment-thread"> <div class="replies"> <div class="comment-heading"> <div class="comment-vote"></div> <div class="comment-info"> <a href="#" class="comment-author"><a href = "{% url 'user_info' comment.creator.username %}">Comment by: {{comment.creator.username}}</a> | <strong>Thread Level: {{comment.identifier}}</strong></p> </div> </div> <div class="comment-body"> <p> <strong> {{ comment.content}} </strong> … -
Can't change dyno with Procfile on Heroku
I'm trying to deploy django project to Heroku using docker image. My Procfile contains command: web: gunicoron myProject.wsgi But when I push and release to heroku - somewhy dyno process command according to a dashboard is web: python3 Command heroku ps tells web.1: crashed And I can not change it anyhow. Any manipulation with Procfile doesn't work. When I deploy the same project with git - everything works fine. But why heroku container deploy does not work. Everything done following heroku instruction. My Dockerfile: FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ My docker-compose.yml: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data # ports: # - "5432:5432" environment: - POSTGRES_DB=${SQL_NAME} - POSRGRES_USER=${SQL_USER} - POSTGRES_PASSWORD=${SQL_PASSWORD} web: build: . # command: python manage.py runserver 0.0.0.0:8000 command: gunicorn kereell.wsgi --bind 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" # env_file: .env environment: - DEBUG=${DEBUG} - SECRET_KEY=${SECRET_KEY} - DB_ENGINE=${SQL_ENGINE} - DB_NAME=${SQL_NAME} - DB_USER=${SQL_USER} - DB_PASSWD=${SQL_PASSWORD} - DB_HOST=${SQL_HOST} - DB_PORT=${SQL_PORT} depends_on: - db My requirements.txt: Django psycopg2 gunicorn Please help me resolve this. Thanks in advance. -
Cannot resolve telethon AuthKeyDuplicatedError
Using Telethon to access a Telegram account and accidentally ran my dev server simultaneously with our production server the other day and now getting this error when trying to create a Telethon connection: telethon.errors.rpcerrorlist.AuthKeyDuplicatedError: An auth key with the same ID was already generated I've switched out the auth key and we deleted all the active sessions in our Telegram account, but to no avail. This is a script in a Django application running in docker on AWS EC2. Could there be a session file lurking somewhere I can't find? I'm using a redis cache, which I've cleared a couple times with no change to the error message either...although I didn't really think it was going to help. Any more ideas would be appreciated. note: I tried the solution steps listed here in this question it did not resolve the problem. -
How can i use from database models with MQTT in Django
Can anybody answer This Question ? I tried This: import django django.setup() But i got this exception: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/usr/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 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/media/me/MAIN/Projects/Fulligence/fulligence-core/billing/__init__.py", line 1, in <module> from .utils import client File "/media/me/MAIN/Projects/Fulligence/fulligence-core/billing/utils/__init__.py", line 1, in <module> from .mqtt import client File "/media/me/MAIN/Projects/Fulligence/fulligence-core/billing/utils/mqtt.py", line 2, in <module> django.setup() File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/apps/registry.py", line 83, in populate … -
Soap implementation in Python:all parameter
We want to rewrite this request in Python: $client = new nusoap_client('https://appketaba.com/Webservice/index.php?wsdl', 'wsdl', $proxyhost, $proxyport, $proxyusername, $proxypassword); In php, the nusoap-client class accepts various variables, including these four parameters that we want to send look at this: class nusoap_client extends nusoap_base { var $username = ''; // Username for HTTP authentication var $password = ''; // Password for HTTP authentication var $authtype = ''; // Type of HTTP authentication var $certRequest = array(); // Certificate for HTTP SSL authentication var $requestHeaders = false; // SOAP headers in request (text) var $responseHeaders = ''; var $responseHeader = null; // SOAP Header from response (parsed) var $document = ''; var $endpoint; var $forceEndpoint = ''; // overrides WSDL endpoint var $proxyhost = ''; var $proxyport = ''; var $proxyusername = ''; var $proxypassword = ''; var $portName = ''; // port name to use in WSDL here's the problem: We have only 6 parameters in Python libraries like zeep class Client: _default_transport = Transport def __init__( self, wsdl, wsse=None, transport=None, service_name=None, port_name=None, plugins=None, settings=None, ): How to send these parameters :proxyhost, proxyport, proxyusername,proxypassword -
Are Django user registration form fields limited to 'username', 'password1', 'password2', 'email', 'first_name', and 'last_name'?
I started a tutorial (seems like ages ago now) in which I built a user registration form with just 'username', 'email', password1', and 'password2' fields. Then a profile form was created on a separate page -- but I didn't like the way CreateProfile page/form looked. So I wanted to be able to put the fields in the CreateProfile form into the user registration form. I still have not found an answer about how to do that. -
Django vs PyCharm, which one is better? [closed]
I'm learning Python for a while using PyCharm anh it's quite pleasant. But I found that PyCharm is not recommended so much. I want to know which one (Django vs PyCharm) is better (like for learning, creating my own project and furthermore for work...) Thank you so much! PS: I used to learn JAVA so I understand fundamental programming, OOP and data structures... -
Guild ID Exception
With the django-allauth module, I am wanting to throw an exception if the user is not in a particular guild. What I am hoping to do is pass in a ACCOUNT_GUILD_REQUIRED = True, or within the provider settings the option for GuilDID. I can then catch that in user.model.manager to check if they are in the guild or not. -
django.db.utils.DatabaseError when added objects = models.DjongoManager() to Djongo mongodb model
I am getting django.db.utils.DatabaseError when trying to migrate my migrations. The only think I remember changing to my models is adding objects = models.DjongoManager() to my StockInfo model. I don't know if that causes a new migration but I am getting a very long error: cchilders@cchilders-HP-ProBook-450-G3 ~/projects/stocks_backend (save_stocks_info_to_db)$ python3 manage.py makemigrations Migrations for 'dividends_info': dividends_info/migrations/0003_auto_20220814_1800.py - Alter field id on stockinfo Migrations for 'users': users/migrations/0002_auto_20220814_1800.py - Alter field id on userprofile cchilders@cchilders-HP-ProBook-450-G3 ~/projects/stocks_backend (save_stocks_info_to_db)$ python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, dividends_info, sessions, users Running migrations: Not implemented alter command for SQL ALTER TABLE "dividends_info_stockinfo" ALTER COLUMN "id" TYPE int Applying dividends_info.0003_auto_20220814_1800...Traceback (most recent call last): File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 889, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 425, in __init__ super().__init__(*args) File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 441, in parse self._alter(statement) File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: … -
How do I add a csrf token to a json fetch in js?
Every time I try to run the code, I get an error that a CSRF token is missing. I have tried adding the token in the html and then adding an event listener for the form but that did not work as I still got the error and the console linked it to the line where I fetched a url. Attempt: (the {{ form }} is a django form which contains a textarea) <div id="add-form"> <form action="" id="form-add"> {% csrf_token %} <h2>New Post</h2> {{ form }} <input type="submit" value="Post" /> </form> </div> // Javascript document.querySelector('#form-add').onsubmit = submit // submit is the function with the fetch command So instead I used babel to add the form into the html (this was not to fix the problem). I have tried to manually add a CSRF token to the react form but I still got the same error: Forbidden (CSRF token missing.): /post. I also tried to add it using a JQuery function I found here (django documentation) but it did not work probably because every time I added the CSRF token in the form I still got the error. So how do I add a csrf token to a fetch command in … -
Organize django apps inside
When creating the apps you do the following: python manage.py startapp app1, but this automatically creates the app inside the root folder of the project. /project1/ /app1/ /app2/ ... __init__.py manage.py settings.py urls.py how to create and save in a folder already created all the apps that are created in Django? for example: in this case I have a folder called "apps" inside it I will have all the apps that are created during the development time: /project/ apps/ app1/ app2/ ... __init__.py manage.py settings.py urls.py Anyone who can provide information would be appreciated in advance. -
How i can reformat this code to follow DRY principle
my views.py from rest_framework import generics from rest_framework.pagination import LimitOffsetPagination from rest_framework.filters import SearchFilter, OrderingFilter from django_filters.rest_framework import DjangoFilterBackend from rest_framework.permissions import IsAdminUser from .serializers import * from .permissions import IsAdminOrReadOnly from .filters import * class ProductsAPIList(generics.ListCreateAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer pagination_class = LimitOffsetPagination permission_classes = (IsAdminOrReadOnly,) filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter) search_fields = ('title', 'category__name') filter_fields = ('category',) ordering_fields = ('price',) filterset_class = ProductsFilter class ProductsAPIUpdate(generics.RetrieveUpdateAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer permission_classes = (IsAdminOrReadOnly, ) class ProductsAPIRemove(generics.RetrieveDestroyAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer permission_classes = (IsAdminOrReadOnly, ) class StorageAPIList(generics.ListCreateAPIView): queryset = ProductsStorage.objects.all() serializer_class = ProductsStorageSerializer permission_classes = (IsAdminUser,) class StorageAPIUpdate(generics.RetrieveUpdateAPIView): queryset = ProductsStorage.objects.all() serializer_class = ProductsStorageSerializer permission_classes = (IsAdminUser,) class StorageAPIRemove(generics.RetrieveDestroyAPIView): queryset = ProductsStorage.objects.all() serializer_class = ProductsStorageSerializer permission_classes = (IsAdminUser,) class ProductSignAPIList(generics.ListCreateAPIView): queryset = ProductSign.objects.all() serializer_class = ProductSignSerializer permission_classes = (IsAdminUser,) class ProductSignAPIUpdate(generics.RetrieveUpdateAPIView): queryset = ProductSign serializer_class = ProductSignSerializer permission_classes = (IsAdminUser,) class ProductSignAPIRemove(generics.RetrieveDestroyAPIView): queryset = ProductsStorage.objects.all() serializer_class = ProductSignSerializer permission_classes = (IsAdminUser,) my urls.py from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView from InternetShop import settings from InternetShopApp.views import * urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/products/', ProductsAPIList.as_view()), path('api/v1/products/<int:pk>/', ProductsAPIUpdate.as_view()), path('api/v1/productsremove/<int:pk>/', ProductsAPIRemove.as_view()), path('api/v1/storage/', StorageAPIList.as_view()), path('api/v1/storage/<int:pk>/', … -
Wagtail / Django- images don't display in wagtail admin when published on a production server
I'm using Docker, PostgreSQL, Gunicorn and nginx. I've searched for the answer everywhere. All works fine on the development server. When I publish to the production server the images do not display in wagtail admin. Dockerfile.prod ########### # BUILDER # ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory WORKDIR /usr/src/wa-cms # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install Wagtail, Django and psycopg2 dependencies RUN apk update \ && apk add \ postgresql-dev \ gcc \ python3-dev \ musl-dev \ build-base \ jpeg-dev \ zlib-dev \ libwebp-dev \ openjpeg-dev # lint RUN pip install --upgrade pip --no-cache-dir RUN pip install flake8 COPY . . # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/wa-cms/wheels -r requirements.txt ###################### # FINAL - PRODUCTION # ###################### # pull official base image FROM python:3.8.3-alpine # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup -S app && adduser -S app -G app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/static RUN mkdir $APP_HOME/media WORKDIR $APP_HOME # install dependencies RUN apk update && apk add libpq \ postgresql-dev … -
How to show local time to the user in django?
I'm developing a Django app I have a model in which timestamps is added automatically. I want to show the time to the end users according to their local timezone. Here is my code: settings.py TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True model.py date_created = models.DateTimeField(auto_now_add=True, null=True) template {{object.date_created}} But it is showing UTC time I want this to detect user's current timezone and render date&time accordingly. -
Whole Javascript Not Working if 1 Array has Length of 0
Hi I am creating a bar chart, and having an issue with the JS in the chart. The JS is supposed to find the % of the total that each rating represents. For instance, A1 = 100 and total equals 1000, so a1 width should be 10%. The JS code works perfectly, except for when the array has no values in it, for instance when A2 has a length of 0. When this happens, it also makes all the values after it not work, even if they have arrays greater than a length of 0. I was wondering if anyone had an idea of what was going wrong thanks. <div class="statistics"> <h6>Rating Distribution</h6> <div class="bar-graph bar-graph-horizontal bar-graph-one"> <div class="bar-one"> <span class="rating">A1</span> <div class="bar" id="a1-rating" data-percentage=""></div> </div> <div class="bar-two"> <span class="rating">A2</span> <div class="bar" id="a2-rating" data-percentage=""></div> </div> <div class="bar-three"> <span class="rating">A3</span> <div class="bar" id="a3-rating" data-percentage=""></div> </div> <div class="bar-four"> <span class="rating">B1</span> <div class="bar" id="b1-rating" data-percentage=""></div> </div> </div> </div> <div class="hidden-rating-distribution-data"> {% for loans in a1_companies %} <div class="security-value-a1" hidden>{{loans.market_value}}</div> {% endfor %} {% for loans in a2_companies %} <div class="security-value-a2" hidden>{{loans.market_value}}</div> {% endfor %} {% for loans in a3_companies %} <div class="security-value-a3" hidden>{{loans.market_value}}</div> {% endfor %} {% for loans in b1_companies %} <div … -
How to keep the button clicked in javascript even after refreshing the page?
I am trying to build a single page app but like twitter for cs50 web project using Django I am using fetch API to get the all the posts on the site and use javascript to plug them in like this : document.querySelector('#all-posts-view').innerHTML = ''; fetch(`all_posts`,{ headers: new Headers({ 'secure': 'secure'}) }) .then(response => response.json()) .then(posts => { console.log(posts) posts.forEach(function(post) { let div = document.createElement("div"); div.setAttribute('id', 'post'); console.log(post.author) div.innerHTML = ` <a href='profile/${post.author}' id='profile-page' data-profile=${post.author_id} data-name=${post.author} > <P>${post.timestamp}</p> <h1 class="capitalize">${post.author}</h1></a> <h3>${post.post}</h3> <p>${post.likes}</p> <button onclick='style.color = "blue"'>Likes</button> {%if ${post.author} == 'zero'%} zzz{%endif%}` document.querySelector("#all-posts-view").append(div); }) }) and each div has a button to like the post , but when the user click on the button and the likes go up by one I do not know how can I show to that user that the like button was clicked because if the page is refreshed the function will just show normal posts and the user will not be able to tell if he actually liked the post or not When the button is clicked : After refreshing: After refreshing: So how can I keep the button clicked to that user ? do I need a global variable to represent the user? or … -
How can I prevent everyone from seeing admin user messages in django?
I'm attempting to set up a commenting system. The issue I have is that all users may see the admin messages. i thought i views from .models import Support, Comment from .forms import SupportForm, CommentForm @login_required def support_details(request, id): support = Support.objects.get(id=id) recent_support = Support.objects.all().order_by('-created_at') comments = Comment.objects.all() if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.user = request.user comment.save() comment_form = CommentForm() messages.success(request, 'comment posted successfully') else: comment_form = CommentForm() context = { 'support': support, 'recent_support': recent_support, 'comments': comments, 'comment_form': comment_form } return render(request, 'support-detail.html', context) models from users.models import User from django.db import models class Support(models.Model): SERVICE_CHOICES = ( ("Crypto", "Crypto"), ("Transaction", "Transaction"), ("Others", "Others"), ) support_id = models.CharField(max_length=10, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) subject = models.CharField(max_length=30, null=True, blank=True) email = models.EmailField(null=True) related_service = models.CharField( max_length=100, choices=SERVICE_CHOICES, null=True) message = models.TextField(max_length=1000, null=True) is_close = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.subject class Comment(models.Model): comment = models.TextField(max_length=1000, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user', null=True) support = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'comment', null=True, blank=True) created_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.comment template {% extends 'base2.html' %} {% load static %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% block … -
I keep getting : Reverse for 'delete_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['deleteentry/(?P<input_id>[^/]+)/\\Z']
I am a begginer and tried to look up solutions from other threads to no avail, Here is my views.py : @login_required(login_url='/login') def delete_entry(request, input_id): input=Diary.objects.get(pk=input_id) input.delete() return redirect('home') Here is my urls.py : urlpatterns = [ path('', views.welcome, name='welcome'), path('home', views.home, name='home'), path('MyEntries/', views.MyEntries, name='entries'), path('deleteentry/<input_id>/', views.delete_entry, name='delete_entry'), ] Here is my html code : <p>Hello, {{user.username}} !</p> {% for article in articles %} <p> {{ article.title}}<br> {{ article.description }} <br> {{ article.date }} <div class="card-footer text-muted"> </p> <a href="{% url 'delete_entry' input.id %}" class="delete">Delete</a> </div> {% endfor %} {% endblock %} -
Django Rest Framework, creating a one-to-many field relationship between users and another model
I am trying to create a simple model which holds a number as the primary key (week number) and then a list of users. Thus the model should be something like this, { id: 10, users: [ user1, user2, ... ] } I am pretty sure I should do this with a one-to-many field. Thus I created the following model, class Schema(models.Model): week = models.PositiveIntegerField(primary_key=True, unique=True, validators=[MinValueValidator(1), MaxValueValidator(53)], ) users = models.ForeignKey(MyUser, related_name="users", null=True, blank=True, on_delete=models.SET_NULL) class Meta: ordering = ('week',) What I want to happen is that if you do a POST request with an id and a list of users, then it simply creates the model. However if the id already exists, then it should simply clear the users, and add the newly given users instead. This is where I am stuck, I have tried the following (keeping comments in the code), class SchemaSerializer(serializers.ModelSerializer): # users = serializers.PrimaryKeyRelatedField(many = True, queryset = MyUser.objects.all()) # user_set = UserSerializer(many = True) class Meta: model = Schema fields = ('week', 'users') # def create(self, validated_data): # # users_data = validated_data.pop('users') # schema = Schema.objects.create(**validated_data) # # answer, created = Schema.objects.update_or_create( # # week=validated_data.get('week', 1), # # defaults={'users', validated_data.get('users', [])} # # … -
I can't place text and video in same grid in django with css
I have application which includes 3 videos(eventually it will include more). I have created a model in models.py and passed courses to template with context in my view. I want my title to be in border below the video but it makes some weird pose. I left some space under image for title. html <div class="next"> {% for course in courses %} {{ course.title }} <video src="/media/{{ course.videofile }}" controls=controls type="video" class="video">{{ course.title }}</video> {% endfor %} </div> css .next{ margin-top: 8em; display: grid; grid-template-columns: .1fr .1fr .1fr; gap: 1em; } .video{ max-width: 15em; border: 1px solid black; padding-bottom: 2em; } If I place for loop in another div it works better but titles are above videos. html <div class="next"> {% for course in courses %} <div class="div"> {{ course.title }} <video src="/media/{{ course.videofile }}" controls=controls type="video" class="video">{{ course.title }}</video> </div> {% endfor %} </div> (css is the same)