Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retrieve value in Dropdown list on edit button in Django
I have a form (edit_city.html) where I want to edit my record, there is also one dropdown field in which data is retrieving from another model name Country. How can I get the exact value in dropdown field, when I click on edit. class Country(models.Model): CountryID = models.AutoField(primary_key=True) CountryName = models.CharField(max_length=125, verbose_name="Country Name") def __str__(self): return self.CountryName class City(models.Model): CityID = models.AutoField(primary_key=True) CityName = models.CharField(max_length=125, verbose_name='City Name') Country = models.ForeignKey(Country, verbose_name='Country Name', on_delete=models.CASCADE) def __str__(self): return self.CityName views.py def Edit_City(request, id): city = City.objects.get(CityID=id) country = Country.objects.all() context = { 'city':city, 'country':country, } return render(request, 'City/edit_city.html', context) edit_city.html <form method="post" action="{% url 'update_city' %}"> {% csrf_token %} <div class="row"> <div class="col-12"> <h5 class="form-title"><span>Edit City</span></h5> </div> {% include 'includes/messages.html' %} <div class="col-12 col-sm-6"> <div class="form-group"> <label for="">Country</label> <select class="form-control" name="country_id" required> <option>Select Country</option> {% for con in country %} <option value="{{con.CountryID}}">{{con.CountryName}}</option> {% endfor %} </select> </div> </div> <div class="col-12 col-sm-6"> <div class="form-group"> <label>City Name</label> <input type="text" class="form-control" name="city_name" value="{{city.CityName}}" required> <input type="text" class="form-control" name="city_id" value="{{city.CityID}}" required hidden> </div> </div> <div class="col-12"> <button type="submit" class="btn btn-primary">Update City</button> </div> </div> </form> -
Fetch API key from Django to React app in a secure way
I am building an app at the moment and security is a priority so I want to ensure I'm implementing API fetches correctly. I currently have stored an API key in a .env file in Django. I want to use this key to perform requests through the frontend. django-app/.env API_KEY = key settings.py import os from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) SECRET_KEY = os.environ['API_KEY'] I'm only just getting into backend development so I'm unsure of how to produce a view that would allow the frontend to use this key safely. Any tips or pointers will be much appreciated, thank you -
Django get_next_in_order and get_previous_in_order return incorrect data when objects are stored in non-default database
When using get_next_in_order and/or get_previous_in_order with a database other than the default, I get the following error: models.Car.DoesNotExist: Car matching query does not exist. Django Framework version is 4.1.1 Python version 3.8 models.py: from django.db import models class Person(models.Model): name = models.CharField(max_length=100, unique=True) class Car(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(Person, models.CASCADE) class Meta: order_with_respect_to = "owner" In settings.py under DATABASES the following is used: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db_other.sqlite3', } } This can be tested in the Django Shell using the following command python manage.py shell: >>> from models import Person, Car >>> carowner = Person.objects.using("other").create(name="carowner") >>> porsche = Car.objects.using("other").create(name="porsche", owner=carowner) >>> ferrari = Car.objects.using("other").create(name="ferrari", owner=carowner) >>> lamborghini = Car.objects.using("other").create(name="lamborghini", owner=carowner) >>> carowner.set_car_order([lamborghini.pk, ferrari.pk, porsche.pk], "other") >>> gnio = porsche.get_next_in_order() >>> gnio.name # Should print ferrari >>> gpio = porsche.get_previous_in_order() >>> gpio.name # Should print lamborghini -
how to handle line breaks with django and js
I store in my db.sqlite3 of django some patterns which can contain a line break (\n). On the /admin page you can still see them. But when I load the content now into the frontend, this is written in a line. But if I output the sentence in the console, I get the line break The following record is stored in the Django database as follows: Hello\nWorld <div id=response_1> </div> document.getElementById('response_1').innerHTML = responses[0] //Hello World console.log(responses[0]) // Hello World -
Django models with self create properties
Let's pretend that you're creating web application. You have users in your app and these users have collections of pictures, books and other. They can add to their collections items (accordingly books, pictures e.g.). Example of book fields: _author _title _desription But what if they want add another information about this book like preview picture, pages quantity, link and other information. How can i implement it with django models?? -
Forbidden (CSRF cookie not set.) but it is set by Axios in React (DRF)
Firstly, I'm getting csrf cookie by calling /auth/session/ endpoint then I'm setting header for csrf cookie, actual error occurs when I'm trying to login Request import axios from 'axios'; import Cookies from "universal-cookie"; const cookies = new Cookies(); const Login = () => { axios .get('http://localhost:8000/auth/session/') .then(({ data }) => { console.log(data) }) .catch((error) => { console.log(error); }); axios.defaults.xsrfHeaderName = 'X-CSRFToken' axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.headers.common['X-CSRFToken'] = cookies.get('csrftoken'); const onSubmit = object => { axios.post( 'http://localhost:8000/auth/login/', object, ) .then(res => { if (res.status === 201) alert('Successfully authorized') else Promise.reject() }) .catch(err => alert(err)) } actual request headers image Response Forbidden (CSRF cookie not set.): /auth/login/ news-board-web-1 | [16/Oct/2022 15:40:58] "POST /auth/login/ HTTP/1.1" 403 2870 response image Settings CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', 'http://localhost:3001', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_HEADERS = list(default_headers) + [ 'X-CSRFToken' ] CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"] CSRF_COOKIE_HTTPONLY = False CORS_ALLOW_CREDENTIALS = True For login I'm using standard rest framework login that works fine with Postman, but I can't find out the reason why it doesn't work with axios path('auth/', include('rest_framework.urls')), -
Django: id_field of model in url not working
I have the following problem: I have an app in which I want a view vocab/1 as a detail page for an entry. WHenever I browse to http://127.0.0.1:8000/vocab/ (displays all word entries (really ugly nothing yet :-D ) this works. Whenever I go for http://127.0.0.1:8000/vocab/1 I get TypeError at /vocab/1/ my vocab.views.py from django.http import HttpResponse from .models import Word # Create your views here. def index(request): return HttpResponse('Hi from landing page') def vocab(request): words = Word.objects.order_by('id') output = ([word for word in words]) return HttpResponse(output) def detail_vocab(request, word_id): return HttpResponse("You're looking at the word with id" % word_id) the vocab.urls.py from django.urls import path from . import views urlpatterns = [ #index path('', views.index, name='index'), #vocab path('vocab/',views.vocab, name='vocab'), #details ex: vocab/1 path('vocab/<int:word_id>/', views.detail_vocab, name='detail'), ] the site/urls.py from django.contrib import admin from django.urls import include,path urlpatterns = [ path('', include('vocab.urls')), path('admin/', admin.site.urls), ] my vocab.models.py: from django.db import models # Create your models here. class Word(models.Model): def __str__(self): return self.word_en word_en = models.CharField(max_length=50) word_indo = models.CharField(max_length=50) word_dt = models.CharField(max_length=50) word_id = models.IntegerField(default=0) Am I missing something? all the best, K -
Using both aria-hidden="true" and aria-labelledby attributes in the same field
I understand the functionality of both aria-hidden="true" attributes and aria-labelledby in the sense that the prior attribute hides the contents of an element and its child-elements from screen-readers (supposedly including aria-labelledby and aria-labelled), and that the latter attribute gives an element its accessible name based on another element's aria-label. However, I am faced by a contradiction in a Django course I am completing. https://youtube.com/clip/UgkxN1rhn70sw6fPvRdhpAFZv0KnPBz7J5-y (I have also attached a snippet of the uncompleted code below.) Here, the creator of the course includes both aria-hidden="true" attributes and aria-labelledby attributes simultaneously. According to what I understood, the inclusion of aria-labelledby makes no difference. So what is the point of including it? TLDR: Does the data of aria-labelledby still appear in screen readers when aria-hidden="true" or did the course creator make a mistake? <div class="modal" id="#myModal{{student.id}}" tabindex="-1" aria-labelledby=""> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> <span aria-hidden="true"></span> </button> </div> <div class="modal-body"> <p>Modal body text goes here.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary">Save changes</button> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> -
How to fetch GitHub repo contributions using python and more specifically celery
I was wondering how I can fetch the list of contributors using python and more specifically using celery. -
Django Rest Framework: Should I use renderer for JPEG?
I am currently building an api where I have to create api for image uploading. Stumbled upon different tutorials, I've found that some of them have used the JPEG Renderer while the others haven't. My question is when I should use a renderer. What may I miss if I don't use one? -
Icons from DigitalOcean spaces can't load with my Django settings
I am using Django summernote, but icons aren't showing, this is the structure of my digitalocean spaces : When it comes to Django settings, I pointed to the res folder with AWS_LOCATION, but am not sure if the path I provided is correct, I used : AWS_LOCATION = 'res/' I also enabled CORS in the DigitalOCean spaces section, but I am still getting this error : DevTools failed to load source map: Could not load content for https://fra1.digitaloceanspaces.com/guio_space/res/vendor/adminlte/css/adminlte.min.css.map: HTTP error: status code 403, net::ERR_HTTP_RESPONSE_CODE_FAILURE DevTools failed to load source map: Could not load content for https://fra1.digitaloceanspaces.com/guio_space/res/vendor/adminlte/js/adminlte.min.js.map: HTTP error: status code 403, net::ERR_HTTP_RESPONSE_CODE_FAILURE DevTools failed to load source map: Could not load content for https://fra1.digitaloceanspaces.com/guio_space/res/vendor/bootstrap/js/bootstrap.min.js.map: HTTP error: status code 403, net::ERR_HTTP_RESPONSE_CODE_FAILURE all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-solid-900.woff2 net::ERR_ABORTED 403 all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-regular-400.woff2 net::ERR_ABORTED 403 all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-solid-900.woff net::ERR_ABORTED 403 all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-regular-400.woff net::ERR_ABORTED 403 all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-solid-900.ttf net::ERR_ABORTED 403 all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-regular-400.ttf net::ERR_ABORTED 403 logo.png:1 -
how to Customize error message when Schema format is not matching with django Ninja?
``` @router.post("/addUser", response={200: responseStdr, 404: responseStdr,422: responseStdr}) def addUser(request, user: userRegister): try: return 200, {"status": 200, "isError": "True", "data": user, "msg": "user crée avec succès", "method": "POST"} except : return {"status": 201, "isError": "True", "data": "erreur format", "msg": "erreur", "method": "POST"} ``` I'm getting this error : ``` { "detail": [ { "loc": [ "body", "user", "last_name" ], "msg": "field required", "type": "value_error.missing" } ] } ``` How to send a custom message instead of this error when a field is not matching with the expected format ? -
HTML doesn't load all CSS properties
I am making a website using django and I need to edit some things on frontend using CSS but I don't know why CSS doesn't load all things I added. It loads some of the tags but rest just doesn't show at all here is the code. index.html: {% extends 'gym_app/base.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> {%load static%}{%block content%} <link rel="stylesheet" type="text/css" href="{% static 'css/index.css' %}" /> <link rel="script" href="{% static 'javascript/index.js' %}"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.css" /> </head> <body class="body"> <div class="container"> <div class="text-center"> <h1>Supreme</h1> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum, debitis!</p> </div> <!--Image slideshow--> <div class="container-slide"> <div class="swiper"> <!-- Additional required wrapper --> <div class="swiper-wrapper"> <!-- Slides --> <div class="swiper-slide"><img src="{% static 'images/gym_1.jpg' %}" alt=""></div> <div class="swiper-slide"><img src="{% static 'images/gym_1.jpg' %}" alt=""></div> <div class="swiper-slide"><img src="{% static 'images/gym_1.jpg' %}" alt=""></div> </div> <!-- If we need pagination --> <div class="swiper-pagination"></div> <!-- If we need navigation buttons --> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.js"></script> <script src="{% static 'javascript/index.js' %}"></script> <!--Ends--> <!--About section--> <div class="container"> <p class="h1 text-center">About us</p> <section class="row mb-5"> <img src="{% static 'images/gym_1.jpg' %}" alt="" class="col-7" style="height: 350px;"> <div class="col-5"> <p>Lorem ipsum … -
Heroku not deployingr: This error originates from a subprocess, and is likely not a problem with pip
I am trying to deploy a demo of my simple django app on heroku, but when I try to deploy the app, the following error occurs. pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. I reviewed the error and it turned out it is due to the version of pip, and I should downgrade it, but I don't know if I can change Heroku's pip version. So what should I do? Here is requirements.text: absl-py==0.12.0 altair==4.2.0 argon2-cffi==21.3.0 argon2-cffi-bindings==21.2.0 asgiref==3.5.2 astroid==2.5.1 asttokens==2.0.5 attrs==21.2.0 backcall==0.2.0 backports.entry-points-selectable==1.1.1 beautifulsoup4==4.9.3 bleach==5.0.0 blinker==1.4 bokeh==2.4.2 cachetools==5.2.0 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.9 click==8.0.3 colorama==0.4.4 commonmark==0.9.1 crypto==1.4.1 cvzone==1 cycler==0.11.0 debugpy==1.6.0 decorator==5.1.1 defusedxml==0.7.1 distlib==0.3.4 Django==4.1 entrypoints==0.4 executing==0.8.3 fastjsonschema==2.15.3 filelock==3.4.0 Flask==2.0.2 fonttools==4.29.1 gitdb==4.0.9 GitPython==3.1.27 gunicorn==20.1.0 idna==3.3 imageio==2.13.3 importlib-metadata==4.11.4 ipykernel==6.15.0 ipython==8.4.0 ipython-genutils==0.2.0 ipywidgets==7.7.0 isort==5.8.0 itsdangerous==2.0.1 jedi==0.18.1 Jinja2==3.0.3 jsonschema==4.6.0 jupyter-client==7.3.4 jupyter-core==4.10.0 jupyterlab-pygments==0.2.2 jupyterlab-widgets==1.1.0 keyboard==0.13.5 kiwisolver==1.3.2 lazy-object-proxy==1.6.0 lxml==4.9.0 MarkupSafe==2.0.1 matplotlib==3.5.1 matplotlib-inline==0.1.3 mccabe==0.6.1 mediapipe==0.8.9.1 mistune==0.8.4 MouseInfo==0.1.3 multitasking==0.0.10 mysql==0.0.3 mysql-connector==2.2.9 mysqlclient==2.1.0 Naked==0.1.31 nbclient==0.6.4 nbconvert==6.5.0 nbformat==5.4.0 nest-asyncio==1.5.5 networkx==2.6.3 nnfs==0.5.1 notebook==6.4.12 numpy==1.20.2 opencv-contrib-python==4.5.2.52 opencv-python==4.5.2.52 packaging==21.3 Panda3D==1.10.10 panda3d-gltf==0.13 panda3d-simplepbr==0.9 pandas==1.3.5 pandocfilters==1.5.0 parso==0.8.3 pickleshare==0.7.5 Pillow==8.4.0 pipenv==2022.1.8 platformdirs==2.4.0 plotting==0.0.7 prometheus-client==0.14.1 prompt-toolkit==3.0.29 protobuf==3.16.0 psutil==5.9.1 pure-eval==0.2.2 pyarrow==8.0.0 PyAutoGUI==0.9.53 pycparser==2.21 … -
Is it possible to sub-parametrize pytest parameters values?
I'm working on a DRF (REST API) project and I'm using pytest. Quite often I find myself writing almost identical test parameters and I've been wondering if there's something I'm missing. I haven't read the entire pytest docs, although I definitely did read the entire django docs chapter on tests (not very helpful in my case) and I've now spent a few hours trying to find a solution. Let's assume I have a view like this: from rest_framework import generics from myapp.permissions import IsStaff, IsAdmin class MessagesListView(generics.ListAPIView): permission_classes = [IsStaff | IsAdmin] # ... and for this view I wrote a test: import pytest from rest_framework.reverse import reverse_lazy from pytest_lazy_fixture import lazy_fixture class TestMessagesListViewPermissions: def get_response(self, client): url = reverse_lazy("api:messages-list") return client.get(url) @pytest.mark.parametrize( argnames=["client", "expected_response_status"], argvalues=[ pytest.param( "anonymous_client", status.HTTP_403_FORBIDDEN, ), pytest.param( "authenticated_client", status.HTTP_403_FORBIDDEN, ), pytest.param( "staff_client", status.HTTP_200_OK, ), pytest.param( "admin_client", status.HTTP_200_OK, ), ], ) def test__permissions(self, client, expected_response_status): # WHEN response = self.get_response(client) # THEN assert response.status_code == expected_response_status And there are 4 different client values, but 1+2nd and 3+4th result in the same response status code. As I said, it's a simplified example, but what if there are 10 parameters? What I'd like to be able to do is … -
How to replace the algorithm thingy in my edit profile page, with a decent bootstrapified input bar - Django
So I have an Edit profile page that looks like this: What I want is to replace this: algorithm: pbkdf2_sha256 iterations: 390000 salt: pZEUwO**************** hash: M7qIWG************************************** Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form. from under the Password column with a proper form that looks like the format of the Username, First Name, Last Name, etc. My views: class NormalUserEditView(generic.UpdateView): form_class = EditProfileFormNormal template_name = 'authentication/edit_normalprofile.html' success_url = reverse_lazy('profile') def form_valid(self, form): messages.success(self.request, f'Account Edit: Successful') return super().form_valid(form) def get_object(self): return self.request.user class PasswordsChangeView(PasswordChangeView): form_class = PasswordChangeForm success_url = reverse_lazy('profile') def form_valid(self, form): messages.success(self.request, 'Password Change: Successful') return super().form_valid(form) My urls: from django.urls import path from . import views from .views import UserEditView, NormalUserEditView, PasswordsChangeView from django.contrib.auth import views as auth_views urlpatterns = [ path('register', views.register_user, name='register'), path('login', views.login_user, name='login'), path('logout', views.logout_user, name="logout"), path('confirm_address_page', views.cap, name="confirm-address-page"), path('activate/<uidb64>/<token>', views.activate, name="activate"), path('edit_user_profile/', UserEditView.as_view(), name="edit-profile"), path('password/', PasswordsChangeView.as_view(template_name='authentication/change-password.html')), path('edit_profile/', NormalUserEditView.as_view(), name="edit-normalprofile"), path('profile', views.profile, name="profile"), ] My forms: from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm from django.contrib.auth.models import User from django import forms class RegisterUserForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) first_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) class … -
Why Django get result list from query_set too late?
I am studying about Django ORM. I couldn't get an answer from the search, but I'd appreciate it if someone could tell me the related site. My model is as follows. user1 has2 accounts, and 500,000 transactions belong to one of the accounts. class Account(models.Model): class Meta: db_table = 'account' ordering = ['created_at'] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account = models.CharField(max_length=20, null=False, blank=False, primary_key=True) balance = models.PositiveBigIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class AccountTransaction(models.Model): class Meta: db_table = 'account_transaction' ordering = ['tran_time'] indexes = [ models.Index(fields=['tran_type', 'tran_time', ]), ] account = models.ForeignKey(Account, on_delete=models.CASCADE) tran_amt = models.PositiveBigIntegerField() balance = models.PositiveBigIntegerField() tran_type = models.CharField(max_length=10, null=False, blank=False) tran_detail = models.CharField(max_length=100, null=True, default="") tran_time = models.DateTimeField(auto_now_add=True) The query time for the above model is as follows. start = time.time() rs = request.user.account_set.all().get(account="0000000010").accounttransaction_set.all() count = rs.count() print('>>all') print(time.time() - start) # 0.028000831604003906 start = time.time() q = Q(tran_time__date__range = ("2000-01-01", "2000-01-03")) rs = request.user.account_set.all().get(account="0000000010").accounttransaction_set.filter(q) print('>>filter') print(time.time() - start) # 0.0019981861114501953 start = time.time() result = list(rs) print('>>offset') print(time.time() - start) # 5.4373579025268555 The result of the query_set is about 3500 in total. (3500 out of 500,000 records were selected). I've done a number of things, such as setting offset to the result (rs) of query_set, … -
Semgrep: A scalable way of catching all cases in a multiline f-strings
I have some logs in my codebase that have multiline f-strings, such as: ... logger.error( f'...' f'...' f'...' f'...' f'...' f'...' ) And some only have two f'...'s on separate lines while others 3 f'...'s, and so on. I am currently duplicating patterns to catch such logs. For example: ... patterns: - pattern-either: - pattern: | logger.$METHOD( f'...' f'...' f'...' ) - pattern: | logger.$METHOD( f'...' f'...' f'...' f'...' f'...' ) Catch those with 3 and 5 f'...'s on multiple lines. I have to write another pattern for those with 4, 2 and so on. Is there a scalable way to capture all of these with fewer patterns? The current implementation won't scale as there might be logs with 6, 7, 8, 9 and so on multiline f-strings. -
Django orm subquery - in clause without substitution
I need to build a query using Django ORM, that looks like this one in SQL: select * from A where id not in (select a_id from B where ... ) I try to use such code: ids = B.objects.filter(...) a_objects = A.object.exclude(id__in=Subquery(ids.values('a__id'))).all() The problem is that instead of nested select Django generates query that looks like select * from A where id not in (1, 2, 3, 4, 5 ....) where in clause explicitly lists all ids that should be excluded, making result sql unreadable when it is printed into logs. Is it possible to adjst this query, so nested select is used? -
Как динамически обновлять данные на странице, по ходу выполнения кода в web приложении Django
Возможно ли по мере выполнения кода из цикла, передавать данные на страницу? При нажатии кнопки в форме, выполняется долгий процесс, хотелось бы отображать на странице ход выполнения данного процесса, а после выполнения, возвращать рендер с финальными результатами Я новичок в django, огромная просьба хотя бы подсказать примерно как это сделать, перерыл весь интернет в поиске решения, предполагаю, что нужно использовать вэбхуки, но как это реализовать не представляю Спасибо! index.html {% extends 'base.html' %} {% block content %} <form action="" method="post"> {% csrf_token %} <select name="employee_name"> <option selected="selected" disabled>ВЫБЕРИ СОТРУДНИКА:</option> <option value="сотрудник1">сотрудник1</option> <option value="сотрудник2">сотрудник2</option> <option value="сотрудник3">сотрудник3</option> </select> <input type="submit" value="Проверить"> </form> {% endblock %} views.py from django.shortcuts import render from .CRM import crm_driver def index(request): if request.POST: data = crm_driver.get_data(request.POST.get("employee_name")) return render(request, 'calculation/calculation.html', {"employee_name": str(request.POST.get("employee_name")).upper(), "file_count": data[0], "verified_count": data[1], "count_complited": data[2], "count_refusal": data[3], "count_order": data[4], "today_verified_count": data[5], "today_complited": data[6], "today_refusal": data[7], "count_today_order": len(data[8]), "today_order": data[8], "count_today_in_work": len(data[9]), "today_in_work": data[9], "renewal_full": data[10], "FOR_TODAY_renewal_full": data[11], "renewal_paid": data[12], "FOR_TODAY_renewal_paid": data[13], "sp_complited": data[14], "sp_order": data[15], "refusal": data[16], "count_error": len(data[17]), "error_list": data[17]}) else: return render(request, 'calculation/index.html') crm_driver.py import csv import time from .crm_module import init_driver, siebel_login, quote_search_init, get_quote_data, siebel_exit from .Refusal import failure_statistics from .utils import to_float complited_list = ['ОТПРАВЛЕНО', 'ОТПРАВЛЕН В СС', 'ОТПРАВЛЕНО В СС', … -
is there a way to run a function all the time in django?
Model.py class QualityControlCheck(models.Model): types_choices = ( ('PASS-FAIL', 'Pass-Fail'), ('MEASUREMENT', 'Measurement'), ('INSTRUCTION', 'Instruction'), ('TAKE A PICTURE', 'Take a Picture') ) quality_control_point = models.ForeignKey(QualityControlPoint, on_delete=models.CASCADE) pass_fail = models.CharField(max_length=50, null=True, blank=True) picture = models.FileField(upload_to='media/QCC/', null=True, blank=True) instruction = models.TextField(max_length=1000, null=True, blank=True) norm = models.FloatField(null=True, blank=True) tolerance_from = models.FloatField(null=True, blank=True) tolerance_to = models.FloatField(null=True, blank=True) note = models.TextField(max_length=1000, default=None, null=True, blank=True) status = models.CharField(max_length=50, default='To Do') mrv = models.ForeignKey(MaterialReceiptVoucher, on_delete=models.CASCADE, null=True, blank=True) returned = models.ForeignKey(MaterialReturnNote, on_delete=models.CASCADE, null=True, blank=True) production = models.ForeignKey(ProductionPlan, on_delete=models.CASCADE, null=True, blank=True) reject = models.ForeignKey(MaterialRejectionNote, on_delete=models.CASCADE, null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) next_check_date = models.DateTimeField(blank=True, null=True) def __str__(self): if self.quality_control_point.raw_product is not None: return str(self.id) + '-' + str(self.quality_control_point.raw_product) elif self.quality_control_point.spare_product is not None: return str(self.id) + '-' + str(self.quality_control_point.spare_product) elif self.quality_control_point.bom_product is not None: return str(self.id) + '-' + str(self.quality_control_point.bom_product) else: return self.quality_control_point.title next_check_date is checking for the current time in Views.py: current_time = timezone.now() if current_time >= next_check_date: doSomething() i manage to do this only in one View i would like to run this with every view i have? -
in pyecharts, how to bring line to front of bar when using bar.overlap(line)?
unfortunatly there is no tag for pyecharts in stackoverflow site , I'm not sure if I will get a helpful answer , hopefully I will get I have the following chart that consists of two bars and one line, I need 2 things : I need to bring the line to front of bar , its under the bar by default I need to shorten the value number to the nearest thousand (e.g 80,000 = 80K) code :- from pyecharts.charts import Bar, Gauge, Line from pyecharts import options as opts from pyecharts.globals import ThemeType bar = ( Bar(init_opts=opts.InitOpts(width='100%', theme=ThemeType.VINTAGE)) .add_xaxis(["Category-1" , "Category-2", "Category-3", "Category-4", "Category-5"]) .add_yaxis('No. Of Investments', [100,700,900,500,400,50], label_opts=opts.LabelOpts(is_show=False),) .add_yaxis('No. Of Investors', [24,65,30,41,88], label_opts=opts.LabelOpts(is_show=False),) .extend_axis( yaxis=opts.AxisOpts( name="Value", type_="value", name_textstyle_opts=opts.TextStyleOpts(font_size=14, font_weight='bold', font_family='Dubai') ) ) .set_global_opts(legend_opts=opts.LegendOpts(is_show=True , pos_right = 0, textstyle_opts = opts.TextStyleOpts(font_size=14, font_weight='bold', font_family='Dubai') ), yaxis_opts=opts.AxisOpts( name='Count', name_location='middle', name_gap=50, type_="value", axistick_opts=opts.AxisTickOpts(is_show=True), splitline_opts=opts.SplitLineOpts(is_show=True), axispointer_opts=opts.AxisPointerOpts(is_show=False), name_textstyle_opts=opts.TextStyleOpts( font_size=14, font_weight='bold', font_family='Dubai') ), xaxis_opts=opts.AxisOpts( type_="category", axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow"), name_textstyle_opts=opts.TextStyleOpts(font_size=14, font_weight='bold', font_family='Dubai') , axislabel_opts = opts.LabelOpts(font_family='Dubai' , rotate = 30, font_size= 11, ) ), tooltip_opts=opts.TooltipOpts( is_show=True, trigger="axis", textstyle_opts = opts.TextStyleOpts( font_family='Dubai') ) , toolbox_opts = opts.ToolboxOpts(is_show=True , pos_left= '5%', feature=opts.ToolBoxFeatureOpts( data_zoom = opts.ToolBoxFeatureDataZoomOpts(is_show=False) , data_view = opts.ToolBoxFeatureDataViewOpts(is_show=False) , brush=None ) ) ) ) line = ( Line() … -
Django - How to iterate queryset object in template
I am trying to developed quiz app in django class base view. here i am get all question in questions and render to template. i want access one by one questions using html next button. so suggest me any backend code required or by using javascript we can iterate? View.py -
The function get_form_kwargs doesn't work, it doesn't return anything
I have a CreateView and i want to save as a kwarg the user, and i don't understand what is wrong with my code. I wrote my get_form_kwargs in my create view(this is from my view.py): class ItemCreateView(CreateView): template_name = 'menus/form.html' form_class = ItemForm def form_valid(self, form): instance = form.save(commit=False) instance.user = self.request.user return super(ItemCreateView, self).form_valid(form) def get_form_kwargs(self): kwargs=super(ItemCreateView, self).get_form_kwargs() kwargs['user']=self.request.user return kwargs def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) context = { 'form' : form, 'var' : 'Add an Item' } return render(request, self.template_name, context) I introduced the init function in my form(this is my form.py): class ItemForm(forms.ModelForm): class Meta: model = Item fields = [ 'name', 'article', 'description', 'exceptions', 'bl', ] def __init__(self,*args, **kwargs): print(kwargs.pop('user', None)) super(ItemForm, self).__init__(*args, **kwargs) The problem is that the print from the init function returned None value. It should returned the user. I'm mentioning that I am logged in. I don't understand what is wrong here. Thanks in advance for your help !!! -
Django- get "parameters" from HTML form in views
I have a template which has this form: template.html <form action="{% url addcart %}" method="POST" class="btn-block"> {% csrf_token %} <input type="number" name="quantity" min="1" max="100"> <input type="submit" class="float-right btn btn-success form-control" value="Add To Cart"> </form> Now, I want to know how to implement the function "addcart()" in the views. How can I get the form variables?