Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Web server with NGINX, Gunicorn (with workers > 1), and Djagno fails to save JWT in a cookie at server side
I have a WSGI Django application, with Gunicorn before it and Nginx as a web server. The Django Application is a Stateless DRF API. Django Related Configs REST_AUTH = { 'USE_JWT': True, 'JWT_AUTH_COOKIE': 'wird-jwt-auth', 'JWT_AUTH_REFRESH_COOKIE': 'wird-jwt-refresh', 'JWT_AUTH_RETURN_EXPIRATION': True, 'JWT_AUTH_HTTPONLY': False, "SESSION_LOGIN": False, "USER_DETAILS_SERIALIZER": "core.serializers.PersonSerializer", "PASSWORD_RESET_SERIALIZER": "core.util_classes.PasswordResetSerializer" } SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SECURE_HSTS_SECONDS = 2_592_000 SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin" # Application definition SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True X_FRAME_OPTIONS = 'DENY' PERMISSIONS_POLICY = {"fullscreen": "*", } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', "django.contrib.postgres", 'member_panel.apps.StudentConfig', 'admin_panel.apps.AdminPanelConfig', 'core.apps.CoreConfig', 'rest_framework', "rest_framework.authtoken", 'django.contrib.sites', 'allauth', 'allauth.account', 'dj_rest_auth.registration', 'django_filters', 'corsheaders', 'polymorphic', 'drf_yasg', "cachalot", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "django_permissions_policy.PermissionsPolicyMiddleware", 'django.middleware.locale.LocaleMiddleware', 'allauth.account.middleware.AccountMiddleware', ] Nginx Configs upstream app { server localhost:8200; } server { server_name .; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://app; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; } location /static/ { alias .; try_files $uri $uri/ =404; } location /media/ { alias .; try_files $uri $uri/ =404; } listen 443 ssl; # managed by Certbot # ssl files } When Gunicorn's workers are >1 the JWT Token I save at Client side disappear after the first refresh. When workers=1 … -
MacOS Django Less Issue
I used Django to use Less on my Windows computer without any issues, but when I switched to MacOS, the system reported an error enter image description here StaticCompilationError at /friendLink node:fs:1336 handleErrorFromBinding(ctx); ^ Error: ENOENT: no such file or directory, mkdir '/static/styles/less/global' at Object.mkdirSync (node:fs:1336:3) at module.exports.sync (/Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/node_modules/make-dir/index.js:97:6) at ensureDirectory (/Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/bin/lessc:172:7) at writeOutput (/Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/bin/lessc:230:7) at /Users/taro/.nvm/versions/node/v16.14.0/lib/node_modules/less/bin/lessc:311:9 { errno: -2, syscall: 'mkdir', code: 'ENOENT', path: '/static/styles/less/global' } Step: pip install django-static-precompiler npm install less -g Django setting.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/static/') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_PRECOMPILER_OUTPUT_DIR = '' Django templates: {% load compile_static %} {% load static %} ... <link rel="stylesheet" href="{% static "styles/less/global/components.less"|compile %}"/> I am certain that the Django project has this folder/static/styles/less/global enter image description here I thought it was a permission issue $ where lessc /Users/taro/.nvm/versions/node/v16.14.0/bin/lessc sudo chmod +x /Users/taro/.nvm/versions/node/v16.14.0/bin/lessc But it's useless I also tried PyCharm's File Watcher settings But it shouldn't be a problem. When I write a less file and save it, CSS will still appear Is it a problem with NVM, django static precompiler configuration, or macos? I'm not sure -
django if any of many to many has filed with value of False
Say I have a model of a library and I want to hide some books if either the book is marked as hidden or any of authors is marked as hidden or any of categories is marked as hidden. class Category(CustomModel): name = models.CharField(max_length=32, unique=True, null=False, blank=False) ... is_hidden = models.BooleanField(default=False) class Person(CustomModel): first_name = models.CharField(max_length=64, null=False, blank=False) ... is_hidden = models.BooleanField(default=False) class Book(CustomModel): title = models.CharField(max_length=128, null=False, blank=False) authors = models.ManyToManyField(Person, null=False, blank=False) translators = models.ManyToManyField(Person, null=True, blank=True) ... categories = models.ManyToManyField(Category, null=False, blank=False) ... is_hidden = models.BooleanField(default=False) Now I tried these queries to exclude all books with either, is_hidden=True, authors__is_hidden=True, translators__is_hidden=True, or categories__is_hidden=True: as this: books = Book.objects.filter( is_hidden=False, authors__is_hidden=False, translators__is_hidden=False, categories__is_hidden=False).distinct() and this: books = Book.objects.filter( is_hidden=False, authors__is_hidden__in=[False], translators__is_hidden__in=[False], categories__is_hidden__in=[False]).distinct() but I cannot find a way to achieve it. I wish to achieve my goal without a loop since the number of entries can get as high as 80K. How to make the query? -
Problems with implementing logout functionallity
i am trying to implement logout but everytime it throw [21/Feb/2024 00:11:58] "GET /logout/ HTTP/1.1" 405 0 if i try to logout trough drf view by clicking on admin -> logout it has the same error [21/Feb/2024 00:11:58] "GET /logout/ HTTP/1.1" 405 0 questionTime/urls.py from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from django.contrib.auth.views import LogoutView from django.urls import include, path, re_path from django_registration.backends.one_step.views import RegistrationView from core.views import IndexTemplateView from users import views as ws from users.forms import CustomUserForm urlpatterns = [ path('admin/', admin.site.urls), path( "accounts/register/", RegistrationView.as_view(form_class=CustomUserForm, success_url="/",), name="django_registration_register",), path("api-auth/logout/", auth_views.LogoutView.as_view(), name="rest_logout"), path('logout/', LogoutView.as_view(next_page=settings.LOGOUT_REDIRECT_URL), name='logout'), path("accounts/", include("django.contrib.auth.urls")), path("api-auth/", include("rest_framework.urls")), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), path("api/v1/", include("questions.api.urls")), path("api-auth/logout/", LogoutView.as_view(), name="rest_logout"), re_path(r"^.*$", IndexTemplateView.as_view(), name="entry-point"), ] settings.py LOGOUT_URL = '/logout/' LOGOUT_REDIRECT_URL = "/" it should log out user -
(WAGTAIL) Read_only for Non-superusers in Wagtail Admin
In my Wagtail admin panel, I want to make ModelA read-only for all users who are not superusers. Currently, the 'read_only' parameter is only available for FieldPanel. Is there another way to achieve this for InlinePanel? class ModelA(models.Model): panels = [ InlinePanel("model_b", classname="collapsed") ] class ModelB(models.Model): model_a = ParentalKey(ModelA, related_name="model_b", ....) foo = models.ForeignKey(ModelC, on_delete=models.CASCADE, ...) bar = models.CharField(max_length=100, ...) -
Why does the get request not reach the view?
I take the redirect request from the hidden input get tag, but it does not reach, I sat in the debug for an hour and looked at the code, tried to fix something, but everything seems to be correct, please help! def login(request): if request.method == 'POST': form = UserLoginForm(data=request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user: auth.login(request, user) messages.success(request, f"{username}, Вы вошли в аккаунт") if request.data.get('next', None): return HttpResponseRedirect(request.data.get('next')) return HttpResponseRedirect(reverse('main:index')) else: form = UserLoginForm() <form action="{% url "users:profile" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {% if request.GET.next %} <input type="hidden" name="next" value={{ request.GET.next }}> {% endif %} <div class="row"> <div class="col-md-12 mb-3 text-center"> {% if user.image %} <img src="{{ user.image.url }}" alt="Аватар пользователя" class="img-fluid rounded-circle" style="max-width: 200px;"> {% else %} <img src="{% static "deps/images/baseavatar.jpg" %}" alt="Аватар пользователя" class="img-fluid rounded-circle" style="max-width: 150px;"> {% endif %} <input type="file" class="form-control mt-3" id="id_image" name="image" accept="image/*"> {% if form.image.errors %} <div class="alert alert-danger alert-dismissible fade show">{{ form.image.errors }}</div> {% endif %} form request <WSGIRequest: POST '/user/login/'> user <User: wicki> username 'wicki' Here is a link with a get request that should redirect to the profile after sending the post request http://127.0.0.1:8000/user/login/?next=/user/profile/ -
Why does the authenticate fails even if the email and password are correct in django?
class login(APIView): def post(self,request): email=request.data.get('email') password=request.data.get('password') user=get_user_model() print("user model",user) print(email,password) user = User.objects.get(email=email) if str(password) == str(user.password): print("authenticated") # return Response({'status':200}) user = authenticate(request,email=email,password=password) if user is not None: # User is authenticated, you can proceed with further logic return Response({'status':200,'msg': 'Login successful'}) else: return Response({'status':401,'error': 'Invalid credentials'}) I have made a custom user model with email and password and i am making post request via postman and sending data in JSON format .I have used a simple password check and the password matched as expected but the authenticate function is not giving correct results . What can be the possible cause for this behavior and how to solve it? -
Infinite Load Page Phenomenon in Django Virtual Environments
I'm using MAC, and I had a problem developing django using virtual environments. My development environment uses vscode to access the aws server, open the django virtual environment with 127.0.0.1:8000, and test the page using local(Mac) chrome. I didn't have any particular issues before, but recently, page loading has suddenly slowed down and the page loading bar is running at infinity. I changed the operating system to Windows and tried again, but there was no problem. The issue only happens on my MacBook. What should I do? I emptied my MacBook's Chrome cache and reinstalled Chrome, but nothing improved. I was wondering if it was a vscode problem, but my development environment is being developed using aws server, so it means that it is not a vscode problem to operate smoothly in Windows environment. -
Celery Beat cannot connect to Rabbitmq container
My celery beat docker container has (from what i believe) problems connecting the message broker. I have a RabbitMQ container running: .... rabbitmq: image: rabbitmq:3.11.13-management-alpine container_name: 'rabbitmq' ports: - 5672:5672 - 15672:15672 env_file: - .env volumes: - ./data:/var/lib/rabbitmq/mnesia networks: - rabbitmq_go_net .... And a Python container running a Django application with Celery (there are multiple more containers running the backend itself, celery workers, celery beat and celery flower, which all utilize the same backend files but handle different tasks): .... celery-beat: build: context: . dockerfile: ./compose/local/django/Dockerfile container_name: 'beat' image: beat command: ["./wait-for-it.sh", "0.0.0.0:1337", "--", "/start-celerybeat"] volumes: - .:/app env_file: - .env depends_on: - rabbitmq - backend restart: always .... Starting script for celery beat start.sh (executed by /start-celerybeat): #!/bin/bash set -o errexit set -o nounset rm -f './celerybeat.pid' celery -A app beat -l INFO app/celery.py: from __future__ import absolute_import import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks()#(lambda: settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): .... app/settings.py INSTALLED_APPS = [ .... 'django_celery_results', 'django_celery_beat', .... ] CELERY_BROKER_URL = CONFIG.get('CELERY_BROKER_URL') CELERY_RESULT_BACKEND = CONFIG.get('CELERY_RESULT_BACKEND') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" .env RABBITMQ_USER=user RABBITMQ_PASSWORD=password RABBITMQ_PORT=5672 RABBITMQ_HOST=rabbitmq CELERY_BROKER_URL=amqp://${RABBITMQ_USER}:${RABBITMQ_PASSWORD}@localhost:${RABBITMQ_PORT}/${RABBITMQ_HOST} CELERY_RESULT_BACKEND=amqp:// I receive the … -
Problem in creating folder and file after upload in Django
I'm creating a source code evaluater platform using React and Django. Basically an user is going to upload a source file of his choice, my frontend sends the file to backend, which is working fine, and my backend has to create a copy of the file in a specific folder structure, because the code evaluater (different application) is set to access this structure searching for new files. The folder structure is basically like this: I've a first folder name Delivereds, inside it I've many folders named by the user id, inside each of these folders I've many folders named by the submission id. To simplify this problem solving, let's deal with this ignoring user id, let's just focus on folder adress like this: "/Delivereds/Question1/code.c++". My problem is that when I try to create a folder, it doesn't work. I'm pretty much a beginner in Django, so I don't really know if I need to set some configs in the main settings file. The solutions that I found in my searches are really simple and didn't work in my case. My current code is like this: elif request.method == 'POST': if request.FILES.get('file'): file = request.FILES['file'] parent_dir = '..\Delivereds\Question1' path = os.path.join(parent_dir, … -
Better way to connect django model with django cms page/placeholder
I'm making a website, and one of the features - News. I have a model News with some fields, to have a better user experience i thought that i need some more information for every News - html snippet and for good administrating that additional content for News, i decided that i need to use django csm. So on every page i have an information from News model and in the end of that - html snippet made with cms. And there is a problem - i don't know the better way to make my wishes. Important bit: i want to make all connections with model slug. I read docs about apphooks - but maybe it's not a good approach in my case? Couse apphooks make application embedding to django cms, but i need only the piece of creation and connecting of html template made by this cms. Additionally i tried just take a Page made by cms and put it in my html, but it was something wrong there, maybe it is not possible? Maybe i can see pages only on cms urls? page = Page.objects.all()[0] # for example in views I tried to make the model placeholder, but … -
Django- admin installation error - Failed building wheel for screen
I published my project on Windows server, but domain.com/admin is not working. As a result of research on the internet, I wanted to install Django-admin, but I am getting an error. I didn't have such a problem on my computer. Creating library build\temp.win-amd64-cpython-312\Release\source\str_util.cp312-win_amd64.lib and object build\temp.win-amd64-cpython-312\Release\source\str_util.cp312-win_amd64.exp str_util.obj : error LNK2001: unresolved external symbol PyUnicode_AS_UNICODE build\lib.win-amd64-cpython-312\screen\str_util.cp312-win_amd64.pyd : fatal error LNK1120: 1 unresolved externals error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.38.33130\\bin\\HostX86\\x64\\link.exe' failed with exit code 1120 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for screen Failed to build screen ERROR: Could not build wheels for screen, which is required to install pyproject.toml- based projects C:\inetpub\vhosts\domain.com.tr\httpdocs> Urls.py from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
why do i get this error "cannot unpack non-iterable bool object"
i get this error "cannot unpack non-iterable bool object" as i try to get user input from a form in django which in this case is an email def send_email(request): recepient_list=[] if request.method == "POST": email = request.POST['pwd_email'] print(email) if User.objects.filter(email == email).exists: recepient_list.append(email) send_mail("PASSWORD RESET", f"Your password resetkey is {random_no} \n Do not share this key with anyone", "eliaakjtrnq@gmail.com",recepient_list,fail_silently=False,) recepient_list.clear() -
Converting Flask or Django Web App to Desktop App for Secure Distribution
I have developed a web application using Flask/Django, and now I'm interested in converting it into a desktop application. I want users to be able to run the application directly from their desktop without needing a web browser, and I'm particularly interested in distributing it securely without exposing the source code. Can someone guide me on how to achieve this conversion? Are there any tools or frameworks available that can help in this process? I'm aiming to preserve the functionality and user experience of my web application while making it suitable for desktop usage and secure distribution. Additionally, I would appreciate any insights or best practices from those who have successfully converted web apps to desktop apps before and managed to distribute them securely without exposing the source code. Thank you in advance for your help! -
JWT refresh token is in httponly cookie, How to use DRF simple-jwt to regen the token
I have a front and backend app, front is react and backend is python Django (DRF), so my problem is I store the refresh token inside an HttpOnly cookie and send it in every request, but the DRF endpoint for refresh token (rest_framework_simplejwt.views.TokenRefreshView) will read the token itself from request.data which is the body of the Http request, is there a better way to handle this view other than rewriting a custom view? -
Django/ Office 365 : 535, b"5.7.139 Authentication unsuccessful, user is locked by your organization's security defaults policy
Running into the following error when trying to send email with Django: 535, b"5.7.139 Authentication unsuccessful, user is locked by your organization's security defaults policy. Here is my current config: #Emailing Settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_FROM = 'email@email.com' EMAIL_HOST_USER = 'email@email.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS= True This error was raised here: https://learn.microsoft.com/en-us/answers/questions/1469524/error-when-testing-smtp-for-django-website The irony of the answer provided by Microsoft is to suggest to disable the security default and also adding "not recommend". It seems the error is specific to Microsoft and comes from the use of SMTP, which MS's security doesnt like and encourage the use of OAuth. Can someone suggest an approach that worked for them? Did you disable the security defaults (for the specific email): is it risky? Did you implement OAuth and if so what steps did you take? -
I am hosting django project on hostinger using vps
I am trying to host my Django project on hostinger, I am using gunicorn to connect to vps and Nginx as the web server I correctly configured Nginx and gunicorn , everything is working without logs,But my site is not showing in the IP adress. -
Django IIS Deployment - HTTP Error 404.0 - Not Found
I need explanation on how to deploy Django Application on Windows IIS Server. I am struggling to follow the following tutorial I have a project which looks like this : [My_App] --> [My_App_Venv] --> [abcd] |-> manage.py |-> [abcd] |-> settings.py |-> [static] |-> ... [ example ] is used to represent folders I Need to understand how I should setup my IIS website : What should be FastCGI Application settings Full Path : C:\xxxxx\My_App\My_App_Venv\Scripts\python.exe Arguments : C:\xxxxx\My_App\My_App_Venv\Lib\site-packages\wfastcgi.py Environment Variables : 1. DJANGO_SETTINGS_MODULE : abcd.settings (I think this is ok) 2. PYTHONPATH : C:\xxxxx\My_App (I am not sure about this) 3. WSGI_HANDLER : abcd.wsgi.application (I think this is ok) Create and Configure a New IIS Web Site what should be the physical Path ? C:\xxxxx\My_App ? C:\xxxxx\My_App\abcd ? C:\xxxxx\My_App\abcd\abcd ? Configure the mapping module ## (which i assume is correct) Request path: * Module: FastCgiModule Executable : C:\xxxxx\My_App\My_App_Venv\Scripts\python.exe|C:\xxxxx\My_App\My_App_Venv\Lib\site-packages\wfastcgi.py Name : Django Handler output Hope someone can help to understand what I am doing wrong, I might use wrong path somewhere. Note : When I do By hand : cd C:/xxxxx/My_App/My_App_Venv .\\scripts\Activate cd.. cd abcd python manage.py runserver The website is well displayed on : http://127.0.0.1:8000/ -
jQuery loading animation not showing
I am attempting to follow the answer here to create a loading animation using jQuery: https://stackoverflow.com/a/1964871/23334971 Unfortunately, no loading animation shows for me and I'm not sure why. I am using Python/django for my server-side script. I'm not sure how to produce a minimal working example because the server side code takes a good few seconds to run. Maybe just replace it with a delay? I'm a complete noob so there's probably something obvious wrong with my code: This is my HTML: {% load static %} <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="{% static 'calculator/script.js' %}"></script> <link rel="stylesheet" href="{% static 'stylesheet.css' %}"> </head> <body> <article> <form id="calculatorForm"> <label for="num1">Numbers</label> <input type="number" name="number1" id="number1"> <input type="number" name="number2" id="number2"><br /> <button type="submit" role="button">Calculate</button><br /><br /> </form> <div class="modal"></div> <div id="result"></div> </article> </body> </html> stylesheet.css: (just copied and pasted from the linked stackoverflow answer) .modal { display: none; position: fixed; z-index: 1000; top: 0; left: 0; height: 100%; width: 100%; background: rgba( 255, 255, 255, .8 ) url('https://i.stack.imgur.com/FhHRx.gif') 50% 50% no-repeat; } /* When the body has the loading class, we turn the scrollbar off with overflow:hidden */ body.loading .modal { overflow: hidden; } /* Anytime the body has the loading class, … -
how to present in Jinja2 notation groupedby dataframe to html template in Django
In Django view I have function where I got dataframe from QuerySet. def owner_observation_count(request): form = ReportForm(request.GET) context = {} if form.is_valid(): organisation = form.cleaned_data['organisation'] department_for_report = form.cleaned_data['department_for_report'] employee_total = Observation.objects.values('owner__last_name','owner__first_name', 'date_created__year','date_created__month').annotate(owner_count_2=Count('owner_id')) if organisation: employee_total = employee_total.filter(users_organization=organisation) if department_for_report: employee_total = employee_total.filter(users_department=department_for_report) employee_total_pd = pd.DataFrame.from_dict(employee_total) employee_total_pd["Emploeey"] = employee_total_pd["owner__last_name"].str.cat(' ' + employee_total_pd["owner__first_name"].str.get(0) + '.') employee_total_pd = employee_total_pd.drop('owner__last_name', axis=1) employee_total_pd = employee_total_pd.drop('owner__first_name', axis=1) emp_columns = {'date_created__year': 'Year', 'date_created__month': 'Month', 'owner_count_2': 'Qty'} employee_total_pd.rename(columns=emp_columns, inplace=True) which gives the result | Year | Month | Qty | Employee | |------|-------|-----|------------| | 2023 | 6 | 2 |Kefer A. | | 2023 | 9 | 1 |Napylov S. | | 2023 | 6 | 2 |Grosheva N. | | 2023 | 9 | 3 |Sapego G. | | 2023 | 8 | 3 |Danilin S. | | 2023 | 8 | 2 |Alekseeva L.| | 2023 | 8 | 2 |Smirnova E. | | 2023 | 7 | 1 |SHaripov R. | | 2023 | 9 | 14 |Lyalina L. | | 2024 | 8 | 2 |Husainov S. | | 2024 | 8 | 3 |Kachanova T.| | 2024 | 8 | 6 |Chistova V. | | 2024 | 6 | 1 |Vishnyakov M| | … -
Cant pass data to Chart.js with Django
Im using bootstrap template for my website and have problem to pass data from view in django to html to chart.js I tried to pass data like any other variable but it didnt worked. I cant see data I have 2 charts one (pie) with predefined data set and second (doughnut) i want to pass data from view, neither shows after render. What do i do wrong? View.py ctx = { "tournament": tournament, "pairing": pairing, "players_points": players_points, "army_points": army_points, "teamB": teamB, "form": form, "green": green, "yellow": yellow, "red": red, "green_p": green_p, "yellow_p": yellow_p, "red_p": red_p, "total": total, # "chart_data": chart_data, "chart_data": json.dumps(chart_data), } return render(request, "pairing5v5.html", ctx) html <div class="container-fluid pt-4 px-4"> <div class="row g-4"> <div class="col-sm-12 col-xl-6"> <div class="bg-secondary rounded h-100 p-4"> <h6 class="mb-4">Pie Chart</h6> <canvas id="pie-chart" width="500" height="500"></canvas> </div> </div> <div class="col-sm-12 col-xl-6"> <div class="bg-secondary rounded h-100 p-4"> <h6 class="mb-4">Doughnut Chart - {{ chart_data|safe }}</h6> <canvas id="doughnut-chart"></canvas> </div> </div> </div> </div> main.js // Pie Chart var ctx5 = $("#pie-chart").get(0).getContext("2d"); var myChart5 = new Chart(ctx5, { type: "pie", data: { labels: ["Italy", "France", "Spain", "USA", "Argentina"], datasets: [{ backgroundColor: [ "rgba(235, 22, 22, .7)", "rgba(235, 22, 22, .6)", "rgba(235, 22, 22, .5)", "rgba(235, 22, 22, .4)", "rgba(235, 22, 22, … -
Django (removal of .auth and .django tables that are created after migrate command)
I have these 10 tables in Django (6-Auth tables and 4 Django tables) I am not using these files in my production project, I thought of removing them but read that its not a good practice to remove. I am dealing with some million records(GET and POST operations), Will these tables effect my code performance in the long run? I have Tried removing these tables but all of them are interlinked with foreign keys. -
Is this proper way to handle all CRUD operations in a single view (endpoint) using HTMX?
I'm new to using HTMX with Django and I'm seeking guidance. I'm in the process of redesigning a large CRUD application, aiming to integrate HTMX for improved interactions. Given the complexity of the app and its interactions with the database across various models, I want to ensure I start off on the right foot by adopting HTMX best practices early on. I've seen in many tutorials that everyone follows the common practice of creating separate views and URL paths for each database transaction (such as create, edit, delete, update). As I think that this could result in a significant amount of additional code and time investment, I would prefer to put all of the application logic in just one view (or endpoint), for each model. Can you please suggest me if this is the right flow and right way to do it: def movie(request, template_name="movies.html"): movies = Movie.objects.all() movie_form = MovieForm(request.POST or None) if request.method == 'POST': action = request.POST.get('action') # 1) CREATE if action == 'add_movie': if movie_form.is_valid(): movie_form.save() content = render(request, 'partials/movie-table.html', {'movies': movies}) return HttpResponse(content, status=201, headers={ 'HX-Trigger': json.dumps({'create': movie_form.cleaned_data['name']})} ) else: content = render(request, 'error.html', {'error': movie_form.errors}) return HttpResponse(content, status=202) # 2) DELETE elif action == … -
Django Rest Framework basic set of APIs around authentication
I'm a django newby and I'm looking to expose basic services like: forgotten password, password change. I would expect to have those services for free but looking here and there it looks like we have to do them by hand, is that correct? Is there any explanation for that? -
I have been trying to runserver for my code but I keep getting this error
your text I'm trying to create a website using django but each time I runserver i keep getting this error message: TemplateDoesNotExist at / base.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 5.0.2 Exception Type: TemplateDoesNotExist Exception Value: base.html Exception Location: C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages\django\template\backends\django.py, line 84, in reraise Raised during: main.views.home Python Executable: C:\Users\Admin\KredibleConstructionWebsite\venv\Scripts\python.exe Python Version: 3.10.11 Python Path: ['C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\python310.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\Admin\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0', 'C:\Users\Admin\KredibleConstructionWebsite\venv', 'C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages'] Server time: Tue, 20 Feb 2024 09:17:47 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction\main\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages\django\contrib\admin\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Admin\KredibleConstructionWebsite\venv\lib\site-packages\django\contrib\auth\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction\main\templates\base.html (Source does not exist) Error during template rendering In template C:\Users\Admin\KredibleConstructionWebsite\kredibleconstruction\main\templates\main\home.html, error at line 3 your text what can I do to resolve this cos I have corrected the base.html file mutliple times and even changed the directory to templates\main\bas.html but it is not working