Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we build a website without using frameworks like django and flask in python?
well I'm new to django and I have a doubt, is it possible to develop a dynamic website without using python frameworks? can we develop a website in pure python? and How? some resources please Thank you -
Returning multiple (if all) objects.get in django then outputting to a template
I am trying to search through the database of users returning matches of the search querry, then I get this data and output it to a html. It works but I need to do this for multiple objects sometimes where this can get quite convoluted. views.py def search_index(request): if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): searchquerry = form.cleaned_data['searchquerry'] try: found = (CustomUser.objects.get(username__icontains=searchquerry)) foundname = (found.username) foundimage = (found.docfile) founddate = (found.date_joined) foundid = (found.id) # Redirect to the document list after POST return render(request, 'search_found.html', {'foundname':foundname,'foundimage':foundimage, 'founddate':founddate, 'foundid':foundid}) except Exception as e: print(e) else: form = SearchForm() # A empty, unbound form return render(request, 'search_index.html', {'form':form}) forms.py class SearchForm(forms.Form): searchquerry = forms.CharField(label="Search for a username", max_length=100) search_found.html {% extends "_base.html" %} {% block content %} <html> <div class="foundbox"> <button class="add-friend">Add Friend</button> <button onclick="window.location.href='../profile/{{ foundid }}'" class="show-profile">Profile</button> <div class="foundimage"> <div class="foundimage_container"> <img class="foundimage_container" src="../{{ foundimage }}" onerror="this.onerror=null;this.src='../static/users/default.gif';"></img> </div> </div> <h2 class="foundtext">{{foundname}}</h2> <p class="founddate">Join date: {{founddate}}</p> </div> </html> {% endblock %} please mind the formatting. -
django [Jquery] on click nav-tab <li>, background color not changing
In my django template I am using the {% forloop %} to populate a list. On first page load, the default behavior I require is that the first list item has to be active, selected and assuming its selected, it must automatically execute an href (a django url call in this case). <ul class="nav nav-tabs nav-fill" id="domain_tab" role="tablist"> {% for object in object_list %} <li class="nav-item"> <a href="{% url 'object_contents' %}?object={{object}}" class="nav-link" data-target="#cardview" role="tab" aria-selected="true"> {{object}} </a> </li> {% endfor %} </ul> The script shows first li nav-tab say A, but on clicking any other li nav-tab say B, B is not highlight, A still remains highlight although the contents of B are shown successfully. <script> $(document).ready(function (){ $('.nav-tabs li:eq(0) a').tab('show'); $('.nav-tabs li:eq(0)').addClass('active'); var link = $('.nav-tabs li.active a').prop('href'); // the page gets its contents but is reloaded multiple time (recurring page loading) // document.location.href = link; }); $('.nav-tabs li a').click(function (e) { e.preventDefault() $('.nav-tabs li.active a').tab('show'); }); </script> I think on every page load/reload, I am forcing the first li nav-tab be highlighted hence no other li nav-tab gets highlighted on click. Also here is my css in case you need to see the color setting: .nav-tabs > li … -
Unable to deploy of Heroku because of Python Package with Error
I'm trying to upload my django application on Heroku. It works on local because I corrected the error, but for some reason after I added whitenoise to get local files so that I can deploy on Heroku, it keeps bringing up the same error. I am loading a local package csv-imports and it has an error on line 70. class ImportModel(models.Model): """ Optional one to one mapper of import file to Model """ #this is the line with the error and I fixed it here with the on_delete csvimport = models.ForeignKey(CSVImport, on_delete=models.DO_NOTHING) numeric_id = models.PositiveIntegerField() natural_key = models.CharField(max_length=100) However when I run: git push heroku master I get the following error which I have fixed on my local, but seems to keep coming up with Heroku. The file has been changed. I might not be on the right file path given by Heroku there is no app/.heroku/ on my computer. But, there is only one installation of csv-imports on my computer and that one has been fixed as above. Why do I keep getting this error and how do I fix it? remote: File "/app/.heroku/python/lib/python3.7/site-packages/csvimport/models.py", line 72, in ImportModel remote: csvimport = models.ForeignKey(CSVImport) remote: TypeError: __init__() missing 1 required positional … -
Can't connect to MSSQL using django-pyodbc-azure 2.1.0.0
As the title says. Im getting this error django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') Heres my code DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'ECP_MISDATA_MISWEB', 'USER': 'phyton_sql_svc', 'PASSWORD': 'Artesyn!2019', 'HOST': 'CHAPO', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } DATABASE_CONNECTION_POOLING = False -
How to rank search results by alphabetical order (Django 2.1)
I have code for a search engine and a button that ranks by alphabetical order, but I can't get them to work together. Code for search engine: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') if 'a-z' in request.GET: articles = articles.order_by('Title') Code for button that ranks posts by alphabetical order: <a href="?a-z=True" type="button" class="btn btn-outline-{% if 'a-z' in request.GET %}success{% else %}secondary{% endif %}">A-Z</a> The button ranks all posts by alphabetical order rather than only ranking the posts in the search results. It's probably because I am not combining the value of request.GET generated by the button and the value generated by the keyword entered into the search engine. How can I edit the code so that the button only ranks the posts in the search results? -
ManyToOne relationship with User database
I want to create a model with a ManyToOne relationship with the user database. Here's the code I used for the field: user_ID = models.ManyToOneRel(User) The migration doesn't work. It returns NameError: NameError: name 'User' is not defined How should I refer to the user database? -
ListView with condition in the data Django
i'm new on Django, and I would like to know how can I create a kind of filter so that only an object appears if it meets a condition in one of its attributes. I tried to do it with tags in the template but it did not work and I don't know if it is the most efficient way. The case is for example that I would like to see in my table the objects that in their attribute "asignar" have a specific value for example the text "Pedro". I'm open to suggestions that do not necessarily apply with labels. Models.py: class reporte_fallo(models.Model): num_inventario = models.CharField(max_length=25) serie = models.CharField(max_length=25) falla = models.TextField() descripcion = models.TextField() LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) area = models.CharField(max_length=1,choices=LOAN_STATUS,blank=True) fecha = models.DateField(auto_now=False, auto_now_add=True) asignar = models.CharField(max_length=20, default=True) fecha_comp = models.DateField(default=timezone.now) View.py: class reportelist(ListView): model = reporte_fallo template_name = 'formulario/reporte_list_jefe.html' Template.html (This is my template that did not work using tags in this case the part "and report.assign == "Pedro" on the if, it just send the message "The list is empty") <tbody> {% if object_list and reporte.asignar == "Pedro" %} {% for reporte in object_list %} <tr> … -
(admin.E108) The value of 'list_display[1]' refers to 'label', which is not a callable, an attribute of '?', or an attribute or method on 'org.Org'
I get the error : (admin.E108) The value of 'list_display[1]' refers to 'label', which is not a callable, an attribute of 'OrgAdmin', or an attribute or method on 'org.Org'. when I try to remove the field label, I don't understand why. (sqlite3) It feels like django has referenced that field somewhere (I was using it in the str function before refactoring and I don't know how to sync it up or something. from django.db import models class Org(models.Model): class Meta: # https://docs.djangoproject.com/en/2.1/ref/models/options/#django.db.models.Options.db_table db_table = "tfp_backoffice_org" verbose_name = 'Organization' # https://docs.djangoproject.com/en/2.1/ref/models/options/#indexes indexes = [ models.Index(fields=['name', 'name']), ] name = models.CharField( help_text="Optional (autogenerated).<br />" "Must be url-compliant (slug, using '-' dash separator, no space, special char, etc.)", max_length=100, ) label = models.CharField( help_text="Label displayed in French language", max_length=100, ) label_fr = models.CharField( help_text="Label displayed in French language", max_length=100, blank=True, default="", ) label_en = models.CharField( help_text="Label displayed in English language", max_length=100, blank=True, default="", ) def __str__(self): return self.label_fr -
Incorrect Number of Bindings Using a For Loop and Lists (Python & SQLite3)
I have a SQLite3 database that I am trying to update with a series of lists. I want each list element to input as a new row in the specified column. I am getting the following error: "Incorrect number of bindings supplied. The current statement uses 9, and there are 10 supplied." This doesn't make sense to me as I'm only supplying 9 lists as values. Some lists have 10 items and others have null entries, but they are all 10 elements long. I'm guessing that's where it's getting the 10 bindings from but I have no idea how to fix this. I have 9 lists Column1 = internetMessageIdList Column2 = receivedDateTime, etc. etc... For loop code: For i in range(len(senderNameList)): c.execute((c.execute("INSERT INTO tutorial_message (MessageID, MessageDate, MessageRecipientAddress, MessageRecipientName, MessageSubject, MessageCC, MessageBCC, MessageSenderAddress, MessageSenderName) VALUES (?,?,?,?,?,?,?,?,?)", (Column1[i], Column2[i], Column3,[i], Column4[i], Column5[i], Column6[i], Column7[i], Column8[i], Column9[i])) -
Django - share media files during development
I want developers to use the same development database while developing a Django project so I've created a remote server with Ubuntu 18.04, created Postgres database and allowed remote access. The problem is that there are missing pictures - media directory is in .gitignore because of production server. How I make media being shared (and editable) so any developer can see any image and assign image to object? I was thinking about sharing it through git or to store media on production server where Postgres is but not sure how and if it's the best way to do this. -
Celery task cannot be called (missing positional arguments) from Django app
Ok I've poured over all the SO posts, Celery docs, etc...and I just cannot figure this out. No matter what I try or how I try to call a task from a Django app, Celery is complaining that I'm not supplying the required parameters. "TypeError: add() missing 2 required positional arguments: 'x' and 'y'". I'm following a very simple example from their docs...simply using delay, such as: add.delay(1, 2) and still the same error. I've also tried add.delay(x=1, y=2), celery.send_task("add", [1, 2]) and a wide variety of other ways I've seen tasks called in various posts and none of them work. Is there anything else I could possible be missing?? The method is very simple: @shared_task def add(x, y): return x + y I've also tried it named, such as: @task(name="my_add") def add(x, y): return x + y Same results. What else can I possibly be missing??? -
How to link a field from one model to a specific field of another model
So I have a platform class where I can set all platforms library/models.py from django.db import models from django.utils import timezone # Create your models here. class Platform(models.Model): platform = models.CharField(max_length=20) def __str__(self): return self.platform class Game(models.Model): title = models.CharField(max_length=100) description = models.TextField() date_posted = models.DateTimeField(default=timezone.now) cover = models.ImageField() cover_display = models.ImageField(default='default.png') developer = models.CharField(max_length=100) twitter = models.CharField(max_length=50, default='') reddit = models.CharField(max_length=50, default='') platform = models.ManyToManyField(Platform) def __str__(self): return self.title then I have a model class where I can set the platforms for that game and each game has its own posts. How do i set the platform field in the Post Model to inherit the platforms from the Game model. I'm doing this so I can sort the posts by the games specific platforms. main/models.py from django.db import models from library.models import Game, Platform from users.models import User from django.utils import timezone from django.urls import reverse from vote.models import VoteModel # Create your models here. class Post(models.Model): article_title = models.CharField(max_length=100) content = models.TextField() date_published = models.DateTimeField(db_index=True, default=timezone.now) game = models.ForeignKey(Game, on_delete=models.CASCADE) article_image = models.ImageField(default='/media/default.png', upload_to='article_pics') platform = models.ForeignKey(Game, related_name='platform') def __str__(self): return self.article_title class Meta: ordering = ["-date_published"] def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) -
Why can't my mod_wsgi module find "libpython3.7m.so.1.0" even though it exists?
I'm using CentOS 7, Apache 2.4 with Python 3.7 band mod_wsgi 4.6.5. I'm trying to install mod_wsgi with Apache. I created the file, /etc/httpd/conf.modules.d/10-wsgi.conf, which contains the contents LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so But when I attempt to load Apache, it dies with an error [myuser@server mod_wsgi-4.6.5]$ sudo apachectl configtest httpd: Syntax error on line 56 of /etc/httpd/conf/httpd.conf: Syntax error on line 1 of /etc/httpd/conf.modules.d/10-wsgi.conf: Cannot load /usr/lib64/httpd/modules/mod_wsgi.so into server: libpython3.7m.so.1.0: cannot open shared object file: No such file or directory [myuser@server mod_wsgi-4.6.5]$ cat /etc/httpd/conf.modules.d/10-wsgi.conf LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so httpd: Syntax error on line 56 of /etc/httpd/conf/httpd.conf: Syntax error on line 1 of /etc/httpd/conf.modules.d/10-wsgi.conf: Cannot load /usr/lib64/httpd/modules/mod_wsgi.so into server: libpython3.7m.so.1.0: cannot open shared object file: No such file or directory I have verified this file exists on my file system [myuser@server mod_wsgi-4.6.5]$ echo $LD_LIBRARY_PATH /usr/local/lib [myuser@server mod_wsgi-4.6.5]$ ls -al /usr/local/lib/libpython3.7m.so.1.0 -r-xr-xr-x 1 root root 13683680 Feb 27 18:01 /usr/local/lib/libpython3.7m.so.1.0 I don't know what else to check to convince my system everything is there. Any help is appreciated, - -
Python Django template rendering from views gives me a too many values to unpack error
I have a function in views.py that renders the template in template.html shown below: views.py def example(request): context_dict = { 'form_1': Step1Form, 'form_2': Step2Form, 'form_3': Step3Form, } return render(request, 'example/template.html', context_dict) template.html <form method="GET" action="/example/"> {% csrf_token %} <div> {% for field in form_1 %} <label for="{{ field.id_for_label }}">{{ field.label }}</label><br> {{ field }}<br> {% endfor %} </div> </form> <form method="GET" action="/example/"> {% csrf_token %} <div> {% for field in form_2 %} <label for="{{ field.id_for_label }}">{{ field.label }}</label><br> {{ field }}<br> {% endfor %} </div> </form> <form method="GET" action="/example/"> {% csrf_token %} <div> {% for field in form_3 %} <label for="{{ field.id_for_label }}">{{ field.label }}</label><br> {{ field }}<br> {% endfor %} </div> </form> But for some reason when I load the template, I get the error: ValueError at /example/ too many values to unpack (expected 2) The template will load if the field tag in the third form is gone. The context dictionary and rendering doesn't look any different from other ones that I've seen so I don't know what's causing the problem. -
Twitter Bootstrap - How do I get my carousel to, well, "carousel"?
Generally I am always way over my head with programming, but I'm doing my best. Please be nice! I watched a nice tutorial on YouTube in order to build myself a carousel in my Django project. But instead of showing one image at a time it is just stacking all three on top of each other. I'm sure there's something simple that I've missed. Please help me to fix this with a minimal of code change. Here is my current HTML code. I don't believe the CSS is important at this point: <div class="container-fluid" id="main-container"> <div class="row"> <div class="col-sm-12"> <div id="slider" class="carousel slide" data-ride="carousel"> <!-- indicators (dot nav): --> <ol class="carousel-indicators"> <li data-target="#slider" data-slide-to="0" class="active"></li> <li data-target="#slider" data-slide-to="1"></li> <li data-target="#slider" data-slide-to="2"></li> </ol> <!-- wrapper for slides: --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img class="img-fluid" src='{% static "images/carousel1.jpg" %}' alt="string players"/> <div class="carousel-caption"> <h1>Text here</h1> </div> </div> <div class="item"> <img class="img-fluid" src='{% static "images/carousel2.jpg" %}' alt="string players"/> <div class="carousel-caption"> <h1>More text here</h1> </div> </div> <div class="item"> <img class="img-fluid" src='{% static "images/carousel3.jpg" %}' alt="string players"/> <div class="carousel-caption"> <h1>Even more text here</h1> </div> </div> </div> <!-- next/prev navigation controls: --> <a class="left carousel-control" href="#slider" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron left" aria-hidden="true"></span> <span … -
Django form with a ModelChoiceField on a UUID do not show its content in cleaned_data
I have a model: class Code(models.Model): section = models.CharField(max_length=255) code_uid = models.UUIDField() def __str__(self): return self.section and a form: class MyForm(Form): code_uid = ModelChoiceField(queryset=Code.objects.all(), to_field_name="code_uid") But the following code after a POST of this form: if my_form.is_valid(): print(my_form) print(my_form.cleaned_data) print(my_form.cleaned_data["code_uid"]) print(type(my_form.cleaned_data["code_uid"])) Prints: for my_form a correctly displayed HTML: <tr><th><label for="id_code_uid">Code uid:</label></th><td><select name="code_uid" required id="id_code_uid"> <option value="">---------</option> <option value="e3112238-0768-1111-aaaa-4654ab799752">foo</option> <option value="e3112238-0768-1111-aaaa-4654ab799752">bar</option> for my_form.cleaned_data: {'code_uid': <Code: foo>} <== should be the UUID for my_form.cleaned_data["code_uid"]: foo for type(my_form.cleaned_data["code_uid"]): <class 'creator.models.Code'> How should I get my UUID value in the cleaned_values dictionary? -
Steps to deploy an image classifier online so that user can identify an image realtime through his smartphone?
I am a beginner in machine learning and have already made basic ML projects and image classifiers, but now I require a direction to proceed in order to make a web application through which user can use, scan any image and the website will speak the class under which the test image is classified by it. Can anyone guide me the easiest way of implementing and deploying such a project Ex 1.- candy classifier- where users just need to visit www.findthecandy.com and then just scan the pic of candy through their camera and then the trained model will determine and announce the result like "this is a cadbury bar". for those who wonder my intension behind this project I am making it for blind people to identify objects and I don't have enough time to learn android so I am resorting to making a web app. Any help will be appreciated. -
Django Channels Tutorial Exception
I've basically followed the Django-Channels 2.0 tutorial exactly with one caveat: I'm sending a ton of data, not a message every few seconds. I'm sending something like 2kb every 10ms and it always throws an exception on this line after sending a few frames of valid data. # Receive message from WebSocket async def receive(self, text_data): # Send message to room group # Wrapped message in a try catch so it doesn't throw. try: text_data_json = json.loads(text_data) chat_message = text_data_json['message'] # Exception here await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) except Exception: pass - 2019-02-27 21:03:32,803 DEBUG WebSocket incoming frame on ['172.20.10.1', 63436] 2019-02-27 21:03:32,818 DEBUG WebSocket incoming frame on ['172.20.10.1', 63436] 2019-02-27 21:03:32,828 ERROR Exception inside application: 'stream_data' File "/.../site-packages/channels/sessions.py", line 179, in __call__ return await self.inner(receive, self.send) File "/.../site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/.../site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/.../site-packages/channels/utils.py", line 52, in await_many_dispatch await dispatch(result) File "/.../site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/.../site-packages/channels/generic/websocket.py", line 196, in websocket_receive await self.receive(text_data=message["text"]) File "/.../rooms/consumers.py", line 28, in receive stream_data = text_data_json['stream_data'] 'stream_data' 2019-02-27 21:03:32,834 DEBUG WebSocket incoming frame on ['172.20.10.1', 63436] 2019-02-27 21:03:32,838 DEBUG WebSocket closed for ['172.20.10.1', … -
django 404 not found page
I am trying to show a blogpost on the site below is details of urls and view file details but still it showing a 404 not found page url.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="ShopHome"), path("blogpost/", views.blogpost, name="blogpost") ] views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return render(request, 'blog/index.html') def blogpost(request): return render(request, 'blog/blogpost.html') Showing 404 not found page -
Django wysiwyg for admin only
Hi I have problem with suit_redactor in Django project... I probably doing something wrong. I need change article_content input widget to suit_redactor or ck-editor or something else. I try this before but nothing happend probably i miss something. (Sorry for English, not my language) I have suit_redactor in installed apps in settings.py My model class Article(models.Model): article_title = models.CharField(max_length=400, null=False) article_content = models.CharField(max_length=20000, null=False) ..... forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser,Article from django.forms import ModelForm from django.contrib.admin import ModelAdmin from suit_redactor.widgets import RedactorWidget class ArticleForm(ModelForm): class Meta: widgets = { 'name': RedactorWidget(editor_options={'lang': 'en'}) } class ArticleAdmin(ModelAdmin): form = ArticleForm admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import ArticleAdmin from django.utils import text from django import forms from .models import CustomUser, Category, Article, Comment admin.site.register(Article, ArticleAdmin) I need to article_content looks like (this for example): after instead this: before -
Multiple views and models in a Django project
I'm working on a Django 1.11 application and I'd like to break my models and views into separate packages. (The models were moved into their own directory some time ago and have been working without issue.) So, the application structure will become: app models __init__.py foo.py bar.py views __init__.py foo.py bar.py ... I've done the above using this tutorial as a reference, but when attempting to import models in the newly nested views (a la from models.foo import Foo), I'm met with an error which says, ImportError: No module named models.foo. Do I need to specify this new path in settings.py? Do I need to change my import statement? Something else? -
How to test Django REST Framework filter using "now"?
Others have explained why writing tests which depend on the current time is a bad idea (for example non-reproducible errors and not being able to test special dates such as summer time transitions). So when testing serializers I've used the following pattern: def test_should_be_valid_if_best_before_a_future_date(self) -> None: serializer = MyModel( data={ 'best_before': datetime.datetime(…), … }, context={'now': datetime.datetime(…)}, ) self.assertTrue(serializer.is_valid()) This pattern makes it trivial to test what happens when, for example, best_before is before, at, and after now. I've not found a similar pattern for filters - they don't seem to have a context property. How would I do similar tests for filters, ideally without mocking anything in datetime, since that makes the test depend on an implementation detail? -
How to do a good post in form with Django
I am using Django 2.1.7. I am trying to post make a post in my form and add item in my sqlite database but it is not working. Here is my error when I try to add an item : Request Method: POST Request URL: http://127.0.0.1:8080/addBill/ Django Version: 2.1.5 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'thetest' Exception Location: C:\Users\fg\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 965 : Here is my code : facture.html <body> <h1> this is the bills template </h1> <ul> {% for all_items in all_items %} <li> {{all_items.content}}</li> {% endfor %} </ul> <form action="/addBill/" method="post" >{% csrf_token %} <input type="text" name="content"> <input type="submit" value="Add"> </form> </body> model.py class Facture(models.Model): content = models.TextField() views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Facture # Create your views here. def myView(request): all_bill_items=Facture.objects.all() return render(request,'facture.html',{ 'all_items':all_bill_items }) def addBill(request): #create and item #save #redirect the user new_item=Facture(request.POST['content']) new_item.save() return HttpResponseRedirect('/Home/') -
Method update in drf for PATCH
After many research and great help (thanks @bkawan), I got write my method create in drf serialization many to many. My challenge now is to make my method "update" work. The PUT works fine, but the PATCH doesn't work when I exclude the product field. Does someone have any idea? My serializer.py, views and create method is here. And here is my idea for update: def update(self, instance, validated_data): products = validated_data.pop('products', None) if products is not None: BundleProduct.objects.filter(bundle=instance.id).delete() for product_id in products: product = get_object_or_404(Product, pk=product_id) BundleProduct.objects.create(product=product, bundle=instance) return instance