Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to disable django page caching
is there a way to prevent page caching in django? Because I have 2 views. view2 is only accessible if a request.session['iv'] exists. This is only created within view1 of a post request and is also deleted at the beginning of view1, so that access to view2 is not possible for the time being. If I am then redirected from view1 to view2 I can easily go back with the browser and land on view1. The problem is I can then go back to "show next page" and end up on view2 although the request.sesion no longer exists. This must be because the browser opens a cached version of view2, which I want to prevent. -
Websocket connection failing
`The WebSocket connection to 'ws://localhost:3000/ws/api/stocks_prices/AAPL/' failed: WebSocket is closed before the connection is established. React frontend views.js `useEffect(() => { const socket = new WebSocket(`ws://${window.location.host}/ws/api/stocks_prices/${symbol}/`); console.log("socket",socket) socket.onmessage = event => { const data = JSON.parse(event.data); setStockPrices(prevStockPrices => ({ ...prevStockPrices, data: [data, ...prevStockPrices.data.slice(0, 4)], })); console.log("websocket data",data); }; return () => { socket.close(); console.log("WebSocket closed"); }; }, [symbol]);` Using Django for backend routing.py `from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/api/stocks_prices/(?P<symbol>\w+)/$', consumers.StockConsumer.as_asgi()), ]` consumer.py `from channels.generic.websocket import AsyncWebsocketConsumer import json import yfinance as yf class StockConsumer(AsyncWebsocketConsumer): async def connect(self): self.stock_name = self.scope['url_route']['kwargs']['stock_name'] self.stock_group_name = 'stocks_prices/%s' % self.stock_name # Join room group await self.channel_layer.group_add( self.stock_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.stock_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) stock_name = text_data_json['stock_name'] # Fetch real-time stock data ticker = yf.Ticker(stock_name) data = ticker.history(period='1d') stock_price = { 'stock_name': stock_name, 'price': data['Close'].iloc[-1], } # Send real-time stock data to the client await self.channel_layer.group_send( self.stock_group_name, { 'type': 'stock_price', 'price': stock_price } ) # Receive message from room group async def stock_price(self, event): stock_price = event['price'] # Send real-time stock data to the client await self.send(text_data=json.dumps({ 'stock_name': stock_price['stock_name'], 'price': stock_price['price'] })) views.py … -
Merging converted pdf files in aws lambda function
Trying to acheive below functionality Uploading multiple files to s3 bucket. Non pdf files needs to get converted to pdf and then merge into single pdf file. The folder structure will be folder1/2/3/4. under folder 4 the files gets uploaded. Below is my code(lambda function) but the issue is the files(only some) are merging before all the files gets converted. convert to pdf has to occur successfully before the merging starts. import os import io from io import BytesIO import tarfile import boto3 import subprocess import brotli from PyPDF2 import PdfMerger from time import sleep #Directory where libre office open source s/w will be saved lambda tmp directory LIBRE_OFFICE_INSTALL_DIR = '/tmp/instdir' s3_bucket = boto3.resource("s3").Bucket("bucketname") def load_libre_office(): if os.path.exists(LIBRE_OFFICE_INSTALL_DIR) and os.path.isdir(LIBRE_OFFICE_INSTALL_DIR): print("Have a cached copy of LibreOffice, Skipping Extraction") else: print("No Cached copy of Libre Office exists , extracting tar stream from brotli file") buffer = BytesIO() with open('/opt/lo.tar.br','rb') as brotli_file: decompressor = brotli.Decompressor() while True: chunk = brotli_file.read(1024) buffer.write(decompressor.decompress(chunk)) if len(chunk) < 1024: break buffer.seek(0) print('Extracting tar stream to /tmp for caching') with tarfile.open(fileobj=buffer) as tar: # TODO: write code... print('opening tar file') tar.extractall('/tmp') print('LibreOffice caching done!') return f'{LIBRE_OFFICE_INSTALL_DIR}/program/soffice.bin' def convert_word_to_pdf(soffice_path, word_file_path, output_dir): conv_cmd = f"{soffice_path} --headless --norestore --invisible --nodefault … -
django listview order by model property
I have a model called Lap with a property calculated using data from the table class Lap(models.Model): team=models.ForeignKey('Team', models.DO_NOTHING) timestamp=models.IntegerField() num=models.IntegerField() @property def laptime(self): endtime=self.timestamp starttime=Lap.objects.get(team=self.team, num=self.num-1).timestamp) return time.timedelta(seconds=endtime-starttime) I am trying to create a listview for the model class FastestLap(ListView): model=Lap template_name='fastestlaps.html' context_object_name='laps' I want to order the list view by the laptime property. sorting by a column can be done using the ordering variable or by creating a get_queryset method and doing queryset.order_by(fieldname) in that method but I cant find a way to order by the property. How do I order by laptime? -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/register.html
Working on *django * on a test app, while creating a subpage as register in index/homepage, facing an error as follows: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: [name='index'] admin/ accounts ^media/(?P.*)$ The current path, accounts/register.html, didn’t match any of these. views.py: from django.shortcuts import render def register(request): return render(request,'register.html') urls.py: from django.urls import path from . import views urlpatterns = [ path("register",views.register, name="register") ] mysite url.py: from django.contrib import admin from django.urls import include , path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('Sell.urls')), path('admin/', admin.site.urls), path('accounts', include('accounts.urls')) ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html: <div class="container"> <div class="header_section_top"> <div class="row"> <div class="col-sm-12"> <div class="custom_menu"> <ul> <li><a href="#">Best Sellers</a></li> <li><a href="#">Gift Ideas</a></li> <li><a href="#">New Releases</a></li> <li><a href="accounts\register.html">Register</a></li> <li><a href="#">Customer Service</a></li> </ul> </div> </div> </div> </div> </div> #Although the register.html is in a templates folder but i tried it too but still not working. Register.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv='X-UA-Compatible' content="IE=edge"> <title>Register</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="main.css"> <script src="main.js"></script> </head> <body> <form action='register' method='post'> {% csrf_token %} <input type="text" name="first_name" placeholder="First Name"><br/> <input type="text" name="last_name" placeholder="Last Name"><br/> <input type="text" name="username" placeholder="username"><br/> <input … -
how to make my css style apply on my pages
I've been using django for a while but I'm just a beginner in css, I don't know much. I put style on my style.css file which is in the static folder and I placed the link in my template base.html but when I launch the server, the css style does not apply. what to do? mon templates base.html {% load static %} <html> <head> <title>Lax blog</title> <link rel="stylesheet" href="{% static 'style.css' %}" /> </head> <body> <div class="sidebar"> <h1>Lax Blog</h1> {% if user.is_authenticated %} {% if user.profile_photo %} <img class="avatar" src="{{ user.profile_photo.url }}" /> {% else %} <img class="avatar" src="{% static 'images/default_profile.png'%}" /> {% endif %} <p><a href="{% url 'home' %}">Accueil</a></p> <p> Vous etes connecté entant que {{request.user }} <a href="{% url 'deconnexion' %}">Se déconnecter</a> </p> {% endif %} </div> <div class="main">{% block content %}{% endblock content %}</div> </body> </html> mon fichier style.css body { background-color: white; color: blue; } html { font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif; } .sidebar { height: 100%; /* Full-height: remove this if you want "auto" height */ width: 220px; /* Set the width of the sidebar */ position: fixed; /* Fixed Sidebar (stay in place on scroll) */ z-index: 1; /* Stay on top … -
How to create password reset in Django Rest Framework
I have an app called API where I want to create a "Forgot Password" button for the user to insert their email, and a password reset is sent to them. In the same Django project, I have an application called users which implements this process in the backend. How can Django Rest Framework be used to reset the password? Do I link the URLs of the users app or create new URLs in API app Here is the users app urls.py app_name = 'users' urlpatterns = [ path('password/', user_views.change_password, name='change_password'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html', success_url=reverse_lazy('users:password_reset_done')), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html',success_url=reverse_lazy('users:password_reset_complete')),name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),name='password_reset_complete'), ] here is the main urls.py urlpatterns = [ path('', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), path('api/', include('api.urls'), ), path('users/', include('users.urls'), ), here is the api app urls.py app_name = 'api' router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='user') urlpatterns = [ path('', include(router.urls)), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] -
Django-channels: How to delete an object?
I'm making a real-time chat app using django channels. I want to delete an object from database using django channels(actually deleting a message from the group). How can this be done? This is my backend code: import json from django.contrib.auth.models import User from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from .models import Room, Message class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): data = json.loads(text_data) print(data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username, room, message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username': username })) @sync_to_async def save_message(self, username, room, message): user = User.objects.get(username=username) room = Room.objects.get(slug=room) Message.objects.create(user=user, room=room, content=message) Should i use javascript? I tried to delete some objects by using Ajax but it didn't work. -
Is it possible to return render request and json response together?
I got a little function for rendering an html and I also wanna return a JsonResponse in the same page, is it possible to return both at the same time? I'll leave mi little function Below def addObservation(request): reservations= Reservation.objects.all() return render(request, 'observations/registerObservation.html', {'reservations': reservations}) I wanna add a Json response to get the reserveations list in js Thanks for your help -
I get this error when I try to render some html files in django: NoReverseMatch at / Reverse for 'it_languages' not found
When I try to render a html file in django project, I get this error, and I can't see the localhost page 'cause of this. The error is: NoReverseMatch at / Reverse for 'it_languages' not found. 'it_languages' is not a valid view function or pattern name. and it languages is url for in html Then it bolds me with yellow this: Home About Me **IT-languages** Projects Contact I expect to see my offline page rendered by django project Should I keep it like the original html version: Home About Me IT-languages Projects Contact -
Unable to add image in django
I am unable to display the image from local storage to the html page using django HTML code: <!DOCTYPE html> <html> <head> <title>Display Image</title> </head> <body> <img src="{{ image_path }}" alt="Image"> </body> </html> view.py code: from django.shortcuts import render def display_image(request): image_path = 'templetes\media\image.png' context = {'image_path': image_path} return render(request, 'valid.html', context) setting.py code: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/ -
Queryset ordered by must frequent values
I'm trying to order a simple queryset by the must frequent value in a column. For exemple, I have those models: class Keyword(models.Model): keyword = models.CharField(verbose_name='Keyword', null=False, blank=False, max_length=20) class BigText(models.Model): text = models.CharField(verbose_name='Big Text', null=False, blank=False, max_length=1000) class BigTextKeyword(models.Model): keyword = models.ForeignKey(Keyword, verbose_name='Keyword', null=False, on_delete=models.CASCADE) bigtext = models.ForeignKey(BigText, verbose_name='Big Text', null=False, on_delete=models.CASCADE) Then, I'm searching for the keywords passed on query params and returning the BigTextKeywords result found like this: class BigTextKeywordViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): queryset = BigTextKeyword.objects.all() serializer_class = BigTextKeywordSerializer def get_queryset(self): keyword_filter = Q() search_content = self.request.query_params.get('search_content', '') for term in search_content.split(' '): keyword_filter |= Q(keyword__icontains=term) keywords = Keyword.objects.filter(keyword_filter) result = BigTextKeyword.objects.filter(keyword__in=keywords) return result I want to order the result by the must frequent bigtext field. For example, if a bigtext occurs 3 times on the result, it should appears first than a bigtext that occurs 2 times. -
Tests failling after django and python upgrade
I've upgraded Django from 4.0.5 to 4.1.6 and python from 3.9 to 3.11 I've also upgraded dependencies: pip==23.0 pytest==7.2.1 pytest-django==4.5.2 coverage==7.1.0 pytest-cov==4.0.0 pylint==2.16.2 mock==5.0.1 These are my logs: django-admin test Traceback (most recent call last): File "/usr/local/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 394, in run_from_argv parser = self.create_parser(argv[0], argv[1]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 357, in create_parser self.add_arguments(parser) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/test.py", line 54, in add_arguments test_runner_class = get_runner(settings, self.test_runner) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/utils.py", line 394, in get_runner test_module = __import__(test_module_name, {}, {}, test_path[-1]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django_coverage/coverage_runner.py", line 31, in <module> from django.db.models import get_app, get_apps ImportError: cannot import name 'get_app' from 'django.db.models' (/usr/local/lib/python3.11/site-packages/django/db/models/__init__.py) -
Incorrect type. Expected pk value, received str
how to post from html form in [enter image description here] (https://i.stack.imgur.com/fevLp.png) django rest framework api i am getting error as Incorrect type. Expected pk value, received str. -
Fullfill drf serializer attribute from dict by key name
Imagine I have a serializer with lower camel-named fields what I have to keep by contract: class SomeSerializer(serializers.Serializer): someField = serializers.CharField() And I have following data to serilaize where I want to keep key names in snake case to follow convention: data = {'some_field': 'I love python'} I want serializer to fullfill its someField from dict some_field key's value serialized_data = SomeSerializer(data=data) serialized_data.is_valid() serialized_data.data['someField'] == 'I love python' What I tried already: DRF serializer source - seems to be applicable to model-based serialzers? DRF serializer method field - seems to be hard to apply when there is few fields of different formats - charfields, datefeilds, intfields and all I need is just to pull values from dict Custom renderers - but they are applied after serialization and validation will fail and will affect whole view Any other suggestions? -
My view does not redirect after processing a form. Used HttpResponseRedirect
I am new to Django and I am trying to use custom forms. My problem is that my form does not do anything after I submit it. I am following the documentation here:https://docs.djangoproject.com/en/4.1/topics/forms/ I have the following files: urls.py: from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('', views.index, name='index'), path('test', views.test_view, name='test') ] views.py: def index(request): return render(request, 'index.html', context) def test_view(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): return HttpResponseRedirect('home:index') else: form = TestForm() return render(request, 'test.html', context={'form':form, 'text':'No text yet.',}) template: test.html <div> <form action="home:club-invite" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> <hr> <p>Your text: {{ text }}</p> </div> The problem is that the Submit button does nothing. I was expecting a redirect to the index page. But here is no error, no subsequent http request or redirect, nothing... Am I missing something here? PS:I also tried return redirect('home:index'). Still no success. -
Multiple Databases in 1 Django Project
I am planning to develop a AI-Enabled Stock Market Project using Django & Tensorflow For Clients, I plan to use MSSQL For Stock Tickers, I plan to use MongoDB How do I do it in Django? I am in Planning stage -
Django reduce amount of queries (M2M relation with through model)
I would like to reduce the amount of similar queries. Here are my models: class Skill(models.Model): name = models.TextField() class Employee(models.Model): firstname = models.TextField() skills = models.ManyToManyField(Skill, through='SkillStatus') def skills_percentage(self): completed = 0 total = 0 for skill in self.skills.all().prefetch_related("skillstatus_set__employee"): for item in skill.skillstatus_set.all(): if item.employee.firstname == self.firstname: total += 1 if item.status: completed += 1 try: percentage = round((completed / total * 100), 2) except ZeroDivisionError: percentage = 0.0 return f"{percentage} %" class SkillStatus(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) skill = models.ForeignKey(Skill, on_delete=models.CASCADE) status = models.BooleanField(default=False) My main problen is related to method skills_percentage, I make too many queries while calculating mentioned value. I have already improved situation a little bit with prefetch_related, but there are still extra queries in Django Debug Toolbar. What else can be done here? I have tried to play with different combinations of select_related and prefetch_related. I thought about other options to calculate skills_percentage but they also required to many queries... Thanks in advance. -
Python Test - I'm not able to get PermissionDenied on Client() get
I'm not finding the way to get when the PermissionDenied error is raised. This test try to catch a Permission Denied on a Django, it is expected just to accept staff user to return a 202 status_code This is the code: from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django.test import Client, TestCase from django.urls import reverse from scrapers.models import Scraper class PublicWebTestCase(TestCase): def setUp(self): # Every test needs a client. self.client = Client() # Create staff user (no staff) self.user = User.objects.create_user('juan', 'juan@myemail.com.ar', 'juan') self.staff_user = User.objects.create_user( 'victor', 'victor@lala.com.ar', 'Vitor', is_staff=True ) self.client.raise_request_exception = True # crear un scraper para que haya una vista de el self.scraper = Scraper.objects.create( name='My Scraper', folder="X", ) self.page_url = reverse('scrapers-page') def test_scrapers_page_for_anon_user(self): """ Scrapers view as anonymous user """ self.assertRaises(PermissionDenied, self.client.get, self.page_url) And this is the result I get: Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). Forbidden (Permission denied): /scrapers/ Traceback (most recent call last): File "/home/lugezz/Dev/lll/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/lugezz/Dev/lll/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/lugezz/Dev/lll/env/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/lugezz/Dev/lll/stud/scrapers/mixins.py", line 14, in dispatch raise PermissionDenied … -
How to solve subprocess.calledprocesserror command returned non-zero exit status 1 error?
I created a task with celery and I'm calling it in my views. But when I trigger the task it returns an error: [2023-02-17 11:37:41,777: ERROR/ForkPoolWorker-7] Task f.tasks.trigger_model[6edf150] raised unexpected: CalledProcessError(1, ['spark-submit', 'run_trigger.py', '../inputs/Test_Dataset_config.yml', '../inputs/run_mode_config.yml']) Traceback (most recent call last): File "/python3.10/site-packages/celery/app/trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "/sgenv/sgvenv/lib/python3.10/site-packages/celery/app/trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "/tasks.py", line 20, in trigger_model subprocess.run(["spark-submit", "run_trigger.py", main_config, runmode_config], check=True, capture_output=True) File "/app/analytics/sgenv/python/lib/python3.10/subprocess.py", line 526, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['spark-submit', 'run_trigger.py', '../inputs/Test_Dataset_config.yml', '../inputs/run_mode_config.yml']' returned non-zero exit status 1. And here is my code: @shared_task() def trigger_model(main_config, runmode_config): with cd("$HOME"): subprocess.run(["spark-submit", "run_trigger.py", main_config, runmode_config], check=True, capture_output=True) How can I fix it and why it gives me this error? -
wWay to find id in tag
I am creating a followers list to the sidebar. How can I get author_id in my custom tag? @register.inclusion_tag('list_followers.html', takes_context=True) def show_followers(context, author_id): request = context['request'] if request.user.is_authenticated: followers = Profile.objects.filter(name=author_id) return {'followers': followers} _sidebar.html Thanks... I tried to get author_id from views.py to posts_tags.py def author_info(request, author_id): """return following users""" current_user = request.user.id author = User.objects.get(id=author_id) .............. or get author_id in _sidebar.html somehow {% load posts_tags %} ........... <div class="media"> <div class="p-3 border bg-light"> <div class="container"> {% show_followers author_id=here %} </div> </div> </div> but I couldn't... -
Django + React app deployment via zappa on aws
I am currently deploying a django + react app on amazon aws using zappa. The page works as intended as long as I navigate on the page via clicking. However, when I refresh the page I do always get a 404 error. Why is this? The URL that I am located on when refreshing the page is like this: myDomainName/currentPath When I refresh the page, an immediate redirect is caused and the new request is made to: myDomainName/stageName/currentPath Therefore, the URL that I see in the browser search bar when everything is done loading is: myDomainName/stageName/currentPath instead of myDomainName/currentPath. As react does not know this URL with the prepended stageName, it raises a 404 error. My question is: How can I make sure that the URL after loading is of form myDomainName/currentPath? I think the redirect of CloudFront must happen, as its origin is simply located at path: /stageName/currentPath. Thus, I cannot change anything here. Note: Once this problem happened once on a specific page, the next refresh works correctly as CloudFront uses cached data. Any advice is warmly welcome, as it is very frustrating to have a fully functional page, which does not work correctly on page refresh. Cheers -
Query set for many to many object relationship
Need to post many items onetime -many titles- in a titles list from mobile app to the backend, the problem is when use create method within the for loop it gets no record in database & that Type Error -Direct assignment to the forward side of a many-to-many set is prohibited. Use container.set() instead.- when try to use the set() method it's not showing any right case!!!!, the problem is when to use create in order to made many create objects in many-to-many relationship. please guide. models.py class Container(models.Model): name = models.CharField(max_length=200, blank=False) capacity = models.IntegerField( null=False ,blank=False) class Item(models.Model): title = models.CharField(max_length=200, blank=False) container = models.ManyToManyField(container) serializers.py class ContainerSerializer(serializers.ModelSerializer): class Meta: model = Container fields = '__all__' class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' Request { "container": { "name": "container1", "capacity": 10, }, "Items":[ {"title":"tl1",}, {"title":"tl2",}, {"title":"tl3",} ] } view.py @api_view(['POST']) def additems(request): data = request.data container = Container.objects.create( name = data['name'] capacity = data['capacity'] ) container.save() for i in Items: item = Item.objects.create( container = container , title = i['title'] , ) item.save() serializer = ContainerSerializer(container, many=False) return response(serializer.data) TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use container.set() instead. … -
How to ignore django expression errors in vscode js file?
Is there any way to ignore these kind of errors (django expressions)? I mean the code works perfectly, but the vscode is triggering those errors. In a way it visually bothers me. -
Django Autocomplete Light - Check all options on click
I have a django autocomplete light, with more than 200 options. Therefore, i want to include a button "select all". I almost managed to do so, with the following code. $('#facility-types').val(['2', '5', '6', '10', '11', '12', '13', '14']); $('#facility-types').trigger('change'); // Notify any JS components that the value changed The problem is, that with django autocomplete light, the option-tags for the select fields are only then created, when the user has manually selected an option. Furthermore, the option-tag has a data-select-2-id that appears me to be kind of random. <option value="12" data-select2-id="127">xxxx</option> Any ideas, how to programatically select all options of a django-autocomplete-light select field? Thank you very much in advance!!