Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I implement few checkboxes in a Django Form?
I was given a task to create a recipe website. A user can add a recipe. They have to choose a category (categories). One recipe can belong to one category or to several. I am inheriting my Form from ModelForm. Here's the code for it: class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['title', 'description', 'ingredients', 'cooking_steps', 'time', 'calories', 'portions', 'image', 'categories'] widgets = { 'title' : TextInput(attrs={'class' : 'create_recipe_title', 'placeholder' : 'Enter a title...' }), 'description' : TextInput(attrs={'class' : 'create_recipe_description', 'placeholder' : 'Enter a short description...' }), 'ingredients' : Textarea(attrs={'class' : 'create_recipe_ingredients', 'placeholder' : 'Your ingredients...', 'disabled' : True }), 'time' : NumberInput(attrs={'class' : 'create_recipe_time', 'placeholder' : 'Cooking time...' }), 'calories' : NumberInput(attrs={'class' : 'create_recipe_calories', 'placeholder' : 'Calories...' }), 'portions' : NumberInput(attrs={'class' : 'create_recipe_portions', 'placeholder' : 'Portions...' }), 'image' : FileInput(attrs={'class' : 'create_recipe_image'}), 'cooking_steps' : Textarea(attrs={'class' : 'create_recipe_cooking_steps', 'placeholder' : 'Describe the cooking process...' }), 'categories' : SelectMultiple(choices=[(1, 'Food'), (2, 'Drinks'), (3, 'Hot'), (4, 'Cold'), (5, 'Breakfast'), (6, 'Lunch'), (7, 'Dinner'), (8, 'Выпечка и десерты'), (9, 'Soups'), (10, 'Salads'), (11, 'Pizza and pasta'), (12, 'Sauces'),(13, 'Portugal'), (14, 'Italy'), (15, 'France'), (16, 'Japan'), (17, 'Chine'), (18, 'Georgia'), (19, 'Armenia'), (20, 'Mexico'), (21, 'Africa'), (22, 'Dietary'), (23, 'Sugar free'), (24, … -
Type Error while populating a model in Django with UniqueConstraint
I'm trying to build up my first project in Django and I'm having some issues while creating an entry into my model Prevision (including sales forecasts), which has a uniqueConstraint to ensure that there is only one forecast between a Supplier (model "Representada") and a Customer (model "Cliente") for a give year (field "Ano"). My models.py file is as follows: from django.db import models from django.db.models import CheckConstraint, Q, F, UniqueConstraint from django.db.models.signals import pre_save from django.dispatch import receiver from datetime import datetime # Create your models here. class Empresa (models.Model): CIF = models.CharField(max_length=9, unique=True, blank=True) Nombre = models.CharField(max_length=64) Telefono = models.CharField(max_length=16, blank=True) Email = models.EmailField(blank=True) Direccion = models.CharField(max_length=64) Ciudad = models.CharField(max_length=32) CP = models.PositiveIntegerField(default=1) Provincia = models.IntegerField(default=1) Contacto = models.CharField(max_length=64, blank=True) Observaciones = models.TextField(blank=True) def __str__(self): return f"{self.Nombre}" class Meta: abstract = True verbose_name_plural = "Empresas" constraints = [ ] class Representada (Empresa): Fecha_Alta = models.DateField() Fecha_Baja = models.DateField(blank=True, null=True) Porcentaje_Comision = models.DecimalField(max_digits=5, decimal_places=2) class Meta: verbose_name_plural = "Representadas" constraints = [ CheckConstraint( check = Q(Fecha_Baja__isnull=True)|Q(Fecha_Alta__lte=F('Fecha_Baja')), name = 'Comprobar fecha de alta y baja de representada', ), ] class Cliente (Empresa): Hay_Toro = models.BooleanField(blank=True) Inicio_Horario_Descarga = models.TimeField(blank=True, null=True) Fin_Horario_Descarga = models.TimeField(blank=True, null=True) def __str__(self): return f"{self.Nombre} ({self.Ciudad})" class Meta: … -
TimeoutError at /studentupdtpwd
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Request Method: POST Request URL: http://127.0.0.1:8000/studentupdtpwd Django Version: 5.0 Exception Type: TimeoutError settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@amil.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_TIMEOUT = 860 ``` While sending email from an Django application using send_mail or EmailMessage sometimes it is working fine but sometimes getting TIME OUT ERROR for same logic.I also created another app and updated settings.py new generated password. -
drf_yasg: Not able to generate Swagger UI from YAML file
I am using the drf_yasg library in my Django REST Framework project to generate Swagger documentation. I have defined my API endpoints and schemas in a YAML file, but when I try to generate the Swagger UI, it is not rendering correctly. It's rendering UI using auto-discovery, which does not have information about functions, but I want to add more information to it. Some key details: I have installed drf_yasg and added it to my Django INSTALLED_APPS I have defined my API endpoints and schemas in a swagger.yaml file In my Django URL config, I have added the get_schema_view() from drf_yasg to generate the schema This is my project urls.py from django.contrib import admin from django.urls import path, include from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework import permissions schema_view = get_schema_view( openapi.Info( title="My Application", default_version="v1", description="A sample API for learning DRF", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="hello@example.com"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), path('swagger/', schema_view.with_ui( 'swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui( 'redoc', cache_timeout=0), name='schema-redoc'), ] this how my function looks: @api_view(['POST']) def searchData(request): name = request.data.get('name') vendor = request.data.get('vendor') s = AppSearch() result = s.search(name, vendor) result = json.loads(json_util.dumps(result)) return Response(result, status=status.HTTP_200_OK) By default, Swagger is showing … -
How to code efficiently in a django project?
I am begineer in django, i am doing my first project in django. I am using mysql database with my project. Now while fetching data from the database and showing it in different sections of my projects need some logic, so i am using simple "for loops" , "if else statements" to do all this. I am also using boolean flags inside the database to execute different logic. I want to know, is this a correct approach to make a django project, or is there any startergy i should follow while adding new features or making new code ? Kindly help, I just want to know about the technique i should follow, as a begineer this question might be simple but it might be important for many as well. "A request, Please dont downvote this question for any unnecessary reason" -
How do I minify my HTML so that CSS and FontAwesome and Bootstrap names are reduced
I have a Django website that displays a table with data. It uses FontAwesome and Bootstrap for styling - which leads to some lengthy HTML (a standard page is 136k). Eg Some TDs contain an arrow using FA and a style to rotate it eg <i class="fa-solid fa-arrow-down fa-lg fa-rotate-by" style=--fa-rotate-angle:282deg></i> Is there a way to minify or some how reduce the name sizes? I have been reading about webpack and gulp minifiers but I cannot find anything that mentions the use of 3rd party assets like FA and BS and how one might reduce their name sizes. Also these seem somewhat targeted to client-side frameworks rather than server-side which mine is. -
ModuleNotFoundError: No module named 'rest_framework_simplejwt'
I am experiencing an issue with rest_framework_simplejwt when I try to run migrations in my Django project. The error I encounter is: ModuleNotFoundError: No module named 'rest_framework_simplejwt' I have verified that the library is installed: pip show djangorestframework-simplejwt Name: djangorestframework-simplejwt Version: 3.2.2 Summary: A minimal JSON Web Token authentication plugin for Django REST Framework Home-page: https://github.com/davesque/django-rest-framework-simplejwt Author-email: davesque@gmail.com License: MIT Location: \Programs\Python\Python311\Lib\site-packages Requires: django, djangorestframework, pyjwt Required-by: My INSTALLED_APPS includes the necessary applications: INSTALLED_APPS = [ 'app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist' ] Here are my REST_FRAMEWORK settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } And my SIMPLE_JWT settings: from datetime import timedelta SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "UPDATE_LAST_LOGIN": False, "ALGORITHM": "HS256", "SIGNING_KEY": SECRET_KEY, "VERIFYING_KEY": "", "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 0, "AUTH_HEADER_TYPES": ("Bearer",), "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", "JTI_CLAIM": "jti", "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5), "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", } I don't understand where the problem comes from. I would appreciate any help to identify the issue. What I have tried: Installing different versions of … -
How to reduce the amount of HTML style code
I have a Django website that displays data in a table, most of the data is highlighted with a calculated background color to make it quickly obvious to the user. Is there a way to reduce the amount of HTML I am outputting? Eg: <td style=background-color:#5eff00>19</td> Ideally I'd use CSS - but I would literally be creating a class for every hex color value. Is there a better way? I did consider using the html bgcolor attribute but this is not supported by HTML5. Is this a possibility? -
Django code freezes using Daphne on async database queries
I am running an async django application that is downloading some data. As I want the downloads to run asynchronously, I defined some async methods to run as coroutines. These methods sometimes have Django ORM queries, which I also run asynchronously (async for loop, sync_to_async or .aget(), for example). Since I'd like to display the download progress in clients browser in realtime, I installed django-channels together with daphne to setup websockets. However, If I run my code without daphne, everything works perfect. But as soon as I register daphne as app in settings.py (that runserver is actually running daphne serevr), the code stucks at a async database query. More details: settings.py: ASGI_APPLICATION = 'MultiClaw.asgi.application' INSTALLED_APPS = [ 'daphne', ... ] The view, that is mapped to a button which starts the download: @csrf_exempt def start_grab_thread(request): parser_name = request.POST['parser_name'] settings_model = Settings.objects.filter(user=request.user, parser_name=parser_name)[0] parser_module = importlib.import_module(f'parser.Parser.{parser_name}') parser_class = getattr(parser_module, parser_name) parser_instance: Core = parser_class(settings_model) asyncio.run(parser_instance.download_products()) if request.method == "POST": return redirect('start') the function, where the problem occures: async def download_products(self): print('downloading products') collected_product_urls = self.product_url_list print(f'{collected_product_urls=}') product_urls_from_db = set([ product.source_url async for product in Product.objects .filter(pk__in=collected_product_urls) ]) print(f'{product_urls_from_db=}') print(f'FINALLY GOT IT') return I tried many attempts, wrap the query into a … -
infinte loop when transforming django into exe file
I want to execute " runserver" command and "run_file_watcher" which is custom command at the same time each one on a sperate thread , it works fine , but when transforming it into exe file with Pyinstaller it go for infinite loop this is the code for multithreading # run_both.py import os from threading import Thread import subprocess import sys import django # Set Django settings module explicitly os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() def run_django_server(): print("Starting Django server...") subprocess.run([sys.executable, 'manage.py', 'runserver']) print("Django server finished.") def run_custom_command(): print("Running custom command...") subprocess.run([sys.executable, 'manage.py', 'run_file_watcher']) print("Custom command finished.") if __name__ == "__main__": # Create threads thread1 = Thread(target=run_django_server) thread2 = Thread(target=run_custom_command) thread1.start() # returns immediately thread2.start() # returns immediately -
Django can`t find image
when i run my Djanfo app by daphne i get error WARNING Not Found: /media/images/lcg.jpg daphne -e ssl:8000:privateKey=ssl/privkey.pem:certKey=ssl/cert.pem website.asgi:application i set all setiings by guids and documantation settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('shop.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html {% for product in column1 %} <div class="item"> {% if product.img %} <img src="{{ MEDIA_URL }}{{ product.img }}" alt="{{ product.name }}" class="product-img"> {% endif %} tried add {% get_media_prefix as MEDIA_URL %} but nothing changed where product.img from DB - images\filename.png and i have this structure i had similar problen with static files but ChatGPT advised to use whitenoise and it solved problem but not with img -
Django automatic conversion/casting when doing lookups
Could someone explain to me where I can find information about why this works in Django? I did some research in the official documentation and couldn't find anything. from django.db import models class Document(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) # Query using an integer document1 = Document.objects.get(id=1) # Query using a string that can be converted to an integer document2 = Document.objects.get(id='1') # Both queries should yield the same result I check this pages in the official documentation: https://docs.djangoproject.com/en/5.0/ref/models/fields/#model-field-types https://docs.djangoproject.com/en/5.0/topics/db/queries/ https://docs.djangoproject.com/en/5.0/ref/models/lookups/ -
Using Records from One Model in Another Model's Column in Django
I Want to Using Records from One Model in Another Model's Column in Django in the Following Code: The Code Says a Model that Add Products as Record and I want to add a model that gives me a Product Records as Column and integer value for giving order. For Example: I Have Apple and Orange in my records and i want to have a model to order 3 Apple and 5 Orange. Note: If I add another Product Record, It Must Add Another Column in Order Model. My Product Model Code is this: class Product(models.Model): name = models.CharField(max_length=255) priceWholeseller = models.IntegerField() priceSeller = models.IntegerField() def __str__(self): return self.name -
Django urlpatterns including / at the back
I'm a student learning Django. I have a question and I'd appreciate it if someone could help me. When I navigate to 127.0.0.1:8000/feeds/1, it correctly displays the feed with ID 1. However, I encounter an issue when I navigate to 127.0.0.1:8000/reviews/1, and I get the following error says page not found This problem can be resolved by adding a slash in the reviews/urls.py path section like this: "int:review_id/". My question is: why does the feeds URL work without the trailing slash in the urlpatterns, but for reviews I have to include the trailing slash to make it work? here is the main urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path("admin/", admin.site.urls), path("feeds/", include('feeds.urls')), path("users/", include('users.urls')), path("reviews/",include('reviews.urls')) # path("boards/", include('boards.urls')) ] # feeds/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.Feeds.as_view()), path("<int:feed_id>",views.FeedDetail.as_view()) ] # reviews/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.Reviews.as_view()), path("<int:review_id>/", views.ReviewDetail.as_view()) ] -
I want to install Docker Desktop for Windows 11
After installing Docker, when I run Docker I get an error "wsl --update" And when I run the code "wsl --update" in 'windows powershell' I get an error: "The service cannot be started, either because it is disabled or because it has no enabled devices associated with it" What is the problem? -
Why doesn't DataDog show BEGIN queries?
I am using DataDog with a Django site running on gunicorn with a Postgresql database. We have atomic DB transactions enabled by default. Postgres and Python traces are both configured per the DataDog documentation. In DataDog we can see the Postgres spans for the transaction COMMIT queries, but the transaction BEGIN queries are missing. I am trying to debug some performance issues with our site and would like to see if the BEGIN queries are somehow at fault, but it's nearly impossible to confirm this when they aren't showing up in DataDog. How do I get the transaction BEGIN queries to show in DataDog? This is a screenshot of a trace from the /health endpoint, which executes zero SQL queries but is still wrapped in a DB transaction. You can see that most of the response time is a black hole where I cannot see what is happening. This trace was only 9ms, but sometimes this delay can take up to 10 seconds which is totally baffling. -
Is there an way to go around the "Field 'id' expected a number" when dealing with a queryset?
I am working on a learning platform. I want to be able to track user progress of the chapters completed. I cerated a new model and inserted it into the html using a form. However when I submit, I keep getting a TypeError with the specifics that "Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['YMvOO6ZYGWVVfxfgoFLVEanZ9zK70CrqlRIx5Y2LOkbzH8Mx3UHPlQYczqLbq1Qt'], 'chapter': ['2'], 'completed': ['on'], 'student': ['1']}>" I tried converting all the variables I was using to identify the user, student and chapter to their primary keys but I got even more complicated error. If there is an easier way to track the progress or a tutorial on a way to do it, please share. Here's what I tried This is he StudemtProgress Model class StudentProgress(models.Model): student = models.ForeignKey( Student, on_delete=models.CASCADE, related_name="student_progress" ) chapter = models.ForeignKey( Chapter, on_delete=models.CASCADE, related_name="student_progress" ) completed = models.BooleanField(default=False) This is the form. Some of the code is to pick only the current logged in user and the chapter of th page that it is being displayed. class StudentProgressForm(forms.ModelForm): class Meta: model = StudentProgress fields = ("chapter", "completed", "student") # widgets = { # "student": forms.HiddenInput(), # } def __init__(self, user, student_slug, chapter_slug, *args, **kwargs): super(StudentProgressForm, self).__init__(*args, **kwargs) student_queryset = … -
Error 403 while running Docker image on Windows, but works on RHEL8
I have a web application made in Django, I build it and run it in Linux Redhat 8 and it works fine. Trying to run it on Windows using Docker allows me to get into webpage, but I can't login, I just get [POST] Error 403 (Forbidden), But the image is the same at both envs. I'm accesing it via 127.0.0.1:8000, which is CSRF Enabled in settings.py and in ALLOWED_HOSTS and works on RHEL8, but doesn't allow me to login on Windows (same for 0.0.0.0:8000 and localhost:8000) How I run it in both environments docker run -it --rm -p 8000:8000 my_image_name Dockerfile: FROM my_image_repo ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY . /app/ EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] settings.py: CSRF_TRUSTED_ORIGINS = [ 'http://localhost', 'http://localhost:8000', 'http://127.0.0.1:8000', 'http://127.0.0.1', 'http://0.0.0.0' ] ALLOWED_HOSTS = [ 'http://localhost', 'http://localhost:8000', 'http://127.0.0.1:8000', 'http://127.0.0.1', 'http://0.0.0.0', 'localhost', '0.0.0.0', 'localhost:8000', '127.0.0.1', '127.0.0.1:8000' ] Are there any firewall settings I need to change for it to allow me to do that on windows? I usually work on Linux only, but company requires me to make this work on Windows as well I tried adding more URLS to ALLOWED_HOSTS and CSRF, as well as I added to settings.py this line: SECURE_PROXY_SSL_HEADER = … -
How to fix Constant Errors When Implementing Google OAuth Sign-in with Django
I decided to put a google sign in method into my Django website, but I have been encountering errors related to the social_auth_app_django library. For example, at first I got a ValueError (Expected 2 got 1) from one of the utils.py in the library code. Note that I am new to adding google sign in to a Django application. Here are my version specifications: Django version 4.2.13 Python version 3.10.5 social_auth_app_django library version 5.4.1 Here is my settings.py (note that the API keys will be hidden for security purposes) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "games.apps.GamesConfig", "account.apps.AccountConfig", "forums.apps.ForumsConfig", "play.apps.PlayConfig", "make_game.apps.MakeGameConfig", "administration.apps.AdministrationConfig", "bootstrap5", "payments.apps.PaymentsConfig", "social_django" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'account.middleware.DeviceDetectionMiddleware', # "django.middleware.debug.DebugMiddleware", 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'superstarstudios.urls' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "my-google-key" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "my-google-secret" SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ "email", ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2' ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates" ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'account.context_processors.device_type', "social_django.context_processors.backends", 'social_django.context_processors.login_redirect' ], }, }, ] LOGIN_REDIRECT_URL = "/games" LOGOUT_REDIRECT_URL = "/" SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'account.pipeline.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) Here is the function where the main ValueError is … -
Django: subclass, separate class or entirely separate classes
I'm building a forum app in Django as a learning project. I'm unsure of how to approach the creation of Post objects. I want users to be able to post threads (i.e. new topic), I want users to be able to post replies to those threads as well as replying to other replies. I want to include features like reactions to posts, and replies. I'd appreciate some feedback on the different approaches I'm considering: My thinking is that, since the two types of posts are so similar, they should inherit common fields/methods from a parent class. I'm unsure how Django would represent that in the DB tbh. Intially this was an abstract class class Post(models.Model): post_body = models.TextField(max_length=2000) publish_date = models.DateTimeField("date posted") author = models.ForeignKey(User, on_delete=models.CASCADE) class ThreadPost(Post): post_title = models.Charfield(200) is_solved = models.BooleanField("is_issue_solved", default=False) class ReplyPost(Post): is_solution = models.BooleanField("is_this_the_solution", default=False) thread_post = models.ForeignKey(ThreadPost, on_delete=models.CASCADE) Later I started using this, based on a stackoverflow response. However, I'm finding it a bit clunky to work with, as I often have to filter by whether a post is a thread or a reply, and have to find the thread which a post replies to. In that case, just having seperate classes seems … -
Protecting publicly accessable endpoints in Django and React
I have an endpoint urls.py from django.urls import path from . import views app_name = 'Main' urlpatterns = [ path("helloKitty/", views.helloKitty, name='helloKitty'), ] views.py def helloKitty(request): hello = pd.read_csv('static/data/helloKitty_data.csv') hello = hello.to_json(orient='records') return HttpResponse(hello) It's currently accessible by anyone at /helloKitty and it needs to be prevented. I use React on the front-end to access this endpoint and retrieve the data import React from "react"; import { create } from 'zustand'; import axios from 'axios'; const kittyStore = create((set) => ({ kitten: [], fetchKitty: async () => { const response = await axios.get('/helloKitty'); const hello = response.data.map((h) => { return { name: h.name, age: h.age, } }); set({ kitten }) }, })); export default kittyStore; The endpoints /helloKitty needs to be protected from being publicly accessible, and just the React app can view and fetch the data. -
Django REST 404 sending params in the url
Good day, I'm having problems with django/ django rest apí Back: url(r'^' + baseurl + etl + eph + 'salud_folder_xls/listar/<str:accion>/', etlEPHSaludXLSListar), url(r'^' + baseurl + etl + eph + 'salud_folder_xls/descargar/(?P<nombre_archivo>.+\\.xls)', etlEPHDescargarSaludFolderXLS), Front: const response = await axios({ url: '/etl/v1/eph/salud_folder_xls/listar/', method: 'GET', }); When I try salud_folder_xls/listar/ works fine but when I add accion, axios returns always ERROR 404 Any idea? -
Voucher Appears on Both Debit and Credit Sides in Sundry Creditors Ledger in Logistic Accounting Software
I am currently working on existing logistic company's accounting software.the sundry creditors ledger data function returning a single voucher entry twice: once on the debit side and once on the credit side. This behavior seems incorrect as the voucher should only be listed once.its only happening journal Vouchar entry for eg: - as you can see the 100 rs transaction effects on both dr and cr side its journal Vouchar entry rest of the vouchar types working perfectly def get_sundry_creditors_coa_response(coa, start_date, end_date, user): invoices = Invoices.objects.filter(date__range=[ start_date, end_date], invoice_type='Purchase', company__users__email=user.email).order_by('date') respone = [] res_obj = {} for invoice in invoices: cost_entrys = CostEntry.objects.filter( invoice__id=invoice.id, is_included=True) for cost_entry in cost_entrys: res_obj = { "account": invoice.client_name.name if invoice.client_name else "", "date": invoice.date, "currency": invoice.currency_sar, "invoice_number": invoice.invoice_number, "vat_percent": 0, "fcy_amount": 0, "vat_amount": 0, "amount": 0, "dr_amount": 0, "cr_amount": 0, "net_amount": 0, "type": "Invoice", "voucher": "", "party_account": invoice.party_account.name if invoice.party_account else "", "job_no": invoice.job.job_number if invoice.job.job_number else "", "narrations": invoice.narration if invoice.narration else "", "branch": invoice.branch if invoice.branch else "", "language_name": coa.language_name if coa.language_name else "" } fcy_amount = float( cost_entry.fcy_amount if cost_entry.fcy_amount else 0.0) amount = float(cost_entry.amount if cost_entry.amount else 0.0) vat_percent = float( cost_entry.tax_group_code if cost_entry.tax_group_code else 0.0) vat_amount = float((vat_percent * … -
How to override queryset for newly added fieldset in Django Admin Panel
I have added "permissions" fieldset in my User model on Admin Panel, but when I try to add a User it takes a lot of queries due to permissions (500) in my case, I am not able to optimize the code because get_queryset is not executing while adding an object. I want to know how can I fetch all related permissions in add user form, so it should fetch all select related permissions to optimize the admin panel interface. -
Get values from request
I am trying to write values from a request.POST to a string format. By default, these always start with "epochs-NUMBER-". Therefore, I should draw a For loop so that a new line is created for each number. The complete request looks like that. But I only need the 'epochs-NUMBER-' values csrfmiddlewaretoken=hJmSuP3O6GmtwBeJhfqb99LaCVOKxgngGNIEqoqhQQR7tQELUVGHeXRXxfnRE1Ah&base-TOTAL_FORMS=1&base-INITIAL_FORMS=0&base-MIN_NUM_FORMS=0&base-MAX_NUM_FORMS=1000&base-0-time=25.06.2024+13%3A36%3A00&base-0-show_differences=on&base-0-show_null=1&source=Manual&epochs-TOTAL_FORMS=3&epochs-INITIAL_FORMS=3&epochs-MIN_NUM_FORMS=0&epochs-MAX_NUM_FORMS=1000&unit_selector=m&unit_selector=m&unit_selector=m&unit_selector=m&epochs-0-target_name=250.01.G&epochs-0-easting=55555&epochs-0-northing=5555&epochs-0-height=555&epochs-0-azimuth=&epochs-0-zenithangle=&epochs-0-slope_dist=&epochs-1-target_name=170.01.G&epochs-1-easting=44646&epochs-1-northing=6554&epochs-1-height=544&epochs-1-azimuth=&epochs-1-zenithangle=&epochs-1-slope_dist=&epochs-2-target_name=150.01.G&epochs-2-easting=78979878&epochs-2-northing=4645&epochs-2-height=455&epochs-2-azimuth=&epochs-2-zenithangle=&epochs-2-slope_dist= The request looks like that: def nmea_string(self, request, target_name): my_dict = {} keys = [] values = [] target_raw_string = ("PTER," + self.short_name + "_TRG," + target_name + "," + self.time.strftime("%Y-%m-%d %H:%M:%S") + "," + str(self.status_target)) for key, value in request.POST.items(): keys.append(key) values.append(value) for i in range(len(keys)): my_dict.update({keys[i]: values[i]}) for k, v in my_dict.items(): if k.startswith('epochs-0-'): if v == '': v = '-9999.999900' if k.startswith('epochs-0-target_name'): target_raw_string += "," + v else: target_raw_string += "," + v + ",0.000000" tg_checksum = self.get_checksum(target_raw_string) tg_nmea_string = "$" + target_raw_string + "*" + tg_checksum + "\n" nmea_string += tg_nmea_string return nmea_string The end result should look a bit like this: $PTER,TS_TRG,TP-008,2024-04-22 23:00:00,129,675666.252000,0.000000,252132.398000,0.000000,412.137000,0.000000,-9999.999900,0.000000,-9999.999900,0.000000,-9999.999900,0.000000*1F $PTER,TS_TRG,TP-009,2024-04-22 23:00:00,129,675704.440000,0.000000,252162.055000,0.000000,412.341000,0.000000,-9999.999900,0.000000,-9999.999900,0.000000,-9999.999900,0.000000*1A