Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.2 disabled form field not passed to widget
I'm using the same form for creating and editing an object. One field cannot be edited when editing the object, so I passed it to self.fields['my_field'].disabled = True since django 1.9+ allow that (and it's cleaner). But whatever, the html doesn't change, the input is still editable and there's no disabled attribute on it. Checked in the view's context_data, my context_data['form'].fields['my_field'].disabled is True. So I don't understand what's happening. From what I saw here when the disabled is passed to the widget attributes. Am I missing somehting? When I manually do self.fields['my_field'].widget.attrs['disabled'] it's actually working. Do I have to add it myself to the widget ? Thanks in advance -
Non-pages in Django wagtail menu
I use wagtailmenus for my menus in Wagtail. This works fine for Wagtail pages. But sometime I wan't to include Django apps (e.g. photoalbum etc.) in the menu or submenu. Any ideas how to go about this? -
How to integrate Django and MySQL Server
How to integrate MySQL and Django? What are the scripts required? I cannot find anything on YouTube regarding this. I have installed both MySQL and Django. MySQL Workbench and Django using pip installer -
Django login page reloads and refreshes after entering username and password. Diagnosis says form is invalid but I don't know how?
It's a Django project. Upon entering the username and password, the login page refreshes and reloads instead of taking me to the homepage.html. When I ran a diagnostic in the view using print(form.is_valid()), it presented me with the base HTML code that makes up the built-in Django {{form}}, in the terminal. However, I'm unable to understand where exactly the fault lies. 1.The Login View def authentication(request): print(request.method) if request.method=='POST': form=LoginForm(request.POST) print(form.errors) print(form) print(form.is_valid()) if form.is_valid(): form.save() username=form.cleaned_data.get('username') password=form.cleaned_data.get('password') user=authenticate(username=username, password=password) login(request, user) return HttpResponse('Success') else: print('code failed') else: form=LoginForm() return render(request, 'TCloneTemplates/login.html', {'form':form}) 2.Forms.py class LoginForm(AuthenticationForm): username = forms.EmailField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '', 'id': 'hello'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '', 'id': 'hi',})) def is_valid(self): form = super(LoginForm, self).is_valid() for f, error in self.errors.items(): if f != '__all__': self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error)}) return form 3.Login.html <body> <div class="pic"> <form method="POST"> {% block content %} {% csrf_token %} {{ form.non_field_errors }} {{form}} <button type="submit">Get Inside</button> {% endblock content %} </form> </div> </body> 4.The url that takes me there path('loginer/', views.authentication, name='loginer') The diagnostic message in the terminal POST <tr><th><label for="hello">Username:</label></th><td><input type="text" name="username" class="form-control" placeholder="" id="hello" maxlength="150" required></td></tr> <tr><th><label for="hi">Password:</label></th><td><input type="password" name="password" class="form-control" placeholder="" id="hi" required></td></tr> False code failed -
Implementing django guardian
Hello seniors and experts in programming , im having some problems implementing django guardian into my work flow engine , viewflow. I have read some example projects using django-guardian and viewflow , however i don't really understand how it works. From my understanding , django-guardian allows me to put restrictions on certain objects , how do i implement it in the case of view flow's process model ? What i wish to achieve is that at different phases of the process , I want different people to have access to it. For example , at phase 1 , only a people from group 'A' can approve it , in phase 2 , only people from group 'B' can approve it. It seems like an easy to do job but i have no clue on how to make it work. Here is some of my code: flows.py class Pipeline(Flow): process_class = PaymentVoucherProcess lock_impl = lock.select_for_update_lock #process starts here start = flow.Start( PVStartView, task_title="Processing New Voucher" ).Permission("preparer" ).Next(this.approve_by_preparer) #preparer will approve approve_by_preparer = flow.View( UpdateProcessView, form_class=PreparerApproveForm, task_title="Approval By Preparer" ).Assign(lambda act: act.process.assign_preparer #the permissions() method is really confusing, i don't understand how it works ).Permission("preparer" ).Next(this.documents) #not the end but just a … -
postgresql is connected in django but not in pgadmin 4
I have installed postgresql in ubuntu, it is working well. I am running django in locally too. This is my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'testdb', 'USER': 'postgres', 'PASSWORD': 'secret', 'HOST': '127.0.0.1', 'PORT': '5432' } } This is really working great with no objection, no complain, no error, no warning But i am experiencing a problem with connecting this testdb with pgadmin 4 My pgadmin 4 is running on docker. I am not getting why it is not connecting. pgadmin 4 saying: Unable to connect to server: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? With the same information and credential, django sucessfully connected but why not on pgadmin 4? Can anyone help me to fix this issue? -
Why are Masonry (desandro) grid-items vertically overlapping? (Used with bootstrap 4 cards)
I have a hard time getting the DeSandro Masonry (https://masonry.desandro.com/) work together with bootstrap 4. What happens is that the bootstrap cards, which are children of the masonry grid-item, all overlap vertically on top of each other when the collapse button is clicked. Below can be seen the structure of the HTML file. I'm using python 3.8.2 together with django 3.0, as well as Bootstrap 4 and the latest version of Masonry. I've simplified the content for the sake of readability. <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-2"> ...Some content here... <div class="col-9"> <!-- wrap all collapsible content --> <div id="entrycontent"> ...Some more content here... <div class="row"> <div class="col-12"> <div class="collapse multi-collapse" id="c{{entry.id}}" data-parent="#entrycontent"> ...Bootstrap Collapse Buttons here... <div class="grid"> <div class="grid-item"> <div class="collapse multi-collapse" id="onethinghere{{entry.id}}"> <div class="card p-2"> ...Main card content here... <div class="grid-item"> <div class="collapse multi-collapse" id="somethingelse{{entry.id}}"> <div class="card p-2"> ...Main card content here... <div class="grid-item"> <div class="collapse multi-collapse" id="somethingmore{{entry.id}}"> <div class="card p-2"> ...Main card content here... And so on... And initialized with jQuery at the bottom of the body tags.: <script> $('.grid').masonry({ // options itemSelector: '.grid-item', columnWidth: 200 }); </script> Also tried initializing with HTML as per the Masonry guide: <div class="grid" data-masonry='{ "itemSelector": ".grid-item", "columnWidth": 200 … -
Rendering Django template as an image [duplicate]
In my Django application, I have a model that I would like to render with a template (one image per object) and export the rendered output as an image with a given resolution. Is it possible? -
Django Python Forms - submitting complex view with multiple forms and formsets
Imagine this concept, I have a Taxi that can be ordered by a group for a full day multiple visits, and I should assign a group leader for each booking. now I have a Booking (PNR) that holds Clients traveling Routes, and a Group Leader (Operator) assigned for that booking. my view holds these: form for selecting the operator formset to add clients in this view I'm trying to make it easier for the user by giving the ability to save each form separately by ajax or save all data of forms by a button at the bottom of the view. I've been searching for a few days and I got the nearest approach on these two linkes 1 & 2 but still can't make my code run correctly and do what it's supposed to do. :( ANY SUPPORT WILL BE HIGHLY APPRECIATED! My models.py: class Operator (models.Model): name = models.CharField(max_length=50) # Other Fields def __str__(self): return self.code class PNR (models.Model): date_created = models.DateTimeField(auto_now_add=True) # Other Fields def __str__(self): return self.pk class Client (models.Model): related_pnr = models.ForeignKey(PNR, on_delete=models.CASCADE) name = models.CharField(max_length=200) # Other Fields def __str__(self): return self.related_pnr+" "+self.name My forms.py: class ChooseOperatorCode(forms.Form): operator = forms.ModelChoiceField(queryset=Operator.objects.all()) def clean(self, *args, **kwargs): … -
import datetime - Clarification
'''' from datetime import datetime now = datetime.now().time() print(now) o/p: 21:44:22.612870 '''' But, when i am trying: '''' import datetime now = datetime.now().time() print(now) '''' it give following error: Traceback (most recent call last): File "D:/3. WorkSpace/3. Django/datemodel/first.py", line 9, in now = datetime.now().time() # time object AttributeError: module 'datetime' has no attribute 'now' any one explain what is difference between both? -
Creating a Django form that allows "extra fields" on a "through" table to be edited
I have User, SocialNetwork, and UserSocialNetwork models in a Django 3.0.3 project. class User(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) middle_name = models.CharField(blank=True, max_length=255, unique=False) bio = models.TextField(blank=True, default='') … socialnetworks = models.ManyToManyField(SocialNetwork, through='UserSocialNetwork') updated_at = models.DateTimeField(auto_now=True) class SocialNetwork(models.Model): name = models.CharField(blank=False, max_length=255) description = models.TextField(blank=True, default='') url = models.URLField(blank=False, max_length=255) format = models.CharField(blank=False, max_length=8, choices=[('handle', 'handle'), ('url', 'url')]) base_url = models.URLField(blank=True, max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['name'] def __str__(self): return self.name class UserSocialNetwork(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) socialnetwork = models.ForeignKey(SocialNetwork, on_delete=models.CASCADE) identifier = models.CharField(blank=False, max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['socialnetwork', ] verbose_name = "User's Social Network" I'm using django-formtools to step through profile creation. One of the steps should be a page where the profile creator is presented with a list of SocialNetworks and given the opportunity to enter their identifier on those networks. I've been struggling with this. It was suggested I use formsets and I've got this class UserSocialNetworkForm(BaseModelForm): class Meta: model = UserSocialNetwork fields = [ 'socialnetwork', 'identifier', ] labels = { 'socialnetwork': _('Social Network'), } UserSocialNetworkFormSet = formset_factory(UserSocialNetworkForm, extra=SocialNetwork.objects.count()) which yields this but all I really want is one line per … -
How to get details of a nested object in a serializer in DRF
So I'm trying to create a serializer that would return a bunch of details of a 'Post' model in my project, but I want to get details of a nested object as well, the output of which I will show below: Post model: class Post(models.Model): # Base post attributes user = models.ForeignKey(UserOfApp, related_name="posts", on_delete=models.CASCADE) ... # Repost post attributes original_repost = models.ForeignKey( to="self", related_name="reposted_post", null=True, blank=True, on_delete=models.CASCADE, ) # Quote post attributes is_quote_post = models.BooleanField(default=False) quoted_post = models.ForeignKey( to="self", null=True, blank=True, on_delete=models.CASCADE ) ... My serializer, using 'depth': class HomeSerializer(serializers.ModelSerializer): id_str = serializers.ReadOnlyField() ... quoted_post_id_str = serializers.ReadOnlyField() class Meta: model = Post depth = 2 fields = "__all__" This yields me an output like, the problem being it returns all sensitive data from my user model as well, like 'password' etc: { "id": 16, ... "is_quote_post": false, "user": { "id": 1, "password": "pbkdf2_sha256$180000$ni6drJvLjUU2$xoMt5tpJmz8TlmORfB/eTkYlGGpUGfriGz8rO7kVB8E=", "last_login": "2020-03-21T06:20:48Z", "is_superuser": true, "username": "manas", "first_name": "Manas", "last_name": "Acharekar", "email": "manas.acharekar98@gmail.com", "is_staff": true, "is_active": true, "date_joined": "2020-03-01T18:42:11Z", "dob": "1998-11-11", "gender": "M", "bio": "i own this place", "location": "", "website": "", "verified": true, "followers": [], "friends": [], "groups": [], "user_permissions": [] }, "original_repost": { "id": 1, ... "user": { "id": 1, "password": "pbkdf2_sha256$180000$ni6drJvLjUU2$xoMt5tpJmz8TlmORfB/eTkYlGGpUGfriGz8rO7kVB8E=", "last_login": "2020-03-21T06:20:48Z", "is_superuser": true, … -
How to implement Django Chained Drop Down using clever select
I'm using doing a small django project and using django-clever-select to created chained drop down select. I followed the exact instruction given in their installation useage guide at https://pypi.org/project/django-clever-selects/. But once i run the app in pycharm the dropdown doesn't show any data to be selected. models.py <pre> class Category(models.Model): mname = models.CharField(max_length=100, blank=False,unique=True) mdescription = models.CharField(max_length=255, blank=True) def __str__(self): return self.mname class Meta: ordering = ('mname',) class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE,null=True, blank=True) scname = models.CharField (max_length=100, blank=False,unique=True) scdecription = models.CharField(max_length=255, blank=True) def __str__(self): return self.scname class Meta: ordering = ('scname',) class Deals(models.Model): vendor_deal = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null= True) description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateField(auto_now_add=True) expire_date = models.DateField(null=False) current_date = models.DateField(auto_now_add=True) def __str__(self): return self.description class Meta: ordering = ('description',) </pre> template file for the form ` {% extends 'base.html' %} {% load static %} {% block content %} </br></br></br></br> <div class="content"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-6"> <form id="post_from" method="post"> {% csrf_token %} <div class="form-group"> {{ form.as_p }} </div> <button type="submit" class="btn btn-primary">Upload</button> </form> </div> <div class="col-md-2"></div> </div> <div class="row"> </div> <div class="row"> </div> </div> {% endblock %} </pre></code> ` form.py file `<pre> … -
Create a subclass not to repeat matching fields
I created two class models in Django. Is there a way not to repeat the same matching fields storing them in a different class or variable? This is what i got: class Post(models.Model): title = models.CharField(max_length=50) content = RichTextField(blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) posted_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) slug = models.SlugField(null=True, unique=True, editable=False) def __str__(self): return str(self.category) + self.slug + " " + str(self.id) def save(self, *args, **kwargs): self.slug = slugify(str(self.category)) + "/" + slugify(self.title+str(-self.id)) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title class Post2(models.Model): title = models.CharField(max_length=50) content = RichTextField(blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) posted_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) slug = models.SlugField(null=True, unique=True, editable=False) def __str__(self): return str(self.category) + self.slug + " " + str(self.id) def save(self, *args, **kwargs): self.slug = slugify(str(self.category)) + "/" + slugify(self.title+str(-self.id)) super(Post2, self).save(*args, **kwargs) def __str__(self): return self.title -
prefetch_related on existing django instance
I have a prefetch_related defined on my ObjectManager - is it possible to get the prefetch_related functionality on an instance that wasn't retrieved by this manager? This would apply to something like a newly-created instance. class Foo(models.Model): objects = FooManager() class FooManager(models.Manager): return (...).prefetch_related("bars") fooA = Foo.objects.get(...).bars # prefetched + cached for later fooB = Foo.objects.create() fooB.bars # not prefetched fooB.bars # queries each time because not included in prefetch cache -
GeoDjango IntegrityError when following the Tutorial
I am precisely following the GeoDjango Tutorial: https://docs.djangoproject.com/en/3.0/ref/contrib/gis/tutorial/ and decided to use SpatiaLite instead of PostGIS as my db-Backend. In order to do that, i edited my projects settings.py-file: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Following the Tutorial worked up to the Part "LayerMapping". When running $ python manage.py shell >>> from world import load >>> load.run() i get the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: world_worldborder.fips What can I do to fix this Error? Thanks in Advance! -
ImportError: cannot import name 'forms' from 'basicapp'
form.py: from django import forms class FormName(forms.Form): name=forms.CharField() email=forms.EmailField() text=forms.CharField(widget=forms.Textarea) views.py: from django.shortcuts import render from .forms import forms def index(request): return render(request,'basicapp/index.html') def form_page(request): Form = forms.FormName() return render(request,'basicapp/form_page.html',{'form':Form}) I dont know what is wrong here! when I run server, it makes an error, saying ImportError : cannot import name 'forms' from 'basicapp' -
Django form with only one select field is passing the input tag value instead of the selected one
Django beginner here. I have a form which asks the user to select an answer to be set as the correct one. Now my form is the following: class SelectCorrectAnswer(forms.Form): def __init__(self, choices, *args, **kwargs): super(SelectCorrectAnswer, self).__init__(*args, **kwargs) self.fields['correct_answer'].choices = choices correct_answer = forms.ChoiceField(choices=(), required=True) As you can see the choices are added dynamically, in fact, they are correctly displayed in the template, which is the following: <!--Select the correct answer--> <form action="{% url 'create-assessment' %}" method="post"> {% csrf_token %} {{ select_correct_form.as_p }} <input type="submit" value="Select" name="select-correct-answer" > </form> And retrieved in the view as shown below: # Initialize select correct answer form. problem_answers = Answer.objects.filter(creator=current_user, question=problem_to_be_answered) choices = [] for answer in problem_answers: choices.append((answer.answer, answer.answer),) select_correct_form = SelectCorrectAnswer(choices) print(choices) The view tries to handle the POST request as follows: # Set answer as correct. if request.method == 'POST' and 'select-correct-answer' in request.POST: print(f'CODE REACHED HERE {request.POST}') select_correct_form = SelectCorrectAnswer(request.POST) if select_correct_form.is_valid(): selected_answer = select_correct_form.cleaned_data['correct_answer'] correct_answer = Answer.objetcs.get(id=selected_answer.id) correct_answer.is_correct_answer = True correct_answer.save() print(f'THIS IS THE CORRECT ANSWER {correct_answer}') From the print statements, I can see that the correct request is being processed but the value I select is not passed. In fact, as you can see from the printed output, … -
Django blocked the raw socket connection
I build a socket server on the python and it worked. And when i call it as thread from django server the connection is refuse. This is my server code on thread: def add_device_to(self): socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() socket_server.bind((host, 5555)) socket_server.listen() while True: socket_c , address = socket_server.accept() print("ok") self.register(socket_c, address) This is my client code: socket_client1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() socket_client1.connect((host,5555)) The error on the client side is: socket_client2.connect((host, 5554)) ConnectionRefusedError: [Errno 111] Connection refused And when i tried that on windows it work fine. -
Use Django Queryset filter API on in-memory list of Model instances?
Is it possible to re-use the Django Queryset API when I've already retrieved a list of objects? i.e. foos = list(Foo.objects.filter(color="red")) large_foos = foos.filter(size="large") small_foos = foos.filter(size="small") I can of course iterate through my foos list, but it'd look cleaner to reuse the API. Use case is something like the color column being indexed but the result set small, and size isn't indexed (or size has high cardinality). -
render data with rest framework based on user input (Django)
I am struggling to modify this view so that a chart is generated based on user input. The underlying isssue is that I cannot find a way to make this with Django rest framework. Here is what I have been able to do so far: view.py: class forecast(APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_res', None) if query and request.method == 'GET': reference = Item.objects.filter(reference = query) forecast1 = Item.objects.filter(reference = query).values('demand_30_jours') forecast2 = Item.objects.filter(reference=query).values('Lt2') forecast3 = Item.objects.filter(reference=query).values('Lt3') data = {'reference': reference, 'forecastdata':[forecast1, forecast2, forecast3]} return Response(data) urls.py urlpatterns = [ path('', HomeView.as_view(), name='HomeView'), path('items.html', ItemPage.as_view()), path('charts',TemplateView.as_view()), path('admin/', admin.site.urls), path('api/chart/data',ChartData.as_view()), path('api/chart/forecast',forecast.as_view()) items.html <form id="searchform" method="get" action="" accept-charset="utf-8"> Search <input id="searchbox" name="search_res" type="text" placeholder="Search"> <input type="submit" value="OK"> </form> <div class="col-lg-6"> <div class="card mb-4"> <div class="card-header"><i class="fas fa-chart-bar mr-1"></i>90 DAYS FORWARD FORECAST</div> <div class="card-body"><canvas id="myChart" width="150" height="116"></canvas></div> <div class="card-footer small text-muted">References</div> </div> </div> <script> $(document).ready(function() { var endpoint = '/api/chart/forecast' var forecastdata= [] var reference = [] ; $.ajax({ method: "GET", url: endpoint, success: function (data) { reference = data.reference forecastdata = data.forecastdata setChart() }, error: function (error_data) { console.log(error_data) } } ) function setChart(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'scatter', data: { labels: reference, … -
How to make automatic anser to mattermost channel
I have a problem with automatic generator of response via mattermost. To simplify a question- I have some dedicated channel on mattermost and if a message send by me is correct I want to have automatic answer "OK" + my_message. Right now I am checking a message and if is good making: result = {"channel" = "@username", "text" = "OK" + my_message} return HttpResponse(result, status=200) but it doesn't work. Ideas? -
Django not working after switching from sqllite3 to postgresql
I'm getting the following error after making switch of database when trying to make migrations: django.db.utils.OperationalError No explanation at all following it. I change the base sqlite3 code in settings to: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'myprojectuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } My models.py: from django.db import models # Create your models here. class Company(models.Model): KIND = ( (0, "Corporate"), (1, "Start Up"), ) name = models.CharField(verbose_name="full company", max_length=50) address = models.CharField(max_length=100) kind = models.IntegerField(default=0) class Job(models.Model): name = models.CharField(max_length=50) salary = models.DecimalField(max_digits=8, decimal_places=2, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) Any idea what is going on? I did makemigrations when using sqlite3, but I already deleted the database. Full traceback error here: Traceback (most recent call last): File "C:\Users\Admin\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 220, in ensure_connection self.connect() File "C:\Users\Admin\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Admin\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Admin\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Admin\Anaconda3\lib\site-packages\django\db\backends\postgresql\base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Admin\Anaconda3\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line … -
how can i pass my context variables to javascript in Django?
views.py context = {'select_company': select_company,} return render(request, 'invest/chart.html', context) html <option value="{{o}}">{{select_company}}</option>----------{{select_company}} can show its value <script> company = {{select_company|safe}}; ---------------js tell me undefined </script> django 2.2 python 3.7 how to solve the weird problem -
TypeError at /stock/delete sequence item 0: expected str instance, int found
I'm deleting multiple objects using checkboxes but I'm facing this error TypeError at /stock/delete sequence item 0: expected str instance, int found views.py class DeleteProducts(SuccessMessageMixin, View): success_url = reverse_lazy('stock:stock') success_message = "Products {} are deleted successfully." def post(self, request, *args, **kwargs): products = self.request.POST.getlist('product') products_deleted = Product.objects.filter(pk__in=products).delete() msg = self.success_message.format(', '.join(products_deleted)) messages.success(self.request, msg, extra_tags='alert-danger') return HttpResponseRedirect(self.success_url) urls.py path('delete', login_required(DeleteProducts.as_view(), login_url='login'), name='deleteproducts'),