Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django sqlite3 database not configured correctly in pycharm
I'm currently continuing a django project on windows originally written by a mac user, and I am using the PyCharm IDE. I had a lot of trouble getting the database set up for the project (using the default sqlite3). My DATABASE settings are correct, and when I check the connection the the database when running manage.py shell it says that it is connected. The only issue is that every variable that is there to access data in the database is highlighted in red, which is typically a sign of an error in the JetBrains IDEs that I've worked with. I'm still able to host the site locally what could be the cause of this issue/error? I've a couple examples of what I mean below: example 1 example 2 EDIT: I know there is a problem because if I run a model independently I get the following exception: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. but the DJANGO_SETTINGS_MODULE was already configured correctly to the right app. Any ideas? -
Django tests are deleting production data, only work when running all tests at once
First off, this is Django 1.9.13. I realize this is an unsupported version, but I have to use it for reasons. The database is postgres 9.6. I have a project that runs about 40 tests divided amongst a few files. All test cases are TransactionTestCase that load their own fixtures through fixture = ['fixture_name.json'] I use fixtures in the app/fixtures directory that are akin to base_data.json test_a_data.json test_b_data.json ... Base data is used in most if not all test cases. But the other fixtures are used in 1 or few tests. The settings to run it are 'test': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 0.0.0.0, 'PORT': 5432, 'NAME': <database>, 'USER': <user>, 'PASSWORD': <pass>, 'TEST': { 'NAME': 'test_database' } } When running the following command, it runs fine python manage.py app.test -v 1 --keepdb However, when running individual test cases it fails python manage.py app.test.test_A.ATestCase -v 1 --keepdb This fails with IntegrityError: Problem installing fixture '/appfixtures/test_a_data.json': Could not load <object>(pk=1): duplicate key value violates unique constraint "<uniq_constraint_name>" DETAIL: Key <key> already exists. as if the fixture is being loaded twice. I have tried inspecting the SQL Django is using and found that the object in question is only loaded once. However, the object … -
"User matching query does not exist" occurring in template but not in unit test?
In a Django project, there is a Family model defined similar to the following: class Family(BaseFamily): employee_first_name = models.CharField(max_length=255, blank=True) employee_last_name = models.CharField(max_length=255, blank=True) partner_first_name = models.CharField(max_length=255, blank=True) partner_last_name = models.CharField(max_length=255, blank=True) where BaseFamily has a package and lucy_guide foreign key: class BaseFamily(TimeStampedModel): package = models.ForeignKey('lucy_web.Package', models.SET_NULL, blank=True, null=True) lucy_guide = models.ForeignKey( User, blank=True, null=True, related_name='lucy_guide_%(class)s', limit_choices_to={'is_staff': True}) The Package model, in turn, is linked to a Company: class Package(TimeStampedModel): company = models.ForeignKey('lucy_web.Company') and a Company, in turn, has a lucy_guide and a default_package: class Company(TimeStampedModel): lucy_guide = models.ForeignKey( User, blank=True, null=True, related_name='lucy_guide_%(class)s', limit_choices_to={'is_staff': True}) default_package = models.OneToOneField( Package, blank=True, null=True, related_name='default_for_%(class)s') Now, I have a template which uses the following template tag, edit_view_family_heading: from django import template register = template.Library() @register.simple_tag def edit_view_family_heading(family): heading = [family.employee_first_name] if family.employee_last_name != family.partner_last_name: heading.append(family.employee_last_name) heading.extend([ '&', family.partner_first_name, family.partner_last_name ]) heading = [e for e in heading if e] if heading[0] == '&': heading.pop(0) if heading and heading[-1] == '&': heading.pop() if heading: if family.lucy_guide: heading.append(f'({family.lucy_guide.first_name})') return ' '.join(heading) else: return family.id However, if I try to display the template, I get the following error: Template error: In template /Users/kurtpeek/Documents/Dev/lucy2/lucy-web/dashboard/templates/dashboard.html, error at line 0 User matching query does not exist. 1 : {% … -
Celery doesn't work
I am current using celery 3.1.25 I am running my celery in docker, this is the start info: tasks_1 | tasks_1 | -------------- celery@da91cb33086e v3.1.25 (Cipater) tasks_1 | ---- **** ----- tasks_1 | --- * *** * -- Linux-4.9.87-linuxkit-aufs-x86_64-with-debian-8.10 tasks_1 | -- * - **** --- tasks_1 | - ** ---------- [config] tasks_1 | - ** ---------- .> app: __main__:0x7f2d2c525350 tasks_1 | - ** ---------- .> transport: amqp://guest:**@rabbit:5672// tasks_1 | - ** ---------- .> results: memory:/// tasks_1 | - *** --- * --- .> concurrency: 2 (prefork) tasks_1 | -- ******* ---- tasks_1 | --- ***** ----- [queues] tasks_1 | -------------- .> default exchange=default(direct) key=default tasks_1 | tasks_1 | I run the following command in my django shell: import os from celery import Celery from django.apps import apps #configure my django setting file os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ns.settings') app = Celery('') app.config_from_object('django.conf:settings') @app.task def add(x, y): return x + y result = add.delay(8, 8) Here is what I get, I think the task is built successfully: Start from server, version: 0.9, properties: {u'information': u'Licensed under the MPL. See http://www.rabbitmq.com/', u'product': u'RabbitMQ', u'copyright': u'Copyright (C) 2007-2018 Pivotal Software, Inc.', u'capabilities': {u'exchange_exchange_bindings': True, u'connection.blocked': True, u'authentication_failure_close': True, u'direct_reply_to': True, u'basic.nack': True, u'per_consumer_qos': True, u'consumer_priorities': True, … -
Stay in the same django template after a request.POST
I'm having problems with the return after doing a POST request in Django. I have a template that shows information in a table after doing POST request, in that table I have a button that opens a modal where I can Update the information of the table, I can do the update without problems, but after that I want to do nothing, in other word stay on the same page with the modal open, but when I return an HTTPresponse() this gives me a blank page -
Standard server response time Django
I would like know if exist standard time to server response for an app with django. Example i have a list of products that retrieve from my db MYSQL. Exist a time standar to validate this request, the idea is that my app dont fall with great user demand.. this is a capture for example of products list: -
remove strange characters from token in url in django
I am using: default_token_generator.make_token(user) for generate my token to recover password, but sometimes it generates strange characters (such as #) and it broke the html. It is possible to change this function to use only letters and numbers, or I have to use another one? -
Django - Passing multichoice field into POST dictionary
I have a queryset generated in my forms.py file that passes into my template. The template result is a multichoice field based on the queryset. The web browser presentation is correct - it renders the queryset as a drop down choice list that I can make a selection from. Here is the template code: <tr><td>{{ form.jury_name | placeholder:'Jury Name' }}</td></tr> <tr><td><select> {% for item in form.parent_jury.field.queryset %} <option name="parent_jury" value="{{ item }}">{{ item }}</option> {% endfor %} </select></td></tr> This is all contained in a table. When the form is submitted (method = "POST") the POST dictionary has all the correct values for the keys except the parent_jury key which posts a value of ''. I've worked through several SO solutions on the views.py side, but they don't change the fact that the information available for a clean() is missing the choice field value for 'parent_jury'. How do I get the selected option from the list to attach to the 'parent_jury' key? -
"ImportError: No module named django.core.wsgi" apache error
I'm trying to run a django project on CentOS 7. I have a virtual environment inside my project containing all the required packages, ... . I configured my httpd.conf file as follows: <VirtualHost *:80> ServerName the_server_ip_address ServerAlias localhost DocumentRoot /var/www/html # adding these lines for handling static files Alias /media/ /var/www/html/wsgi-scripts/walk/mysite/static/media Alias /static/ /var/www/html/wsgi-scripts/walk/mysite/static/static_root/ <Directory /var/www/html> #Order allow,deny #Allow from all Require all granted Satisfy Any </Directory> WSGIDaemonProcess localhost processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/html/wsgi-scripts/walk/walk.venv python-path=/var/www/html/wsgi-scripts/walk/mysite WSGIProcessGroup localhost WSGIScriptAlias / /var/www/html/wsgi-scripts/walk/mysite/mysite/wsgi.py <Directory /var/www/html/wsgi-scripts/walk/mysite/mysite> WSGIPassAuthorization On <Files wsgi.py> Require all granted </Files> #Require all granted </Directory> and my wsgi.py is configured as follows: import os, sys # add the mysite project path into the sys.path sys.path.append('/var/www/html/wsgi-scripts/walk/mysite') # add the virtualenv site-packages path to the sys.path sys.path.append('/var/www/html/wsgi- scripts/walk/walk.venv/lib/python2.7/site-packages') # poiting to the project settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") from django.core.wsgi import get_wsgi_application #os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() The httpd is restarting fine, but when I access the website, an "Internal Server error" is returned and there are the following lines inside the apache log: (most recent call last): File "/var/www/html/wsgi-scripts/walk/mysite/mysite/wsgi.py", line 21, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi mod_wsgi (pid=11196): Target WSGI script '/var/www/html/wsgi-scripts/walk/mysite/mysite/wsgi.py' cannot be loaded as Python module. mod_wsgi … -
Django ORM - Filter Related Objects
I apologize if this is a duplicate, but I was unable to find any other SO posts that address this matter. I have models like so: class Person(models.Model): pass class Interest(models.Model): person = models.ForeignKey(Person, related_name='interests') is_cool = models.BooleanField() I know that I can find all people who have cool interests like so: Person.objects.filter(interests__is_cool=True) However, what I really want is to get only their cool interests when I get the Person object. I know that I could always pluck the related queryset out and operate on it, like so: interests = person.interests.filter(is_cool=True) but I cannot assign it back to the person instance since the relationship is reversed. To summarize, the goal is to use the ORM directly to filter the Interest objects being returned in the person.interests queryset. -
Cross-Origin Request Blocked (Ionic + Django)
I am building an application using ionic framework with backend written in Django. When i try to do testing i am getting the following error message Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). I saw some documentation and it was mentioned that i need to add proxies under ionic.config.json so i added the proxies it look something like this "proxies":[ { "path":"/api", "proxyUrl": "http://localhost:8000/api" } ] Thanks in Advance -
Django requested URL was not found on this server in TestClass
My TestClass looks like: from django.test import TestCase, Client class TestGetSomething(TestCase): def test_get_first_url(self): path = "some/long/path" client = Client() response = client.get(path=path) self.assertEqual(response.status_code, 200) But assertEquals raises the exception, 404 != 200. When i wrote print(response.__dict__) i have noted request that fields: '_closable_objects': [<WSGIRequest: GET 'somelong/path'>] 'request': {'PATH_INFO': 'some/long/path', 'REQUEST_METHOD': 'GET', 'SERVER_PORT': '80', 'wsgi.url_scheme': 'http', 'QUERY_STRING': ''} 'templates': [<django.template.base.Template object at 0x7f4b33ac17f0>], 'context': [{'True': True, 'False': False, 'None': None}, {'request_path': '/somelong/path/', 'exception': 'Resolver404'}] As you can see the part of paths does not have the slash between 'some' and 'long' When i am trying to get the page by URL manually (using a browser) everything goes OK In my Django app i do not use nothing except of Model and ModelAdmin. Even urls.py is clear. Everybody now how can i fixed it? Any additional code I'll add if it necessary. -
Download a file inside project using javascript
I'm trying many different download locations but nothing seems to download, or I don't know if I am downloading anything at all. I don't really know javascript and trying to understand it for this small part of my project, where I want to automatically download something from the project. Usually I get the message url not found or nothing at all. I know I am almost there to solving this but I could use some help. The function is calling which is a good sign. function Download(url) { document.getElementById('my_iframe').src = url; }; And I call it by typing this: Download('music/music/static/Album.zip') And I want to download from project, this zip file: -
how to edit and create event in Fullcalendar with Django
I am trying to use calendar features in my site with events model. class Event(models.Model): limit = models.Q(app_label='crm', model='Household', id=10) | \ models.Q(app_label='crm', model='Lead', id=13) | \ models.Q(app_label='crm', model='Opportunity', id=14) | \ models.Q(app_label='crm', model='Case', id=11) name = models.CharField( pgettext_lazy("Name of the Event", "Event"), max_length=64) On my html I have . the events displayed fine. Now, to add or edit an event. I have this. $(document).ready(function() { $('#calendar').fullCalendar({ defaultDate: '{{today|date:'%Y-%m-%d'}}', editable: true, header: { left: 'prev,next today prevYear', center: 'title', right: 'nextYear month,agendaWeek,agendaDay' }, navLinks: true, // can click day/week names to navigate views eventLimit: true, // allow "more" link when too many events events: [ {% for i in events %} { title: "{{ i.name}}", start: '{{ i.start_date|date:"Y-m-d" }}', end: '{{ i.close_date|date:"Y-m-d" }}', }, {% endfor %} ], firstDay:1, slotDuration:'00:15:00', scrollTime:'07:00:00', selectable: true, selectHelper: true, ignoreTimezone: false, lazyFetching:true, select: function(start, end) { eventType=""; $("#eventDialogLabel").html("New Appointment"); $("#eventID").val(''); $('#eventDialog').modal('show'); startDate=start; $("#deleteButton").hide(); }, eventClick: function(calEvent, jsEvent, view) { eventType=""; $("#eventDialogLabel").html("Update Appointment"); $("#eventID").val(calEvent._id); alert(calEvent._id); $("#modal-body").html(calEvent.title); $("#deleteButton").show(); $('#eventDialog').modal('show'); startDate=calEvent.start; endDate=calEvent.end; }, eventDragStart:function( event, jsEvent, ui, view ) { eventType="eventDragStart"; startDate=event.start }, eventDrop: function(event, delta, revertFunc) { endDate=event.start; EventDropOrResize(calEvent); }, eventResize: function(event, delta, revertFunc) { EventDropOrResize(calEvent); }, }); }); $("#deleteButton").on('click',function(){ doPOST('DELETE'); return false; }); function EventDropOrResize(calEvent) … -
Returning all fields with Wagtail API from page slug
I'm creating a VueJS front-end app that uses Wagtail CMS for the backend and connects through the Wagtail APIV2. The problem I'm having is when retreiving page information via the page slug. This query will not return additional fields, whereas queires by page type and page id will. The Blog model looks like this (I've trimed out some methods for brevity: class BlogPage(Page): intro = RichTextField(blank=True) body = StreamField(blocks.CMSStreamBlock(), blank=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) date = models.DateField("Post date") author = models.ForeignKey( settings.AUTH_USER_MODEL, default='', on_delete=models.SET_NULL, related_name='author_data', null=True, blank=True, limit_choices_to=limit_author_choices ) feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) class Meta: verbose_name = "Blog and Updates Page" content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('date'), FieldPanel('author'), ImageChooserPanel('feed_image'), FieldPanel('tags'), FieldPanel('intro', classname="full"), StreamFieldPanel('body'), ] api_fields = [ APIField('feed_img', serializer=ImageRenditionField('width-800', source='feed_image')), APIField('intro'), APIField('body'), APIField('tags'), APIField('date'), APIField('author') ] If I query http://localhost:8000/api/v2/pages/?type=cms.BlogPage&fields=* It returns: { "meta": { "total_count": 4 }, "items": [ { "id": 8, "meta": { "type": "cms.BlogPage", "detail_url": "http://localhost:8000/api/v2/pages/8/", "html_url": "http://localhost:8000/en/blog/first-blog-post/", "slug": "first-blog-post", "show_in_menus": false, "seo_title": "", "search_description": "", "first_published_at": "2017-10-18T22:54:14.709694Z" }, "title": "First blog post", "feed_img": { "url": "/media/images/DSC02705.width-800.jpg", "width": 800, "height": 534 }, "intro": "<p>Praesent placerat in eros sit amet gravida. Curabitur nec semper ligula, sit amet egestas sapien. Nullam feugiat non … -
How to use a given database to make queries within a method in djano?
Here is the case. A method or function has a couple of database queries. There are two databases, such as DATABASE_A and DATABASE_B. def method(): # database queries here orders = Order.objects.filter(...) products = Product.objects.filter(...) How to achieve the follows easily with decorator or any other ways? Can anyone give an example? # Here call method() using DATABASE_A # here call method() using DATABASE_B -
Django 'clearsessions' not actually doing anything
I'm using Django 1.10.7 and a database session backend. It's come to my attention that running the clearsessions command isn't doing anything for me. All of the DJANGO_SESSION rows in my database are still there, dating back as far as January. Is there some setting I have to include in the code in order for this to function properly? I thought I could simply run the clearsessions command and it would delete all sessions from my database older than 2 weeks. -
How to download file from django admin
I created FileField in class Part in models.py. Also I get the link of this file by method file_link(self): origin = models.FileField(upload_to='origin_files', null=True, blank=True) def file_link(self): try: return "<a href='%s'>download</a>" % (self.origin.url,) except PageNotAnInteger: return "<a href=127.0.0.1:8000/main>download</a>" file_link.allow_tags = True In admin.py I added readonly_fields for file_link. Also I added in fieldsets file_link: readonly_fields = ('file_link',) fieldsets = ( ('Характеристики плёнки', { 'fields': (....'data', 'origin', 'file_link') }), ) So, in my django admin I have FileField which allows to upload files to directory origin_files and link to this file. But when I click on this link I'm redirecting to home page of my site. For example, I downloaded file presentation.pptx. When I get url of this file I get http://127.0.0.1:8000/admin/description/part/12/change/origin_files/Presentation.pptx How I can download this file? -
django, save() missing 1 required positional argument 'request'
i tried create_user for email login as custom user model, but it's not working. save() missing 1 required positional argument 'request'. how can i solve this problem, help me please. this is Traceback.. File "/Users/maxx/.local/share/virtualenvs/testauth--sM0sqjl/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/Users/maxx/Documents/workspace/python3/testauth/users/views.py", line 12, in post user = serializer.save() TypeError: save() missing 1 required positional argument: 'request' models.py class UserManger(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('You must give email address') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser): email = models.EmailField(unique=True) nick_name = models.CharField(max_length=50) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManger() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True serializers.py class RegisterSerializer(serializers.Serializer): email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED) password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already … -
object has no attribute 'cleaned_data'
i have a model which is a image filed class Image(models.Model): Image = models.ImageField(upload_to='pic/',default='pic/1.png') and its my form class Getimageform(forms.Form): Image = forms.ImageField() and it's my viwe def GetImage(request): if request.method == 'POST': form = Getimageform(request.POST,request.FILES) if form.is_valid(): cd = form.cleaned_data image = cd['Image'] m = Image(Image=image) m.save() return HttpResponseRedirect('/') form = Getimageform() return render(request, 'test.html', {'form':form}) and it's my template <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> </head> <body> <form method="post" enctype="multipart/form-data">{% csrf_token %} <p> <input id="Image" type="file" class="" name="Image"> </p> <input type="submit" value="Submit" /> </form> </body> </html> but when i run this and submit image i got this error image -
Reverse for 'password_reset_done' with arguments with namespace
Under Django 1.8. I added a namespace to my app but now I have problem with registrations pages. Url: http://127.0.0.1:8000/accounts/password_reset/ # include registration app urls url(r'^accounts/', include('registration.urls')), url(r'^accounts/password_reset/$', password_reset, {'template_name': 'registration/password_reset.html'}, name='reset-password'), url(r'^accounts/password_reset_success/$', password_reset_done, {'template_name': 'registration/password_reset_done.html'}, name="password_reset_done"), Error: NoReverseMatch at /accounts/password_reset/ Reverse for 'password_reset_done' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I think I have to pass the namespace to the registrations urls somewhere. -
Heroku and Django: No default language could be detected for this app
I have followed the instructions given under a tutorial (Link here). I have even included the runtime.txt file with the proper version of Python. I have searched everywhere but no solution seems to work. My GitHub project link for reference: https://github.com/MithilRocks/chakri The error message: PS C:\Users\Mithil Bhoras\Documents\GitHub\chakri\chakri> git push heroku master Counting objects: 90, done. Delta compression using up to 4 threads. Compressing objects: 100% (80/80), done. Writing objects: 100% (90/90), 8.78 MiB | 234.00 KiB/s, done. Total 90 (delta 26), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to chakrilevels. remote: To https://git.heroku.com/chakrilevels.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/chakrilevels.git' -
Django slow query
This query is really slow and can't run after we upgraded Django 1.8.7 => 1.11.13 q = WorkReport.objects.filter( ~Q(case__customer=session.integration.null_customer), ~Q(product = None) | ~Q(work_type__bill_as_product = None), ~Q(case = None), ~Q(case__casesync__is_closed = True), employee__company=session.integration.company, productreportonquotationsync=None, productreportonordersync=None,productreportsync=None, productreportoncaseasinvoicesync = None, approved=True) -
GUI CSS picker in Django
I want to add a functionality which let the user choose a "interface theme': I added a dropdown in my base.html so the user can change the theme in all the templates. I use a base.html for all my html templates using {% extends 'base.html'%}. '# All my views will need this: theme = MyThemeModel.objects.filter(user=self.request.user).first().theme return render(request, 'mytemplate.html', {'theme': theme}) '#base.html {% if theme = 'theme 1'%} <link rel="stylesheet" type="text/css" href="{% static 'theme1.css' %}" /> {% else if theme = 'theme 2'%} <link rel="stylesheet" type="text/css" href="{% static 'theme2.css' %}" /> {% else if theme = 'theme 3'%} <link rel="stylesheet" type="text/css" href="{% static 'theme3.css' %}" /> {% endif%} I'm thinking of using AJAX so I can take the theme the user choose but then I will need to add a function in each existing view and I don't want to repeat that much of code. Is there an easier way to do this? -
writable create() method in drf serializers
models.py class Product(models.Model): product_name = models.CharField(max_length=32) quantity = models.IntegerField() remarks = models.TextField(blank=True) class Vendor(models.Model): vendor_name = models.CharField(max_length=50) address = models.CharField(max_length=100) bill_no = models.CharField(max_length=8) product = models.ManyToManyField(Product) serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class VendorSerializer(serializers.ModelSerializer): product = ProductSerializer(many=True, read_only=False) class Meta: model = Vendor fields = '__all__' How do I override writable create() to give products from vendors view where each products are uniquely related to Vendor?