Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django- disallow url in robots.txt that contains variable [duplicate]
In my App I use an API to handle likes for blog posts. The urls are structured like path('post/<int:pk>/<slug:slug>/', views.DetailPostView, name='post-detail'), path('post/<int:pk>/like', PostLikeToggle.as_view(), name='like-toggle'), path('api/post/<int:pk>/like', PostLikeAPIToggle.as_view(), name='like-api-toggle'), The issue is google search console is giving me errors because it is trying to index the likes url and not the true url. How would I prevent the likes URL's from being index by google as I cannot find a way to pass variables in robots.txt or is there a different way to prevent these pages from being indexed. Update: Based on the suggested post I'm just a bit confused on how to implement this. Is it just as simple as Disallow: /*/like Would this block a url such as /post/999/test/unsportsmanlike/foo Updated: I discovered the google robots.txt Tester and was able to determine that the above query works -
django - server is slow to render response, how to manage user experience
My django app is responding slowly on some pages. While I'm working on improving the query efficiency, indexing on the db, etc, my question is how to manage the user experience. What I think is to run some kind of waiting icon, but my research only finds js that works on page loading delays once the browser receives the new page (e.g some element within the document takes time to present). I'm asking about after the user clicks on a url, the message goes off to the server, and before the server responds with a page. The browser shows the "old" page while the server churns away generating the new page. The only clue the user has that something is processing is the "stop/refresh" icon in the url bar is an "x" (in firefox). Are there any ideas, standard approaches, or solutions on how to approach the user experience while the next page is being "resolved/generated?" I guess I could move the offending elements to an API so the response comes more quickly and the do the "working" icon while the page finishes loading. But, suppose that's not something we'd like to do if possible (at least right now). Thanks … -
WebSocket connection is not return any data?
I run this code the handshake and connection work fine but I don't get any results after I run the client.even though the code is working perfectly without any issues. is there any idea to fix the problem? note: I'm using graphql and Django framework in my project import asyncio import graphene from channels.routing import ProtocolTypeRouter, URLRouter class Query(graphene.ObjectType): hello = graphene.String() @staticmethod def resolve_hello(obj, info, **kwargs): return "world" class Subscription(graphene.ObjectType): """Channels WebSocket consumer which provides GraphQL API.""" count_seconds = graphene.Float() async def resolve_count_seconds(root, info): for i in range(10): yield i await asyncio.sleep(1.) schema = graphene.Schema(query=Query, subscription=Subscription) class MyGraphqlWsConsumer(channels_graphql_ws.GraphqlWsConsumer): """Channels WebSocket consumer which provides GraphQL API.""" schema = schema async def on_connect(self, payload): pass application = channels.routing.ProtocolTypeRouter({ "websocket": channels.routing.URLRouter([ django.urls.path("graphql/", MyGraphqlWsConsumer.as_asgi()), ]) }) ASGI_APPLICATION = 'graphql_ws.urls.application' client: from graphql_client import GraphQLClient ws = GraphQLClient('ws://localhost:8000/graphql/') def callback(_id, data): print("got new data..") print(f"msg id: {_id}. data: {data}") query = """ subscription { countSeconds } """ sub_id = ws.subscribe(query, callback=callback) -
Since django 4.1, templates are cached with DEBUG=True. Is this solution right?
As described in the documentation, since 4.1 the default behavior for template loading changed drastically. If I understand it right, until 4.0 it worked like this: With DEBUG enabled, the templates are loaded in every request, therefore if you keep making changes and reloading while working on a template, you always see the latest version. With DEBUG disabled, the templates are cached when initializing the application, therefore you can only see changes in your templates if you also restart the application. That way, the template caching was seamlessly enabled in production which is great. Now this ticket proposal was included and, if I get it correctly, the template loading method must be specified and it's not anymore tied to DEBUG setting, AND, by default are cached. We want the original behavior so the frontend developer can see the changes without having to restart the app, and we also want the production deployment to have the caching enabled, so we did this: develop_loaders = [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ] production_loaders = [ ("django.template.loaders.cached.Loader", [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", "path.to.custom.Loader", ]) ] TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ "templates", ], "OPTIONS": { "context_processors": [ "maintenance_mode.context_processors.maintenance_mode", "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "wagtail.contrib.settings.context_processors.settings", ], "loaders": develop_loaders … -
searchable and able to sleelct all options in Django
How can I make a form that I can do these with: 1_ seaerchable choice field like cities. 2_a button that make me able to select all of cities. -
NoReverseMatch , Reverse for 'profilepage' with arguments '('',)' not found. 1 pattern(s) tried: ['profilepage/(?P<pk>[^/]+)/\\Z']
def profilki(request): profilki = profile.objects.all() context = {'profilki':profilki } return render(request,'base/profilki.html',context) def profilepage(request,pk): user = Trainingvalue.objects.get(id=pk) trainingplan = Trainingvalue.objects.all() profilepage= profile.objects.get(id=pk) user_training= Trainingvalue.objects.filter(user=profilepage.user) context ={‘user_training’:user_training,‘user’:user,‘profilepage’:profilepage, ‘trainingplan’:trainingplan,} return render(request, 'base/profilepage.html' , context) url : path (‘profilepage/str:pk/’,views.profilepage, name=“profilepage”) profilepage in context profile page has an attribute id profilepage.id entity does not provide value - yet i can access it through the borwser… so technically this should work in html template: profile i get error: Reverse for 'profilepage' with arguments '('',)' not found. 1 pattern(s) tried: ['profilepage/(?P<pk>[^/]+)/\\Z'] -
Why do I get MIME type error on Django/React app when loading css/js from Aws?
So I deployed a Django-Rest/React app on Heroku where I serve my static and media files on AWS S3 buckets. After pushing to Heroku and accessing the API URL or admin URL everything works fine but when I try to access my React URLs I get a MIME type error. On the network tab of developer tools, I get status 301 on my JS and CSS file. And in the console I get: Refused to apply style from 'https://app.herokuapp.com/static/css/main.9d3ee958.css/' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. app.herokuapp.com/:1 Refused to apply style from 'https://app.herokuapp.com/static/css/main.9d3ee958.css/' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. app.herokuapp.com/:1 Refused to execute script from 'https://app.herokuapp.com/static/js/main.3b833115.js/' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Even though the URL above is correct and I do have those files in my bucket. Here are my production settings: from decouple import config import django_heroku import dj_database_url from .base import * SECRET_KEY = config('SECRET_KEY') DEBUG = False ALLOWED_HOSTS = ['*'] ROOT_URLCONF = 'portfolio.urls_prod' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'frontend/build') ], … -
how to reverse fetch data in django models
I am working on a project and stuck somewhere to fetch the data child model which has a foreignkey of parent model. this is how my model looks like class Projects(models.Model): project_name = models.CharField(max_length=100,null=False) class ProjectTask(models.Model): project_id = models.ForeignKey(Projects,on_delete=models.CASCADE,null=False) class TaskBlockers(models.Model): task_id = models.ForeignKey(ProjectTask,on_delete=models.CASCADE,null=False,related_name='task_id_related') blocker = models.CharField(max_length=100,null=False) now what I want is to get all the blockers under a projectTask which has a projectid = something. ProjectTask.objects.filter(project_id=1) this will give a queryset right? and for each element in a queryset i want the blocker from TaskBlockers table. can you tell me how we can achieve this? Thanks for your help. -
django project search bar
I'm trying to implement a search bar in my application I use an API to retrieve product data then I search by code product, But after searching it does not display the product found Views.py def search(request): code=request.GET.get('search') url='http://myAPI/Product/GetProducts' x=requests.post(url) content=x.json() all_products=content['products'] selected_product= next((item for item in all_products if item['code']== code),None) if selected_product!= None: product=selected_product context={'product':product} return render(request,'cart/search.html',context) search.html <h3>Results:</h3> {% for search in product %} {{search.code}} {{search.designation}} {% endfor %} And I noticed at the level of the url of my browser, that there is no value for action (http://127.0.0.1:8000/cart/search/?search=or21&action= ) Here is the form <form method="GET" action="/cart/search/"> <input type="search" name="search" placeholder="Exemple name product"> <button class="btn waves-effect waves-light" type="submit">Search <i class="material-icons right">search</i> </button> </form> -
Django breadcrumb html tag define list in include tag
I want to for loop the names with bclist in breadcrumb.html {% include 'breadcrumb.html' with bcTitle=category.name bcList=["test","tester"] %} breadcrumb.html: {% for i in bcList %} <li class="breadcrumb-item" aria-current="page">{{ i }}</li> {% endfor %} -
I'm doing the migration, but the table is not created in the database
When I do the migration, I get the following message in the terminal: Migrations for 'bookList': bookList/migrations/0001_initial.py: Create model bookList And then I run the migrate command: Operations to perform: Apply all migrations: admin, auth, bookList, contenttypes, sessions When I look at mysql, a table named books does not appear. I've included the contents of my models.py file below: from django.db import models # Create your models here. class BookList(models.Model): site_name = models.TextField() site_id = models.TextField() image = models.TextField() book = models.TextField() author = models.TextField() publisher = models.TextField() price = models.TextField() link = models.TextField() category_name = models.TextField() category_id = models.TextField() class Meta: managed = False db_table = 'books' The contents of my 0001_initial.py file are as follows: # Generated by Django 4.1.1 on 2022-09-26 13:17 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='BookList', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('site_name', models.TextField()), ('site_id', models.TextField()), ('image', models.TextField()), ('book', models.TextField()), ('author', models.TextField()), ('publisher', models.TextField()), ('price', models.TextField()), ('link', models.TextField()), ('category_name', models.TextField()), ('category_id', models.TextField()), ], options={ 'db_table': 'books', 'managed': False, }, ), ] What do I need to do to be able to view my books table in mysql? -
Mongo update array of nested dict in Django
I'm trying to update a data but I'm facing the issue because it's nested form some fields are already present in the database I have fetched them and stored them in the DF variable the existing data structure looks like this { "created_by_id":122, "updated_by_id":123, "farm_area": [ { "area_id": 1, "area_name": "Area 1", "area_acerage": 4, "zone_latest_id": 1, "zone_name": "test zone", "zone_acerage": 2, "area_zone":[ { "zone_acerage":0.3 } ] "device_info":[ { "device_id":232, "device_type":"sensor" } ] }, { "area_id": 2, "area_name": "Area 2", "area_acerage": 4, "area_structure_type": "polyhouse" } ] } and I am trying this existing data by sending new data which { "created_by_id":122, "updated_by_id":123, "farm_area": [ { "area_id": 1, "area_name": "Area 1", "area_acerage": 4, "zone_latest_id": 1, "zone_name": "test zone", "zone_acerage": 2, "area_zone":[ { "zone_acerage":0.3 } ] "device_info":[ { "device_id":232, "device_type":"sensor" } ] }, { "area_id": 2, "area_name": "Area 2", "area_acerage": 4, "area_structure_type": "polyhouse", "area_zone":[ { "zone_acerage":0.3, "zone_name":"Test Zone" } ] "device_info":[ { "device_id":232, "device_type":"sensor" } ] } ] } But every time I run this command collection.update_one({"_id": ObjectId(str(kwargs['pk']))}, {"$set": request.data}, upsert=True) The data is getting replaced by the new one and due to this I'm losing some of my columns from the database But I'm looking for the output in which both of … -
Django - RecursionError: maximum recursion depth exceeded while calling a Python object
I came across an error that was poorly explained when I wanted to customize the magic str function of my "ApiCall" model. My Model : HOME_PAGE = 1 CONSUMPTION_PAGE = 2 PROFILE_PAGE = 3 ROUTES = ( (HOME_PAGE, "Page d'accueil"), (CONSUMPTION_PAGE, "Page de consommation"), (PROFILE_PAGE, "Page de profil"), ) class ApiCall(TimeStampedModel): user = models.ForeignKey(MobileUser, on_delete=models.CASCADE) route = models.PositiveSmallIntegerField('Page consultée', choices=ROUTES) def __str__(self): return f"Appel API du {self.user.phone} le {self.created_at.strftime('%d/%m/%Y %H:%M')} sur la page {self.get_route_display}" Error : RecursionError: maximum recursion depth exceeded while calling a Python object -
Location based recomendation on user location Django
I'm developing an e-commerce and each product has a location. Through the user's location, I want to recommend products from the same city as the user. How can I get the location of the authenticated and anonymous user? for the backend to do what I need -
Calling Ajax from django template fails with error: Field 'id' expected a number but got 'populate_sections'
I have one URL in urls.py file as given below:- urlpatterns = [ ........ path('edit_student/<student_id>', views.edit_student, name="edit_student"), path('populate_sections', views.populate_sections, name="populate_sections"), .......... ] In views.py file edit student function is defined as follows: @login_required def edit_student(request, student_id): form = UpdateStudentForm() context = { "form": form } return render(request, "edit_student.html", context) Now the template edit_student.html has a Ajax call:- $("#id_class_name").change(function(){ var class_name = $(this).val(); $.ajax({ url: 'populate_sections', type: 'GET', data: {class_name:class_name}, dataType: 'json', success: (data) => { $("#id_section_name").empty(); for( var i in data.context){ $("#id_section_name").append("<option value='"+data.context[i].id+"'>"+data.context[i].name+"</option>"); } } }); }); The views.py file function populate_section is declared as follows:- @login_required def populate_sections(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax: if request.method == 'GET': class_name = request.GET.get("class_name") class_object = Classes.objects.get(id=class_name) sections = Sections.objects.filter(classes=class_object) return JsonResponse({'context': list(sections.values())}) return JsonResponse({'status': 'Invalid request'}, status=400) else: return HttpResponseBadRequest('Invalid request') Whenever i change the field which triggers Ajax function call i am getting the value error: ValueError at /edit_student/populate_sections Exception Value: Field 'id' expected a number but got 'populate_sections'. I understand that it is expecting the student id but how to do that. Thanks & Regards Neha Singh -
Submit forms in django without refreshing the page
Okay, first of all, I know that there are a lot of videos and tutorials out there to help with the question I have raised. However, my case is a little different than the usual. So, basically, I am trying to build out a chat app on Django. For this I am planning to save the messages that the user wants to send in the database and then render them on screen. Now, in order to send this data to the server, I wish to use Ajax as it would prevent page reload and thus make for a much smoother UX. However, that raises an issue. The issue is that how do I keep track of the fact that which room/ chat is the message coming from and which user sent it? The obvious solution that comes to mind is the create a hidden field inside if my form and then pass in the room details of it through that hidden field. But won't that be highly insecure as the data could be subject to change, allowing users to send messages from a chat they have access to, to a chat they don't have access to? The username part can … -
Cannot resolve manager type when using django-polymorphic with mypy django-stubs
I'm trying to use django-polymorphic to extend a DRF project that uses typeddjango with mypy-stubs. I recently started to use PolymorphicModels and mypy instantly started to complain and throw errors: error: Could not resolve manager type for "<MyModel>.objects" I included "polymorphic" and "django.contrib.contenttypes" in the INSTALLED_APPS of the project, and can't really make sense of why mypy keeps complaining. I read about inherited managers in the django-polymorphic doc which could be a cause for troubles, but I didn't manage to identify the root cause to find a fix. I opened a ticket here: https://github.com/typeddjango/django-stubs/issues/1158 with more details. If anyone has some info, I'd love to hear.. -
Reverse for 'func_name' not found. 'func_name' is not a valid view function or pattern name
Recently I django suddenly stopped working and gives me the error "Reverse for 'test' not found. 'test' is not a valid view function or pattern name. Whats interesting is that in my previous projects everything works just fine. I've tried to reinstall django and selected different python interpreters - nothing helped."views.py (only the useful bit) def test(): return HttpResponse('work') urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path('test', views.test, name='test') ] index.html {% extends "network/layout.html" %} {% block script %} {% load static %} <script src="{% static 'network/index.js' %}"></script> {% endblock %} {% block body %} <button id="butt">Click</button> <a href="{% url 'test' %}">Link</a> {% endblock %} main/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("", include("network.urls")), ] -
TypeError: unsupported operand type(s) for |: 'chain' and 'AsyncResult'
I'm new to Celery and want to implement a basic example of a chain containing four tasks. The first task passes its return value to the next task in the chain, and so on. While running Celery worker, I got the following error: ERROR/ForkPoolWorker-4] Task run-chain[...] raised unexpected: TypeError("unsupported operand type(s) for |: 'chain' and 'AsyncResult'") Here is my simple chain with the tasks: from celery import chain, signature from celery import shared_task @shared_task(name = 'add') def add(x, y): return x + y @shared_task(name = 'substract') def substract(x, y): return x - y @shared_task(name = 'multiply') def multiply(x, y): return x * y @shared_task(name = 'divide') def divide(x, y): return x / y @shared_task(name = 'run-chain') def run_chain(x, y): canvas = chain( add.s(x, y).apply_async(), substract.s(x, y).apply_async(), multiply.s(x, y).apply_async(), divide.s(x, y).apply_async() ) return canvas and this is my celery.py file: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myfirsttask.settings') app = Celery() app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() app.conf.beat_schedule = { 'run-every-five-seconds': { 'task': 'run-chain', 'schedule': 5.0, 'args': (2, 3) } } Your help is much appreciated! -
gunicorn status returns 'No Module named status'
In my virtual environment, without any running gunicorn processes, inside the correct Django path my gunicorn status returns 'No Module named status' (venv) root@django-server:/home/user/repo/project# gunicorn status [2022-09-27 11:05:15 +0000] [821146] [INFO] Starting gunicorn 20.1.0 [2022-09-27 11:05:15 +0000] [821146] [INFO] Listening at: http://127.0.0.1:8000 (821146) [2022-09-27 11:05:15 +0000] [821146] [INFO] Using worker: sync [2022-09-27 11:05:15 +0000] [821148] [INFO] Booting worker with pid: 821148 [2022-09-27 11:05:15 +0000] [821148] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/user/repo/venv/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/user/repo/venv/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/user/repo/venv/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/user/repo/venv/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/user/repo/venv/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/user/repo/venv/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/user/repo/venv/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'status' [2022-09-27 11:05:15 +0000] [821148] [INFO] Worker exiting (pid: 821148) [2022-09-27 11:05:15 +0000] [821146] [INFO] Shutting down: Master [2022-09-27 11:05:15 +0000] [821146] [INFO] Reason: Worker failed to boot. (venv) root@django-server:/home/user/repo/project# -
Convert this raw sql to django query
hi im trying to convert this sql code into django query select * from KnowledgeManagement_tblknowledge where (14010705 - CreateDate) >=10000 and (register_status = 7 or register_status = 9) I have done a part of it knowledges = TblKnowledge.objects.filter(Status__gte=0).filter(Q(register_status=7) | Q(register_status=9)) but this part seems to be a little tricky where (14010705 - CreateDate) >=10000 BTW CreateDate is an integer filed and saves the current date in solar date and 14010705 is a solar date 14010705 = 1401/07/05 -
Django's construct_search for custom search number-only
I'm trying to search for only numbers in a masked string. In this case, it is a string that is returned by the list_display and can be formatted with a mask and letters, but I want to search only for numbers and disregard any other element that comes in the string. For example the string when I search returns 111.1111-111 and I want to search for it only with 111111111. form = ConfigTestFormAdmin list_display = ( 'id', 'show_url', 'cpf_cnpj', 'username' ) search_fields = ( 'id', 'cpf_cnpj__icontains', 'username' ) def show_url(self, cpf_cnpj): return cpf_cnpj(''.join(i for i in just if i.isdigit())) show_url.allow_tags = True -
Django Regoup - Sum in templates
I want to get the Volume subtotal of my "Contracts" field grouped in my template. I manage to display the total but not the subtotal. Here are my files: views.py class TransportDetListView(LoginRequiredMixin,ListView): login_url = 'admin:login' model = TransColisCgDlaDet template_name = "betou/transports/sciages/trans_detail.html" paginate_by = 15 def get_queryset(self): queryset = TransColisCgDlaDet.objects.filter(code_trans__contains=self.kwargs['code_trans']).order_by('num_contrat','essence','epaisseur') lstcolis = queryset.values( 'num_colis', 'essence', 'epaisseur', 'qualite', 'produit', 'num_contrat', 'code_specif', 'code_specif_douane', 'destinataire', 'port_destination', 'marque', 'receptionnaire', 'code_trans' ).annotate(volumecolis=Sum('cubage')).annotate(nb_elts=Sum('nbre_elts')) return lstcolis def get_context_data(self, **kwargs): context = super(TransportDetListView, self).get_context_data(**kwargs) context['codetrans_filter'] = TransColisCgDlaDet.objects.filter(code_trans__contains=self.kwargs['code_trans']).order_by('num_contrat','essence','epaisseur') context['nbrecolis'] = context['codetrans_filter'].values('num_colis').annotate(nbcolis=Count('num_colis')) context['totalvolume'] = context['codetrans_filter'].values('cubage').aggregate(totalvolume=Sum('cubage')).get('totalvolume') context['totalelts'] = context['codetrans_filter'].values('nbre_elts').aggregate(totalelts=Sum('nbre_elts')).get('totalelts') context['contrats'] = context['codetrans_filter'].annotate(volumecolis=Sum('cubage')).annotate(nb_elts=Sum('nbre_elts')) return context template {% regroup contrats by num_contrat as lst_group %} <table class="table table-responsive table-bordered text-center"> {% for group_ct in lst_group %} <thead> <tr> <td colspan = "15" class="align-center" style="font-weight: 600">{{ group_ct.grouper }}</td> </tr> <tr> <tr> <th>N.Contrat</th> <th>Essence</th> <th>Epais.</th> <th>N.Colis</th> <th>Nb Elts</th> <th>Volume</th> <th>Qualité</th> <th>Produit</th> <th>Specif</th> <th>Specif Douane</th> <th>Destinataire</th> <th>Destination</th> <th>Marque</th> <th>Réceptionnaire</th> <th>Code Trans</th> </tr> </thead> <tbody> {% for trans in group_ct.list %} <tr> <td>{{trans.num_contrat|default_if_none:""}}</td> <td>{{trans.essence}}</td> <td>{{trans.epaisseur}}</td> <td>{{trans.num_colis}}</td> <td style="text-align: right;">{{trans.nb_elts}}</td> <td style="text-align: right;">{{trans.volumecolis}}</td> <td>{{trans.qualite|default_if_none:""}}</td> <td>{{trans.produit|default_if_none:""}}</td> <td >{{trans.num_contrat}}&nbsp{{trans.code_specif}}</td> <td>{{trans.code_specif_douane|default_if_none:""}}</td> <td>{{trans.destinataire|default_if_none:""}}</td> <td>{{trans.port_destination|default_if_none:""}}</td> <td>{{trans.marque|default_if_none:""}}</td> <td>{{trans.receptionnaire|default_if_none:""}}</td> <td><a href="{% url 'betou:transport_codetrans' trans.code_trans %}" class="link text-secondary">{{trans.code_trans}}</a> {% if not forloop.last %}{% endif %}</td> </tr> {% endfor %} <tr> <td colspan = "3" style="text-align: center; font-weight: … -
Django runserver - ValueError: source code string cannot contain null bytes
I'm trying to run my Django application, which used to work fine before. Now, it is showing this strange error, which seems like coming from Django. Django Version: 4.1 Python Version: 3.10.6 (Docker Image python:3.10.6) django shell commands Traceback (most recent call last): File "/srv/project/./manage.py", line 9, in <module> from django.core.management import execute_from_command_line File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 16, in <module> from django.apps import apps File "/usr/local/lib/python3.10/site-packages/django/apps/__init__.py", line 1, in <module> File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 13, in <module> File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 62, in AppConfig File "/usr/local/lib/python3.10/site-packages/django/utils/functional.py", line 27, in __init__ from django.utils.deprecation import RemovedInDjango50Warning File "/usr/local/lib/python3.10/site-packages/django/utils/deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async ValueError: source code string cannot contain null bytes -
how to do django transaction to a set of code , including queries as well as local operations
permissionIds = [1,2...] try: with transaction.atomic(): RolePermissionMap.objects.bulk_create([ RolePermissionMap(role_id=role.id, permission_id=id) for id in permissionIds]) rolePermissionsMap[roleId] = permissionIds # map should NOT update if the insert fails return Response({"ok": 1}, status=200) except: return Response({"ok": 0} In my code , I need to create multiple raws at a time, incase one of the given permission Id fails, it shouldnot do the next step , which storing some data in to a dict.(its not a db transaction, so it cannot rollback). how can I do it efficiently?