Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Signature drawing for the form
For my application with Django, I want to make a signature drawing field after entering the necessary information in the form field. When I want to save and edit this form later, the signature drawn in that signature drawing place needs to be displayed again. I'm new to this and I have no idea how to do it, can you help with this? -
How to generate auto generate unique serial number by date and also It will be generate serial vise after delete in django
I have to generate serial number like TES-0922-1,TES-0922-2 and so on.... here TES is (company_lable) 0922 is (month and year) 1,2 is (serial number) I wish to generate unique number by date . If today is month 9 and year 22 and I am generating new data of this month then my serial number will be TES-0922-01. Also If I have serial numbers TES-0922-01,TES-0922-02,TES-0922-03 and If I am deleting TES-0922-01 from them. afterwards when I creating new data my serial number will be TES-0922-04 Also If I have serial numbers TES-0922-01,TES-0922-02,TES-0922-03,TES-0922-04 and If I am deleting TES-0922-01, TES-0922-04 from them. afterwards when I creating new data my serial number will be TES-0922-04 Note : I am saving that data in the database and handling them by django queryset. What I did is mentioned below but Its not working properly. Because I am counting my data by django queryset. views.py def sales_invoice(request): current_time = datetime.datetime.now() latest_year = current_time.year year=str(latest_year)[-2:] latest_month = current_time.month month="%02d" % (latest_month) company_label= Company_Setup.objects.get(id=request.session['company_id']) existing_label=Sales_Invoice.objects.filter(company=company_label).all() if not existing_label: gen_invoice_number=f"{company_label}-{month}{year}-1" else: total_sales = Sales_Invoice.objects.filter(company=company_label).all().count() + 1 gen_invoice_number=f"{company_label}-{month}{year}-{total_sales}" -
Difference between request.user vs. get_user(request) in Django?
I noticed there are two ways to get a user object from request (assuming user is already logged in and the session is valid): user = request.user user = get_user(request) where get_user() is imported from django.contrib.auth. What's the difference? get_user() seems to do a lot of validation for request session. Which is better? -
Several properties with the same type Django
I have two models class Manager(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class Project(models.Model): title = models.CharField(max_length=250, null=True, blank=True) work_statement = models.TextField(null=True, blank=True) contract_id = models.CharField(max_length=250, null=True, blank=True) note = models.TextField(null=True, blank=True) customer = models.CharField(max_length=250, null=True, blank=True) #executer = models.ManyToManyField(Manager) deadline = models.DateTimeField(null=True, blank=True) So there is logic I want Model Project to has several managers as executers but not all of them how can i do it? so for example: Project "N" can include two managers for execution i know that this way is not correct class Project(models.Model): title = models.CharField(max_length=250, null=True, blank=True) work_statement = models.TextField(null=True, blank=True) contract_id = models.CharField(max_length=250, null=True, blank=True) note = models.TextField(null=True, blank=True) customer = models.CharField(max_length=250, null=True, blank=True) executer1 = models.ForeignKey(Manager) executer2 = models.ForeignKey(Manager) deadline = models.DateTimeField(null=True, blank=True) -
Is celery-beats can only trigger a celery task or normal task (Django)?
I am workign on a django project with celery and celery-beats. My main use case is use celery-beats to set up a periodical task as a background task, instead of using a front-end request to trigger. I would save the results and put it inside model, then pull the model to front-end view as a view to user. My current problem is, not matter how I change the way I am calling my task, it always throwing the task is not registered in the task list inside celery. I am trying to trigger a non-celery task(inside, it will call a celery taskthe , using celery beats module, Below is the pesudo-code. tasks.py: @app.shared_task def longrunningtask(): res = APIcall.delay() return res caller.py: from .task import foo def dosomething(input_list): for ele in input_list: res.append(longrunningtask()) return res Periodical Task : schedule, created = CrontabSchedule.objects.get_or_create(hour = 1, minute = 34) task = PeriodicTask.objects.create(crontab=schedule, name="XXX_task_", task='app.caller.dosomething')) return HttpResponse("Done") Nothing special about the periodical task, but This never works for me. It errored that not detected tasks or not registered tasks if I do not make the dosomething() as celery task. Problem is I do not want to make the caller function a celery task, the … -
In Django how to add login required for entire app?
Suppose I have 3 apps in my Django website app_1, app_2, app_3. app_1 and app_2 can access any user, but for app_3 I want the user should log in. Using login_required I can achieve this. But I have more than 30 views and urls. I don't want to write login_required decorator on every view function. Is there any other shortcut? -
How can I "copy" some dependencies to my project
I'm following a great course (Django/react ecommerce on udemy), however the bootstrap version that they're using is really old and a lot of stuff doesn't work on newer versions, I saw they dependencies on Github but all are conflicting when I'm trying to install by npm, I can try and force some but it'll probably make things worse. There's a way I "copy/paste" their package.json and run npm install or something to get the same dependencies on my project? I can refactor everything to newer versions of course but that'll take triple the time to finish the course. -
Django "ProgrammingError at /create-post" usnig heroku postgres as database host
I am trying to create a blog website in django using postgres with heroku in the cloud. When trying to submit the post using forms from django I get this error "ProgrammingError at /create-post column "title" of relation "main_post" does not exist LINE 1: INSERT INTO "main_post" ("author_id", "title", "description"... " This is my view for creating posts from django.shortcuts import render, redirect from .forms import RegisterForm, PostForm from django.contrib.auth.decorators import login_required from django.contrib.auth import login, logout, authenticate @login_required(login_url="/login") def home(request): return render(request, 'main/home.html') @login_required(login_url="/login") def create_post(request): if request.method =='POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect("/home") else: form = PostForm() return render(request, 'main/create_post.html', {"form": form}) This is my forms.py file from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Post class RegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ["username", "email", "password1", "password2"] class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "description"] This is my Post model from django.db import models from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + "\n" + self.description … -
TemplateSyntaxError when tried to manage page on Django admin backend
I am new on Django CMS and i have experience with error when try to add a page or page type trough backend site. Below is the error i got. I am using Django 4.1.1 version, Django-cms 3.11.0. Any help or suggestion will be appreciated. TemplateSyntaxError at /admin/cms/pagetype/add/ Invalid block tag on line 101: 'page_submit_row', expected 'endif'. Did you forget to register or load this tag? Request Method: GET Request URL: http://localhost:8000/admin/cms/pagetype/add/ Django Version: 4.1.1 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 101: 'page_submit_row', expected 'endif'. Did you forget to register or load this tag? Exception Location: C:\project_data\python\myblog\env\lib\site-packages\django\template\base.py, line 557, in invalid_block_tag Raised during: cms.admin.pageadmin.add_view Python Executable: C:\project_data\python\myblog\env\Scripts\python.exe Python Version: 3.10.7 Python Path: ['C:\\project_data\\python\\myblog\\myblog', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\python310.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\Rosidin\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0', 'C:\\project_data\\python\\myblog\\env', 'C:\\project_data\\python\\myblog\\ and here is my settings.py SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-rt-cu)&d604(@1pmfi!@z^_etwo(jvm!k#&z3&yxb62ll+gz1#' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] X_FRAME_OPTIONS = 'SAMEORIGIN' SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'simpleblog', 'sekizai', 'django.contrib.sites', 'cms', 'menus', 'treebeard', ] 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', … -
ElastiCache(redis) cluster mode enabled with django
I configured ElastiCache redis with cluster mode enabled. I want to connect ElastiCache with local Django. So I configured bastion host. I connected ElastiCache(non-cluster mode) with local Django. I tried cache.set(), cache.get(). It's OK. I installed 'Django-redis-cache' and 'settings.py' is like that. CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': 'localhost:6379', } } But I have problem when I connect ElastiCache(cluster mode) with django. I tried tunneling with ElastiCache configuration endpoint. When I use the same 'settings.py', error message is like that. 'SELECT is not allowed in cluster mode' So, I changed 'settings.py'. CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': 'localhost:6379', 'OPTIONS': { 'DB': 0 }, } } And then, error message is like that. 'MOVED 4205 xx.xx.xx.xxx:6379' What I have to do? There are no example which connect ElastiCache(cluster mode) with Django. -
django how to update item
I have postgres function DECLARE office_lastnumber TEXT; BEGIN UPDATE curriculum.clearance_item SET resolve=TRUE,resolve_date=now() where cl_itemid=f_cl_itemid; INSERT INTO curriculum.transaction_log (cl_itemid,trans_desc,trans_recorded) VALUES (f_cl_itemid,'Resolved Clearance Item',now()); RETURN f_cl_itemid; END; I have this list of items, cut some rows so it's easier to read <table style="width:100%"> <tr> <th>cl_itemid</th> <th colspan="2">Actions:</th> </tr> {%for data in data%} <tr> <td>{{data.cl_itemid}}</td> <td><a href="{% url 'update' data.cl_itemid %}">Update</a></td> </tr> {%endfor%} </table> And views.py def update(request): if request.method == "POST": cursor = connection.cursor() resolve_item = # what to put here cursor.execute("select resolve_clearance_item('"+resolve_item+"')") return render(request, 'clearance/index.html') else: return render(request, 'clearance/index.html') cl_itemid OSA2022-2023 | update DORM2022-2023| update How can def update knows if I click update (ex.OSA2022-2023) then it puts in resolve_item and run the function -
reverse_lazy not redirecting to the correct link (adding a suffix)
so this is my class based function class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = 'app/add_comment.html' def form_valid(self, form): list_obj = List.objects.get(slug = self.kwargs['slug']) form.instance.list = list_obj return super().form_valid(form) success_url = reverse_lazy("app:list_detail", kwargs={'slug': List.slug}) once the comment is submitted I wanna go back to detailview page which is http://127.0.0.1:8000/home/list/best-bangla-art-films2022-09-09-0505595309260000/ but its taking me to http://127.0.0.1:8000/home/list/best-bangla-art-films2022-09-09-0505595309260000/comment/ any way i can solve this? in my urls (I have excluded irrelevant paths) app_name = "app" urlpatterns = [ path('', views.HomeView.as_view(),name='home'), path('list/<slug:slug>/', TheirDetailView.as_view(),name='list_detail'), path('list/<slug:slug>/comment/',AddCommentView.as_view(),name="add_comment"), ] -
Viewing or Editing their own Profile who is currently login
I am editing profile using Django framework. The problem lies where the user login can see the profile of other user when they change the id in the web address. Could someone help me so that I can only view the user's profile who is login and if they change the id they will receive an error. Thanks Edit User Profile @login_required(login_url = 'signin') @user_passes_test(check_role_super) def sa_profile_edit(request, user_id=None): user = get_object_or_404(User, pk=user_id) user_profile = get_object_or_404(userMember, pk=user_id) if request.method == 'POST': form = UserFormAdmin(request.POST or None, instance=user) form_profile = MemberForm(request.POST or None, instance=user_profile) else: form = UserFormAdmin(instance=user) form_profile = MemberForm(instance=user_profile) context = { 'form': form, 'user': user, 'form_profile': form_profile, 'user_profile': user_profile } return render(request, 'pages/sa_editProfile.html', context) If role is super def check_role_super(user): if user.role == 3: return True else: raise PermissionDenied Model class User(AbstractBaseUser): MEMBER = 1 ADMIN = 2 SUPERADMIN = 3 ROLE_CHOICE = ( (MEMBER, 'Member'), (ADMIN, 'Admin'), (SUPERADMIN, 'Super Admin') ) ACTIVE = 1 DELETED = 2 DEACTIVATED = 3 STATUS = ( (ACTIVE, 'Active'), (DELETED, 'Deleted'), (DEACTIVATED, 'Deactivated') ) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, default="Some String") last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) mobile_number = models.CharField(max_length = 100, db_index=True, null = True, … -
Return newly created object after creation with ModelViewSet
We have a modelViewset: class ObjectViewSet(viewsets.ModelViewSet): serializer_class = MyObjectSerializer def perform_create(self, serializer): ... def perform_update(self, serializer): ... def perform_destroy(self, instance): ... But perform_create doesn't return the newly created object which means the 201 response only contains a few random fields that were specified during creation and not the whole new object. Is there some special way to get the object without overriding the .create() call? It seems like returning the new object is expected behavior, so I'm worried I'm doing something wrong here. -
Django. Infinite Scroll on Scrollable Table is not working
I have an scrollable table in one of my templates defined like this: <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/infinite.min.js' %}"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], }); </script> ... more template ... <div id="table-div" style="overflow: scroll; height: 500px;"> <table class="table" id="sale_orders" style="margin-top: 10px; font-size: 10px;"> <form class="container py-3" method="GET"> <thead> <tr> <th scope="col" class="order_header">Header 1</th> <th scope="col" class="order_header">Header 2</th> <th scope="col" class="order_header">Header 3</th> <th scope="col" class="order_header">Header 4</th> <th scope="col" class="order_header">Header 5</th> <th scope="col" class="order_header">Header 6</th> <th scope="col" class="order_header">Header 7</th> <th scope="col" class="order_header">Header 8</th> <th scope="col" class="order_header">Header 9</th> <th scope="col" class="order_header">Header 10</th> <th scope="col" class="order_header">Header 11</th> <th scope="col" class="order_header">Header 12</th> </tr> </thead> <tbody class="infinite-container"> {% for s in sales %} <tr class="infinite-item"> <td scope="row"><span class="badge badge-info">{{s.number}}</span></td> <td scope="row">{{s.client_name}}</td> <td scope="row">{{s.comuna}}</td> <td scope="row">{{s.get_total_weigth}}</td> <td scope="row">{{s.get_total_cubic_cm}}</td> <td scope="row">{{s.get_total_area}}</td> <td scope="row">{{s.get_total_amount}}</td> <td scope="row">{{s.get_total_items}}</td> <td scope="row">{{s.product_fam}}</td> <td scope="row">{{s.deliver_date|date:"d/m/Y"}}</td> <td scope="row"> {% if s in loadedOrders %} <a class="btn btn-danger update-cart" data-load="{{initLoad.id}}" data-order="{{s.id}}" data-action="remove"> <i class="fa fa-download" aria-hidden="true"></i> </a> {% else %} <a class="btn btn-success update-cart" data-load="{{initLoad.id}}" data-order="{{s.id}}" data-action="add"> <i class="fa fa-upload" aria-hidden="true"></i> </a> {% endif %} </td> <td scope="row"> {% if s in loadedOrders %} <a data-toggle="modal" data-target="#lines_info_{{s.id}}"> <input type="button" name="partial_selection" value="Selección parcial" id="button{{s.id}}" class="btn btn-warning"> </a> {% else %} … -
Django allauth No Reverse Match
Django allauth fails when using a custom user model with the email as the primary key, I learnt about this when I tried to test the password change functionality. Reverse for 'account_reset_password_from_key' with keyword arguments '{'uidb36': 'mgodhrawala402@gmail.com', 'key': 'bbz25w-9c6941d5cb69a49883f15bc8e076f504'}' not found. 1 pattern(s) tried: ['accounts/password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/$'] I don't mind going into the code to fix this issue, since my application is still under development, I can still change authentication incase anyone has any suggestions. -
Django Form-Model issue;
I am having trouble working with models and forms in Django. A little clarification and help will be highly appreciated! I am really confused because I do not see the form in my html url page. I see everything else but not the form. I assume, I'm missing something. This is my forms.py from django import forms from .models import TwitterContainer class TwitterUpdateForm(forms.ModelForm): class Meta: model = TwitterContainer fields = ["Twitter_API_key", "Twitter_API_key_secret", "Twitter_API_token", "Twitter_API_token_secret"] This is my models.py from django.db import models from django.contrib.auth.models import User class TwitterContainer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Twitter_API_key = models.fields.CharField(max_length=100) Twitter_API_key_secret = models.fields.CharField(max_length=100) Twitter_API_token = models.fields.CharField(max_length=100) Twitter_API_token_secret = models.fields.CharField(max_length=100) def __str__(self): return f'{self.user.username} Twitter Container' This is my views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import TwitterUpdateForm @login_required def twitter(request): tw = TwitterUpdateForm(request.POST, instance=request.user) if tw.is_valid(): tw.save() messages.success(request, f'NICE!') return redirect ('home') else: tw = TwitterUpdateForm(request.POST, instance=request.user) context = {'tw': tw} return render(request, 'twitter_container/twitter_container.html', context=context) And last but not least, this is my html file. {% extends 'home/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset="form-group"> <legend class="border-bottom mb-4">Profile Information</legend> {{ u_form|crispy }} {{ p_form|crispy … -
Not able to run local server for postgresql db on Django on a M1 Max Chip Mac after successfully installed psycopg2 and psycopg2-binary
I have a M1 Max Mac(released in October 2021), and installed Django 4.1.1. I was trying to have my Django app connected to a PostgreSql database I created under DATABASES in settings.py. Successfully installed psycopg2-binary using pip3 install psycopg2-binary. In ENGINE I have django.db.backends.postgresql_psycopg2. When I run python3 manage.py runserver, I kept getting this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/hahaha/codingProjects/django/env/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> import psycopg2 as Database File "/Users/hahaha/codingProjects/django/env/lib/python3.9/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/hahaha/codingProjects/django/env/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 0x0002): symbol not found in flat namespace (_PQbackendPID) I was following the step from here to tackle the issue and then got You are using macOS 12. We do not provide support for this pre-release version. You will encounter build failures with some formulae. and since then no success. Some guidance needed -
tailwindcss config with django
I can't figure out how to config tailwindcss with django. I might just be doing the tailwind side wrong but I know I've configured my django static files correctly. I've watched every video I can find and none of them address my specific problem. An explanation of how tailwind config works on a low level would also be helpful so I could diagnose the problem myself. thanks. error message file structure and config file -
How to conditionally remove form field=required
It's simple to require a field based on the state of another: class FooForm(forms.Form) foo = forms.BooleanField() bar = forms.CharField(required=False) def clean(self): if self.cleaned_data.get('foo') and not self.cleaned_data.get('bar'): raise forms.ValidationError('With foo you must have bar') How can I do the reverse and remove a field requirement instead? E.g. class FooForm(forms.Form) foo = forms.BooleanField() bar = forms.CharField(required=True) def clean(self): if not self.cleaned_data.get('foo'): # No foo, no bar required del bar.required?? -
pytest -n auto + mariadb + m1 mac too slow
Issue Running pytest -n auto on my system with mariadb is taking significantly longer the running pytest Image of result and time System specs System specs Package versions mariadb Ver 15.1 Distrib 10.8.3-MariaDB python 3.9.6 pytest 7.1.3 MariaDB config file [client] port = 3306 socket = /tmp/mysql.sock [mysqld] port = 3306 socket = /tmp/mysql.sock back_log = 50 max_connections = 100 wait_timeout = 256 max_connect_errors = 10 table_open_cache = 2048 max_allowed_packet = 16M binlog_cache_size = 512M max_heap_table_size = 512M read_buffer_size = 64M read_rnd_buffer_size = 64M sort_buffer_size = 64M join_buffer_size = 64M thread_cache_size = 8 thread_concurrency = 8 thread_stack = 240K query_cache_size = 128M query_cache_limit = 2M ft_min_word_len = 4 default-storage-engine = InnoDB transaction_isolation = REPEATABLE-READ tmp_table_size = 512M log-bin=mysql-bin binlog_format=mixed slow_query_log long_query_time = 2 server-id = 1 # INNODB options innodb_buffer_pool_size = 4G innodb_buffer_pool_instances = 8 innodb_data_file_path = ibdata1:10M:autoextend innodb_write_io_threads = 8 innodb_read_io_threads = 8 innodb_thread_concurrency = 16 innodb_flush_log_at_trx_commit = 1 innodb_log_buffer_size = 1GB innodb_change_buffering = all innodb_change_buffer_max_size = 25 innodb_log_file_size = 512M innodb_log_files_in_group = 3 innodb_max_dirty_pages_pct = 90 innodb_lock_wait_timeout = 256 [mysqldump] quick max_allowed_packet = 50M [mysql] no-auto-rehash [mysqlhotcopy] interactive-timeout [mysqld_safe] open-files-limit = 8192 Additional info All packages and apps are running natively and not through rosetta -
django autofil with the pk page
I would like to add documents to an employee's profile in a form but I would like the form to automatically select the id or the (pk) of the employee's page, anyone have the solution? view.py def createDocument(request): forms = documentForm() if request.method == 'POST': forms = documentForm(request.POST, request.FILES) if forms.is_valid(): forms.save() return redirect('/employe') context = {'forms':forms} return render(request, 'accounts/document_form.html', context) add document form -
strptime() argument 1 must be str, not DeferredAttribute
I am heaving trouble here, am making a travel and visa website, am trying to make sure we know each appointment 10 days in advance. So I made a model property that would help me compare dates, but am having trouble error after error here is the model field class customer(models.Model): first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') biometry_date = models.DateField(blank=True, default='', null=True) @property def is_due(self): datetime_object = datetime.strptime(Profile.biometry_date, '%Y-%m-%d') t2 = datetime.now().date() t3 = timedelta(days=30) return datetime_object - t2<= t3 and in the Html template {% if customer.is_due %} <td class="text-right"> <span class="badge badge-danger">{{ profile.biometry_date }}</span> </td> {% else %} <td>{{ customer.biometry_date }}</td> {% endif %} Please help me Thanks -
asyncio.create_task() is not running asynchronously in async view function
I'm creating an async function to upload a video. The goal is to run the video upload asynchronously in the background without making the user wait. The user will be redirected to another page while the video is uploading. Following instructions in Python's asyncio docs, I'm using create_task() as that seems to be the simplest solution. In the following code, it works but it is not running asynchronously. HttpResponseRedirect is not running until after the video is fully uploaded. I also inserted 2 lines to check whether upload_video() is running asynchronously and it is. print('before') and print('after') are both printed to the console before the upload_video function completes. However, the final HttpResponseRedirect() does not run until all the code has been executed. async def my_async_func(request): if request.method == 'POST': video = request.FILES['video'] print('before') asyncio.create_task(upload_video(video)) print('after') return HttpResponseRedirect(... somewhere) async def upload_video(video): ... Basically despite all the async syntax & logic I wrote, the function is still running like a typical synchronous django view function. Why is this? What do I need to change to make upload_video() run asynchronously and return HttpResponseRedirect() without waiting? P.S. I also tried replacing create_task() with ensure_future() but it gave me the same result - the … -
Display a product whose ID is passed as a parameter
I would like to retrieve the product whose 'id' is passed as a parameter, how do I do this? For example here I passed the id equal to 1 Note I don't use a model but a dictionary def cart_add(request, id): dico={"produits":[{'id':1,'name':'pomme de terre','price':1250}]} mes_produits=dico['produits'] cart = Cart(request) mes_produits['id']=id product=mes_produits['id'] cart.add(product=product) return render(request, 'cart/cart_detail.html') i get this error : list indices must be integers or slices, not str