Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difference between select_related() and prefetch_related() in django?
Can I use prefecth_related for foreign key field. I used select_related for a table containing foreign key fields. Can I use prefetch Instead of that? I am working on modelviewsets. models.py class Category(models.Model): category_name=models.CharField(max_length=100) active=models.BooleanField(default=True) def delete(self): self.active=False self.save(update_fields=('active',)) def __str__(self): return self.category_name class Brand(models.Model): brand_name=models.CharField(max_length=100) active=models.BooleanField(default=True) def delete(self): self.active=False self.save(update_fields=('active',)) def __str__(self): return self.brand_name class Product(models.Model): name=models.CharField(max_length=100) price=models.FloatField() details=models.TextField() category=models.ForeignKey(Category,on_delete=models.CASCADE,related_name='productshavecategory') brand=models.ForeignKey(Brand,on_delete=models.CASCADE,related_name='productshavebrand') stock=models.PositiveBigIntegerField() price_per_amount=models.CharField(max_length=100) rating=models.PositiveIntegerField(default=0) active=models.BooleanField(default=True) Special_offer=models.BooleanField(default=False) rating_count=models.PositiveIntegerField(default=0) average=models.FloatField(default=0) def delete(self): self.active=False self.save(update_fields=('active',)) def __str__(self): return self.name views.py class CategoryViewset(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] queryset=Category.objects.filter(active=True) serializer_class=CategorySerialaizer def list(self, request, *args, **kwargs): queryset=Category.objects.filter(active=True) if queryset.exists(): serializer=CategorySerialaizer(queryset,many=True) return Response({'status':True,'data':serializer.data,'message':'Category found'}) else: return Response({'status':False,'data':None,'message':'Category not found'}) class BrandViewset(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] queryset=Brand.objects.filter(active=True) serializer_class=BrandSerialaizer def list(self, request, *args, **kwargs): queryset=Brand.objects.filter(active=True) if queryset.exists(): serializer=BrandSerialaizer(queryset,many=True) return Response({'status':True,'data':serializer.data,'message':'Brands found'}) else: return Response({'status':False,'data':None,'message':'Brands not found'}) class ProductViewset(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] queryset=Product.objects.select_related('category','brand').filter( Q(active=True) & Q(stock__gt=0) ) serializer_class=ProductSerialaizer filter_backends = [DjangoFilterBackend,filters.SearchFilter] search_fields = ['name'] filterset_fields = ['category','brand'] def list(self, request, *args, **kwargs): queryset=Product.objects.select_related('category','brand').filter( Q(active=True) & Q(stock__gt=0) ) if queryset.exists(): serializer=ProductSerialaizer(queryset,many=True) return Response({'status':True,'data':serializer.data,'message':'Products found'}) else: return Response({'status':False,'data':None,'message':'Products not found'}) When I used prefetch_related instead of select_related I got same result and query set returned at almost same time. Is this a proper way? -
Can't import modules
I've searched for this problem and tried different solutions but can't fix it. In my Django project I have different apps and a non-app directory called 'testing_utils' with modules which serve for a testing purposes. In particular I want to import all available models to file dummy_factory.py. However when I simply import modules from my apps like so: from abc import ABC from datetime import date from users.models import User I get the error message ModuleNotFoundError: No module named 'users' Which is strange since I definetley can import models to some_app.views.py and access them. Here's an example of my project's directory: /home/user/dev/project/ ▸ project/ ▾ testing_utils/ dummy_factory.py ▾ users/ ▸ __pycache__/ ▸ migrations/ ▸ templates/ ▸ tests/ __init__.py admin.py apps.py models.py views.py manage.py* -
Is there a good way to develop a ERP/CRM application using django? Maybe using an existing example such as Acumatia, Odoo or SAP?
Ok so I am in the process of starting my own ERP(enterprise resource planning)/CRM(company resource management) company and would like to use django to develop the application. I have the database setup however the data in the tables I extracted is from another ERP. I need help piecing everything together. Can anyone help me? -
Retrive Data from specific year interval in djnago
How are you? I need some help please. I am working in Django and I need to make a query that should return a value in specific year interval. for example if year interval is 2 than it should return data for 10 years, if apply date was 2020 than it should return data in 2020, 2022, 2024 like that and if the apply date was 2023 and interval was 3, than it also should return data similarly. The Code is below, i have tried: diff = get_factors_of(i.year_num) componant3 = ComponentInfo.objects.filter(component__category__water_scheme = scheme,maintenance_interval__in = diff_year, apply_date__lte = i.end_date, interval_unit='Year').aggregate(labour_cost = Sum(F('labour_cost')*F('component_numbers'),output_field=FloatField()),\ material_cost = Sum(F('material_cost')*F('component_numbers'),output_field=FloatField()), \ replacement_cost = Sum(F('replacement_cost')*F('component_numbers'),output_field=FloatField()),\ maintenance_cost = Sum(F('maintenance_cost')*F('component_numbers'),output_field=FloatField()),) and the diff return method is : def get_factors_of(num): """Return factor of integer number""" factor_list = [1] for i in range(1, num + 1): if num == 1: factor_list = [x for x in range(1,15)] elif num % i == 1: factor_list.append(i) return factor_list this method should return a specific interval range -
Deploying to production a Django app - Azure
I have a Django app in a Github repo. Through a Github action, it is deployed as a Python app in Azure. In the Azure portal: 1- In "Configuration > Application" settings, I've defined POST_BUILD_COMMAND as python manage.py makemigrations && python manage.py migrate as described in Configure a Linux Python app for Azure App Service. 2- I have configured a deployment slot and a production slot. It offers a 'Swap' option, to push the live app in the deployment slot to production. However, I'm under the impression that doing that doesn't run the POST_BUILD_COMMAND command for the production Django app, leaving the database unaltered - which means that the production frontend gets the new fields/updates, but the migrations don't occur. What's the best way to perform the migrations in production? Would the correct way be to set "Configurations > General settings > Startup Command" to 'python manage.py makemigrations && python manage.py migrate'? Would that work? -
Connection to server at "localhost" failed in Docker - Django
Im very new to Docker and im trying to create a one for my django application. but i encounter the error "Is the server running on that host and accepting TCP/IP connections?connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address" I've tried this and this and this . Basically everything I could find but still doesnt work . Docker-compose version: '1' services: web: build: . container_name: evident_django hostname: evident_django restart: always image: evident:latest volumes: - ./logs:/var/log/evident - ./src:/code - static_volume:/code/static expose: - 7000 ports: - "127.0.0.1:7000:7000" env_file: - ./src/.env depends_on: - db networks: - evident_network db: image: postgres:13-alpine restart: always container_name: evident_postgres hostname: evident_postgres volumes: - ./storage:/var/lib/postgresql/data/ env_file: - ./src/.env expose: - 5432 networks: - evident_network volumes: static_volume: networks: evident_network: driver: bridge Dockerfile FROM python:3.10.4-slim-bullseye COPY requirements.txt /requirements.txt RUN set -ex \ && BUILD_DEPS=" \ apt-utils \ build-essential \ ffmpeg libsm6 libxext6 \ postgresql-client \ python3-opencv \ " \ && apt-get update && apt-get install -y --no-install-recommends $BUILD_DEPS \ && pip install -U --force-reinstall pip \ && pip install --no-cache-dir -r /requirements.txt \ && rm -rf /var/lib/apt/lists/* RUN mkdir /code/ WORKDIR /code COPY /src . EXPOSE 7000 ENTRYPOINT [ "./entrypoint.sh" ] and the errors im getting … -
Create multiple user types in django
I want to create multiple user types in Django. Each type has several unique attributes, and some common like username and email. The code below creates 3 tables with one to one connection to the Account user model. However I want to add choice field to the user model and store user types in tuples, instead of creating is_type1 is_type2 etc. variables, but I'm not sure how to connect those types with it's class. Here is my account model in models.py: class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=255, unique=True) username = models.CharField(verbose_name='username', max_length=30, unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_type1 = models.BooleanField(default=False) is_type2 = models.BooleanField(default=False) is_type3 = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True And here is my subclasses: class Type1(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True) #unique attrs def __str__(self): return self.account.username class Type2(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True) #unique attrs def __str__(self): return self.account.username class Type3(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True) #unique attrs def __str__(self): return self.account.username -
In Django how to add a placeholder to a form based on model charfield
I have a form: class SideEffectForm(ModelForm): class Meta: model = SideEffect fields = ['se_name'] def __init__(self, *args, p, **kwargs): super().__init__(*args, **kwargs) if p == 'antipsychotic': self.fields['se_name'].choices = [ ("insomnia_and_agitation", "Insomnida and Agitation"), ("akathisia", "Akathisia"), ("dystonia", "Dystonia"), ] That is based on this model: class SideEffect(TimeStampedModel): SE_CHOICES = [ ("insomnia_and_agitation", "Insomnida and Agitation"), ("akathisia", "Akathisia"), ("anticholinergic_effects", "Anticholinergic Side Effects") ] se_name = models.CharField("",max_length=200, choices=SE_CHOICES, blank=False) concern = models.IntegerField("",default=50) case = models.ForeignKey(Case, on_delete=models.CASCADE) As it stands the form displays the first option. I would however like to have a place holder e.g. 'Please select a side effect'. I could do this by having it as one of the options but would prefer not to as then would need to implement measures to stop the placeholder being saved as a valid user entry. I have tried a range of suggestions on the site but none have been sutiable -
Django : Plotly plot shows on localhost but not on heroku
I am trying to display some plots(created with plotly) on my page, it works totally fine on localhost but when deployed on heroku the plots are not shown. code to create plot in views.py def icons(request, name): l1 = testtable.objects.values() d1 = [] d2 = [] for i in l1: d1.append(i["d1"]) d2.append(i["d2"]) fig =px.bar(x=d1,y=d2) photo = plotly.io.to_html(fig,config= {'displayModeBar': False}) fig2 = px.line(x=d1, y=d2) photo1 = plotly.io.to_html(fig2,config= {'displayModeBar': False}) return render(request, 'icons.html', {'name':name,"photo":photo,"photo1":photo1}) code in icons.html {% extends 'index.html' %} {% block content %} <div class="content icon-content"> <div class="container icon-container"> <h3 class="icon-heading">Quick Launch</h3> <div class="icon-bar"> <a class="active" href="#"><i class="fas fa-hand-pointer fa-2x"></i><span>Time In/Out</span></a> <a href="#"><i class="fa-solid fa-copy fa-2x"></i><span>My Attendance Record</span></a> <a href="#"><i class="fa-solid fa-calendar-minus fa-2x"></i><span>My Leave List</span></a> <a href="#"><i class="fa-solid fa-file-invoice-dollar fa-2x"></i><span>My Payslips</span></a> <a href="#"><i class="fa-solid fa-calendar-check fa-2x"></i><span>Apply Leave</span></a> <a href="#" class="timesheet-icon"><i class="fa-solid fa-calendar-days fa-2x"></i><span>My Timesheet</span></a> <a href="#" class="team-icon"><i class="fa-solid fa-people-group fa-2x"></i><span>My Team</span></a> </div> </div> <hr> <div class="container icon-container"> <h3 class="icon-heading">Pending My Approval</h3> <div class="icon-bar"> <a class="active" href="#"><i class="fa-solid fa-file-circle-check fa-2x"></i><span>Leave</span></a> <a href="#"><i class="fa-solid fa-user-check fa-2x"></i><span>Attendance Regularization</span></a> <a href="#"><i class="fa-solid fa-business-time fa-2x"></i><span>Timesheet</span></a> </div> </div> <div> {% if photo %} {{ photo|safe }} {% else %} <p>No graph was provided.</p> {% endif %} </div> <div> {% if photo1 %} {{ photo1|safe }} {% … -
Django ManyToMany field relationship confusion
I am using Django 3.2 I am writing an app for commuities, and I want to be able to provide functionality for Administrators of a Community, as well as functionality to allow users to request access to restricted or private Groups. I seem to be getting myself confused with the ManyToMany relationships. This is what I have so far (redacted): class Community(models.Model): pass # Group of administrators responsible for moderation and membership approvals # (for restricted and private communities) # Note: administrators can autopost and delete topics and comments class CommunityAdministrator(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT) community = models.ForeignKey(Community, on_delete=models.CASCADE, related_name="administrators") class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'community'], name='idxu_commty_admin') ] # Community membership approvals (for restricted and private communities) # class CommunityMembership(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT) communities = models.ManyToManyField(Community, though='CommunityMembershipApproval') class CommunityMembershipApproval(models.Model): PENDING = 0 APPROVED = 1 REJECTED = 2 APPROVAL_STATES = ( (PENDING, 'Pending'), (APPROVED, 'Approved'), (REJECTED, 'Rejected') ) person = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) community = models.ForeignKey(Community, on_delete=models.CASCADE) approval_state = models.PositiveIntegerField(choices=APPROVAL_STATES, default=PENDING) request_tstamp = models.DateTimeField(auto_now=True) Will the tables above allow me to implement the functionality I described above - namely: Administrators - allow me to add/remove administrators of a community, and also access the administrators of a community via an … -
use ->, #> operators in django JSONfield ORM
I would like to use ->, #> operators with Django ORM. at the moment I was able to perform only: ModelWithJsonField.objects.filter(id=1).values('outputs__key') that is translate from ORM in: SELECT ("app_model_with_json_field"."outputs" #> ARRAY['key']) FROM "app_model_with_json_field" WHERE "app_model_with_json_field"."id" = 1; args=(['key'], 1) but .values() it can't be used with single object, so if I try: ModelWithJsonField.objects.get(id=1).values('outputs__key') Any ideas to how perform this kind of operators in Django ORM? -
How to get actual return value instead of task id in celery?
I have a django app to run some linux commands accepted from a form. I'm implementing both actual process, and one using celery. I pass arguments to celery task and want to get return value from it, but I'm getting only the task id I guess. This is me running celery task in views.py: if 'celeryform' in request.POST: command = request.POST.get('command') rep = request.POST.get('rep') dur = request.POST.get('dur') cmd ='powershell -command '+command result=celery_run.delay(cmd,rep,dur) context = {'output':result} return render(request,'home.html',context) This is my tasks.py: from __future__ import absolute_import,unicode_literals from celery import Celery, shared_task import time,subprocess app = Celery('tasks', broker='redis://localhost:6379',include=['problem.tasks.add']) @shared_task def celery_run(cmd,rep,dur): output='' for i in range(int(rep)): time.sleep(int(dur)) p=subprocess.run(cmd,capture_output=True,text=True,shell=True) output += p.stdout return output I display my output in a textarea in a webpage, I'm getting output as d59af727-b24d-4518-9b66-dff063864c4a The above one is task id I guess How to get actual return value? Sample return value using normal method with command=pwd,rep=1,dur=2 Path ---- D:\betsol\Linux_command_app Path ---- D:\betsol\Linux_command_app -
Change object label on specific value in js
I'm working on charts in React.js and i want to display data sorted by month. In django i've created view for displaying json with total events per month and it looks like this: [ { "month": "2022-06-01T00:00:00+02:00", "total": 4 }, { "month": "2022-08-01T00:00:00+02:00", "total": 1 } ] ] I would like to sort every object in that array and change value 'month' from numbers to month name, so it would be: [ { "month": "june", "total": 4 }, { "month": "august", "total": 1 } ] ] For generating charts i'm using chartist. -
Django IntegrityError when change data in admin
Sorry I don't know much about deployment, My django rest framework project (I'm using it as a backend API), works fine in my computer, I can access to my django admin page and do modifications. The problem is, when I deployed my project to a server (I used nginx and gunicorn), I can't change data in django admin page, but I can see data and all my models. The message I get when I try to modify a model's data : IntegrityError at /admin/myproject/study/185/change/ Error: null value in column "id" violates not-null constraint PS: I don't have an id column in my Model, and I already run migrations PS: I use postgresql I imported the database that I have exported from my local project -
Explicity enable cache in Django by function/endpoint but not site wide
Our Django application is quite big, and it has reached the point where Caching in certain parts will improve a lot the performance. However, when we enable caching it will do site wise, and so some endpoints are failing for different reasons. Our ideal solution therefore would be to have cache by explicitly setting it by function or rest api endpoint, and all the rest disable by default. In order to enable it we could just use the decorator: @cache_page The problem is that I cannot get the default cache to be disabled, I tried these different options but non of them seem to work. CACHES = { 'manual': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } -- CACHES = { 'default': {}, 'manual': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } -- CACHES = { 'default': None, 'manual': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } -
icant see my 404 and 500 custome pages in django
hello i try to make a custom 404 and 500 pages in my django project so when i use this codes i cant see any result ! views.py: def handle404(request,exception): return render(request,'400.html',status=404) def handle500(request): return render(request,'500.html',status=500) url.py : handler404 ='base.views.handle404' handler500 = 'base.views.handle500' i see only this page : enter image description here anybody have some suggestions to improve my code ? -
list action with modal(not intermidiate page) to update model with input value
I want to update a list of model with input values but using modal instead of intermediate page, I googled a lot but I don't find any help, can someone give me some helps ? -
QR Application in Python
I want to create Django application. The logic is next: I scan the QR-code using QR- scanner, and then send this code to the web app. After that the app connect with Data Base and regarding to this information display some information. Could you give advice how to start this project, maybe some examples? i don't understand how looks the process of sending qr code from Qr scanner to app. -
Google Cloud Run + Django + RabbitMQ (or another message broker)
I have a contenerized Django application, which I deployed on Google Cloud Run. For the most time no requests are made to the app, so GCP can reduce it to 0 instances (and the billing is small). Some requests provide time consuming tasks and I need to handover them to another service by RabbitMQ (or possibly another message broker). I wanted to use pika at the Django app side, but if I understand correctly it forces it to be running all the time. So is there a solution, where I can pass messages to message broker from Django app and also listen to message queue, but the app can reduce to 0 instances when the queue is empty (and increase instances if it's not)? Thanks -
Date filter binned data
I have a model in django that contains a start and end date for a financial year and a value for demand volume. start_date = models.DateField(null=True) end_date = models.DateField(null=True) new_demand = models.PositiveIntegerField(default=0) I would like to filter this data on a given date range that may not coincide with the date ranges of the data, taking a proportion of the demand from each data point that may fall somewhere in the filter date range. I am assuming I need to work out if the data point falls over the edge of the filter and divide the demand by the number of days inside the filter? But I am having a hard time trying to write this. any help would be appreciated! :) -
How to count my checkboxes and insert to my vizualization of my table?
I have a problem that looks really simple to solve but I can't find the solution. I have in my django model a field nb_engins corresponding to an integerfield, my model is of this type : models.py class Flottes(models.Model): name = models.CharField(max_length=255, null=True) nb_engins = models.IntegerField(validators=[MaxValueValidator(9999999999)], default=0) engins = ArrayField(models.CharField(max_length=555, blank=True), null=True) calculateur = models.CharField(max_length=555, null=True) type_fichier = models.CharField(max_length=255, null=True) created_at = models.DateTimeField(auto_now_add=True, null=datetime.date.today) Here are now my 2 functions, one is used to retrieve the selected checkboxes and the other to validate my form component.ts // Get List of Checked Items getCheckedItemList(){ this.checkedList = []; this.count = 0; for (var i = 0; i < this.engins.length; i++) { if(this.engins[i].isSelected) this.count = this.count+1; this.checkedList.push(this.engins[i]); } this.checkedList = JSON.stringify(this.checkedList); } submitForm(): void { const { value } = this.form; // get selected fruit from FormGroup value const selectedEngin = value?.engins?.filter((f: Engins) => f.checked) || []; // form value binded console.log('current form value: ', value); console.log('only selected form value: ', selectedEngin); // original value from database not change console.log('original engins list: ', this.engins); this.result = { name: value?.name || '', selectedEngin, nb_engins: value?.checkedList|| '', calculateur: value?.calculateur || '', type_fichier: value?.type_fichier|| '', } alert('La flotte a été enregistré avec succès !'); this.api.registerFlotte(this.form.value) .subscribe((res:any)=>{console.log(res)}); … -
Infinity loop when i override the get() method in a class based view django
I want to override the get method. But I get the error : The view auctions.views.AuctionsDetail didn't return an HttpResponse object. It returned None instead. If I use a httpresponse I reload the function and call the function again. How can solve this? Its a detail view ''' def get(self, request, *args, **kwargs): list_auction = self.kwargs['pk'] set_current_bid=Bids.objects.filter(listing_auctions__id = list_auction).latest('id') print(f'offer {set_current_bid.offer}') return HttpResponseRedirect(reverse('auctions_detail', args=(list_auction,))) ''' -
Django quick quest on making queries for blog posts and categories
I have a blog page showing all the user's posts. Each post has a 'Category'. (Ex: Post 1 --> category: general coding, Post 2 --> category: general coding, Post 3 --> category: web dev) If I wanted to show all the categories that the user posted in (Ex: User profile page listview--> Categories posted --> general coding, web dev ) , would I have to use a 'for loop' and put them in a list? Or is there a better way to do this. posts = user.post_set.all() category_list = [] for post in posts: if post.category not in category_list: category_list.append(post.category) models.py class Category(models.Model): category_name = models.CharField(max_length=50, default='general coding', verbose_name="Categories") class Post(models.Model): title = models.CharField(max_length=100, help_text="100 characters or less") content = models.TextField() category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) liked = models.ManyToManyField(Profile, blank=True, related_name='likes') -
Django model constraint for ensuring one or both fields are not empty strings
Following this answer I want to set up a constraint on a Django model that ensures one or both of two fields are set. However, while that answer assumes the empty fields are NULL, in my case they are always empty strings. I'm not sure how to check for that in the constraint. from django.db import models from django.db.models import Q class Person(models.Model): firstname = models.CharField(max_length=150, blank=True, null=False, default="") surname = models.CharField(max_length=150, blank=True, null=False, default="") class Meta: constraints = [ models.CheckConstraint( name="%(app_label)s_%(class)s_firstname_and_or_surname", check=( Q(firstname__exact="", surname__exact!="") | Q(firstname__exact!="", surname__exact="") | Q(firstname__exact!="", surname__exact!="") ), ) ] This should work except that, unlike surname_isnull=False, surname__exact!="" isn't valid syntax. I know that if I had a queryset I could use exclude(surname__exact="") to mean "is not empty", but I'm not sure how to do that in this constraint with Q() expressions. -
how safe is it to use post requests through ajax?
I'm making inventory control applications in django. All data from the database is taken through ajax and api, that is, get, post and put requests. I use django view only to display html templates I need advice on how safe it is to use code like this: function iterTable() { let items = []; let docDate; let docContragent; let docWare; let comment; let table = document.querySelector(".invoice-add-table table"); for (var i = 1, row; row = table.rows[i]; i++) { if(row == document.querySelector('.add-elements')) { break; } docDate = document.querySelector('input[name="invoice-date"]').value docContragent = document.querySelector('select[name="invoice-contragent-select"]').value docWare = document.querySelector('select[name="warehouse-select"]').value comment = document.querySelector('textarea[name="invoice-comment"]').value // ITEMS let name = row.cells[1].querySelector('span').dataset.id let quantity = row.cells[2].querySelector('input').value let buy_price = row.cells[3].querySelector('input').value let sell_price = row.cells[5].querySelector('input').value items.push({ "product": name, "buy_price": buy_price, "sell_price": sell_price, "quantity": quantity, }); } let invoice = { "warehouse": docWare, "date": docDate, "comment": comment, "contragent": docContragent, "items": items } let json = JSON.stringify(invoice); const csrftoken = Cookies.get('csrftoken'); $.ajax({ data: json, contentType: "application/json; charset=utf-8", type: "POST", // GET or POST headers: {'X-CSRFToken': csrftoken}, url: "http://127.0.0.1:8000/warehouse/api/notes/", success: function (response) { alert('ok') }, error: function (response) { console.log(response.responseJSON.errors) } }); return false; } document.querySelector('span[name="note-submit-btn"]').addEventListener("click", iterTable); serialisers.py def create(self, validated_data): last_num = ConsignmentNote.objects.filter(warehouse__company=self.context['request'].user.company).latest('id') items = validated_data.pop('items') note = ConsignmentNote.objects.create(**validated_data, doc_type = 1, number …