Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Two related models but error: using variable before assignment
I have 2 models that are closely related but I keep getting the error: Using variable 'Bid' before assignment The problem is if I move Bid before Listing, I will still get the same error of course because I will have mentioned Listing before assignment. I did just add the highest_bid field to my Listing model so maybe there is a better way of structuring my models. Essentially, I want all the bid_inputs for a listing to be stored in Listing.highest_bid but I want the highest_bid to only every display the max value. I am wondering if this is maybe something I could work out in my views.py rather than having a separate field for it? models.py class Listing(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='active') options = ( ('active', 'Active'), ('closed', 'Closed'), ) title = models.CharField(max_length=64) description = models.TextField(max_length=64) start_price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0.99)]) image = models.URLField(max_length=200, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings") lister = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True, blank=True) date_added = models.DateTimeField(default=timezone.now) highest_bid = models.ForeignKey(Bid, on_delete=models.CASCADE, max_digits=9, decimal_places=2, default=None, null=True) status = models.CharField(max_length=10, choices=options, default="active") favourites = models.ManyToManyField(User, related_name="favourite", default=None, blank=True) objects = models.Manager() listingmanager = NewManager() def __str__(self): return f"{self.title} ({self.pk}, Β£{self.start_price}, {self.lister})" class Bid(models.Model): bidder_user = models.ForeignKey(User, β¦ -
How to get the difference of 2 different django models fields?
I have here 2 django database table class ProductName(models.Model): name = models.CharField(max_length=100) class Inventory(models.Model): product = models.ForeignKey(ProductName, on_delete = models.CASCADE ) qty = models.PositiveIntegerField() class Sold(models.Model): product = models.ForeignKey(ProductName, on_delete = models.CASCADE ) qty = models.PositiveIntegerField() I would like to have an inventory table page wherein I can see the total qty left in Inventory (for example: Inventory.qty - Sold.qty) . how to do this in Django ? -
Django - Initial form field values not showing
I am trying to set the initial value of a form field. I have approached it the following ways: forms.py: class FilterGigsForm(forms.Form): field = forms.IntegerField(label="", required=False, initial=5) def __init__(self, *args, **kwargs): instance = kwargs.get('instance', None) kwargs.update(initial={ 'field': 5, }) super().__init__(*args, **kwargs) self.fields['field'].initial = 5 views.py class HomePage(FormMixin, TemplateView): template_name = 'index.html' model = MyModel form_class = MyForm def get(self, request, *args, **kwargs): form = MyForm(self.request.GET, initial={'field': 5,}) ... return render(request, 'index.html', {"form": form, }) However, none of these approaches are working and the initial value is not showing when I load/reload the page. -
request from client side comes in array, how to handle it with Django rest framework filter
As I mentioned in heading, client side filter request comes in this pattern from tabulator data table to rest framework back end. /?page=1&size=10&filters[0][field]=q&filters[0][type]=like&filters[0][value]=something i have tried this way but it is not working class MemberListApiView(TemplateView): template_name = 'api/member_list_api.html' def get_context_data(self, **kwargs): context = super(MemberListApiView, self).get_context_data(**kwargs) return context class MemberListSerializerView(generics.ListAPIView): model = Membership serializer_class = MemberSerializer pagination_class = CustomPagination def get_queryset(self): queryset = Membership.objects.members() query = self.request.query_params.get('filters[value][0]', None) if query is not None: queryset = queryset.filter( Q(user__username__icontains=query) | Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) ) return queryset -
Troubles with making migrations on django x docker x postgres project
Im having troubles running migrations in my django docker project. Here is my current project structure: Main Project Directory βββ Backend β βββ main_app_folder (settings.py is here) β βββ sub_app_1_folder β βββ sub_app_2_folder βββ _Frontend β βββ Frontend folder β βββ standard create_react_app folder structure β βββ Dockerfile(to build frontend image) βββ nginx β βββ Dockerfile β βββ nginx-proxy.conf β βββ uwsgi params βββ scripts β βββ entrypoint.sh βββ .dockerignore βββ .env βββ Dockerfile βββ docker-compose.yml βββ requirements.txt βββ .gitignore Here is the main Dockerfile thats in the root directory responsible for booting up the backend folder: # Pull base image FROM python:3.8-alpine # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PATH="/scripts:${PATH}" RUN apk update #Copy our backend folder and place it inside the image RUN mkdir /dockerbackend COPY ./requirements.txt /dockerbackend COPY ./backend /dockerbackend COPY ./scripts /dockerbackend WORKDIR /dockerbackend #Installing dependencies, remove those that are not needed after the installation RUN \ apk add libpq &&\ apk add --no-cache --virtual .build-deps gcc postgresql-dev libc-dev make git libffi-dev openssl-dev python3-dev libxml2-dev libxslt-dev gcc musl-dev && \ apk add jpeg-dev zlib-dev libjpeg &&\ pip install -r requirements.txt &&\ apk del .build-deps #Create media and static directories RUN mkdir -p β¦ -
Django Form Is Valid not producing any errors but returning False
I'm trying to update an existing model row (add choices to an existing ManyToMany field with previous entries) with a form but when I use the is_valid() it returns false, I have checked for errors in a few ways but no errors are being displayed I have used in my template: {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="errorlogin"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="errorlogin"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} and, in my views, after the is_valid and before the is_valid function is called: print(form.errors) My code is below: views.py def lessonRecord(request,id): if request.method == "POST": id = Lessons.objects.get(id=id) form = forms.LessonAddForm(request.POST,instance=id) if form.is_valid(): form.save() return redirect('lessons:lessonsView') else: print(form.errors) else: id = Lessons.objects.get(id=id) form = forms.LessonAddForm(instance=id , user=request.user) return render(request,'lessons/lesson_record.html',{'id':id,'form':form}) forms.py class LessonAddForm(forms.ModelForm): def __init__(self, user,*args, **kwargs): super(LessonAddForm, self).__init__(*args, **kwargs) self.fields['attendees'].queryset = CustomUser.objects.filter( Q(username=user) | Q(customuser__username=user) ) class Meta: model = models.Lessons fields = ['attendees'] -
Html submit button don't work after add jquery
Html submit button did work finely before add jquery script. But when i add jquery script in User Academic Information html submit button doesn't work. This template did work in django. i added jquery in id="form_set" And when i also add style="display:none" in id="empty_form" submit button don't work Here is html code: {% extends 'base/base.html' %} {% load static %} {% block content %} <div class="card"> <form class="form-horizontal" action="/" method="post"> {% csrf_token %} <div class="card-header"> <strong class="icon-user"> User Basic Information</strong> <hr class="divider" /> </div> <div class="card-body"> <div class="form-horizontal"> {% for field in employ_basic_forms %} <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"><h6>{{ field.label_tag }}</h6></label> <div class="col-md-9">{{ field }}</div> </div> {% endfor %} <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"><h6>Select Employ Designation:</h6></label> {% for field in user_role %} <div class="col-md-9">{{ field }}</div> {% endfor %} </div> </div> </div> <div class="card-header"> <strong class="icon-book"> User Academic Information</strong> <hr class="divider" /> </div> <div class="card-body"> <div class="card-body"> <div class="form-horizontal"> {{ employAcademicFormSet.management_form }} <div id="form_set"> {% for form in employAcademicFormSet %} {% for field in form.visible_fields %} <table class="no_error"> <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"><h6>{{ field.label_tag }}</h6></label> <div class="col-md-9">{{ field }}</div> </div> </table> {% endfor %} {% endfor %} </div> <input type="button" value="Add More" id="add_more" /> β¦ -
Django, link a model field with an admin model field with ForeignKey
I'm trying to link a "normal" model field with an admin model field, for example I have a table "Post" and I want to add the admin username as a ForeignKey to the field "Author" of the table Post. I mean : class Post(models.Model): title = models.CharField(max_length=50) body = RichTextField(blank=True, null=True) date = models.DateTimeField('date_posted') username = models.ForeignKey(admin.username, on_delete=models.CASCADE) Where admin.username refers the username of auth_user admin model Thanks for your help -
How to pass multiple kwargs parameter to Django Class Based View (ListView) at HTML page?
Views.py class CalendarWeekView(LoginRequiredMixin, generic.ListView): login_url = 'signup' model = Event template_name = 'calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) w = int(self.request.GET.get('week', None)) cal = Calendar(d.year, d.month, w) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) context['current_month'] = current_month(d) context['next_week'] = next_week(w) return context urls.py app_name = 'calendarapp' urlpatterns = [ path('week/', views.CalendarWeekView.as_view(), name='calendarWeek'), ] calendar.html href="{% url 'calendarapp:calendarWeek' %}?{{ next_week}}/?{{ current_month }}" How to pass multiple kwargs parameter to Django Class Based View (ListView) at HTML page using URL Path at HTML page ? -
My function is missing 1 required positional argument: 'request'
I am currently working on my first website, and I'm experiencing some trouble in views.py. Specifically this def: def translated_view(self, request): text = request.POST.get('text') translate = self.translator context = { 'translated': translate(text) } return render(request, context, 'main/translated.html') As you can see I have the request argument. However I'm still seeing this error. -
Nginx somtimes said "Forbidden β You donβt have permission to access / on this server"
I have deployed my Django application with the Nginx web server on Linode and my site is running correctly but sometimes, I don' know why, when I try to access my site I have the error: Forbidden You don't have permission to access / on this server my domain name is: dontrepeatyourself.org try to access it and see the error. Note that this error does not appear all the time, sometimes I can access my site normally. Here is my configuration for Nginx: /etc/nginx/nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 1024; } http { sendfile on; tcp_nopush on; tcp_nodelay on; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; include /etc/nginx/conf.d/*.conf; add_header X-Content-Type-Options nosniff; add_header X-Frame-Options SAMEORIGIN; add_header X-XSS-Protection "1; mode=block"; server_tokens off; keepalive_timeout 75; } /etc/nginx/conf.d/dontrepeatyourself.conf server { if ($host = www.dontrepeatyourself.org) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = dontrepeatyourself.org) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name dontrepeatyourself.org www.dontrepeatyourself.org; return 301 https://dontrepeatyourself.org$request_uri; } server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; # ssl stuff server_name dontrepeatyourself.org www.dontrepeatyourself.org; β¦ -
How to get a YAML file containing api keys to work in django?
I'm new to django and I am trying to make an API call to ebay when a user clicks a button, using ebay python SDK. There is a YAML file inside my project which contains the api keys. In my app, I have a python file that contains a function that makes the api call. When I run the function that python file separately, it works fine and finds the YAML file no problem. But when I try to run that same function from views.py, it gives me an error that says - config file 'ebay.yaml' not found. Can anyone please help me with this as I have no idea what's wrong... Do I have to do anything special when running the API call through django, besides just having a YAML file in the same direcotry? -
Using Apache Ignite with Django
We have an existing Apache Ignite in-memory DB with lots of stored data. I want to connect my existing Django web application to the Ignite DB in order to query the existing data. Are there any examples of how to connect a Django application to an Apache Ignite DB and how to query the DB using the Django ORM? -
How to set default value for a ManyToManyField in Django
models.py: from django.db import models class Department(models.Model): departmentName = models.CharField(max_length=100) def __str__(self): return self.departmentName class Designation(models.Model): designationName = models.CharField(max_length=100) def __str__(self): return self.designationName class Employee(models.Model): name = models.CharField(max_length=100) email = models.EmailField(unique=True, blank=False) department = models.ManyToManyField(Department, blank=True) designation = models.ForeignKey(Designation, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name My query/requirement: Employee and Department are linked by M2M. I set blank=True to overcome the form validation of no department being chosen. (null=True doesn't seem to be working with M2M) Let's say, scenario 1: while creating a new Emp, if there is no department provided then it should set to RP(Resource pool) by default. scenario 2: An existing Emp is from the HR department; assuming for some reason the HR dept is being deleted or Emp is being kicked out, now that Emp has no department linked to it, it should move to RP(Resource pool) by default!! How to arrange the default department- RP in Django such that both the scenarios are passing!? Thanks in advance :) Dueces -
Django - Updating a value of a field every 24 hour automatically
I have the following model in my django project: class Player(models.Model): creation_time = models.DateTimeField(auto_now_add=True) player_name = models.CharField(max_length=100, blank=False) ... player_lifetime = models.IntegerField(default=100) class Meta: ordering = ['creation_time'] So, the Player instance gets the lifetime value 100 during its creation. Now, I want to update the value of this field every 24 hour by subtracting it with -10. After 1 day, this value should be 90, after the second day it should be 80 and so on. How, can I let Django update this value for me automatically/periodically ? -
Field 'id' expected a number but got 'xyz'
In Models.py class Post(models.Model): user = models.CharField(max_length=100) likes = models.IntegerField(default=0) content = models.TextField() date = models.DateTimeField(auto_now_add=True) class Profile(models.Model): following = models.ForeignKey('User',on_delete=models.CASCADE,related_name='following') user = models.ForeignKey('User',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.user In views.py def viewProfile(request,username): posts = Post.objects.filter(user=username).order_by('id').reverse() profile = Profile.objects.filter(user=username) no_of_followers = profile.following.count() return render(request, "network/profile.html",{ "posts":posts, "username":username, "no_of_followers":no_of_followers }) In profile.html {% extends "network/layout.html" %} {% block body %} <h2 style="margin-left: 20px;">Posts of {{username}}</h2> <div class="col-sm-6"> <div class="card"> <div class="card-body"> <h5 class="card-title">Profile Details</h5> <p class="card-text">Followers:{{no_of_followers}}</p> <p class="card-text">Followings:0</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% for post in posts %} <div class="card" style="width:70%;margin-left: 10%;margin-right: 20%;"> <div class="card-body"> <a href="{% url 'viewprofile' post.user %}"><h5 class="card-title">{{post.user}}</h5></a> <div class="form-group"> <p>{{post.date}}<br>{{post.content}}</p> </div> <p>{{post.likes}}</p> </div> </div> {% endfor %} {% endblock %} Facing an error of Field 'id' expected a number but got 'xyz'. xyz is the username If I replace profile = Profile.objects.filter(user=username)with profile = Profile.objects.filter(user__user=username) then I am getting the error django.core.exceptions.FieldError: Related Field got invalid lookup: user -
summation two similar objects based on the name django
i try to make a system for a storage , sometimes it happen two similar objects are entry in two different time , i have summation the quantity of both and looks like one object instead of two different object for example i've entry this data one week ago name=mouse , qnt=20 , price=20 and today i add a new collection of mouse (the same mouse as before) name=mouse , qnt=10 , price=15 i have to whenever i face similar problem it automatically summation quantities =(30) and price = ((20+15)/2) instead of creating a new object to the second mouse object this is my model class Products(models.Model): name = models.CharField(max_length=20,unique=True) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) def __str__(self): return self.name class Collections(models.Model): name = models.ForeignKey(Products, on_delete=models.CASCADE) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) i dont need to create new object to the same product as exist in collection , i have to just summation the quantities ?! is it possible ?thanks -
insert django tag in react gatbsy helmet
I have to put a django tag inside the head, so the template will render the dynamic metatags server side. what I want to do is: {% block metatags %} <meta name="description" content="{{ metatags.description }}" /> <meta name="keywords" content="{{ metatags.keywords }}" /> <meta property="og:url" content="{{ metatags.og_url }}" /> <meta property="og:title" content="{{ metatags.og_title }}" /> <meta property="og:description" content="{{ metatags.og_description }}" /> <meta property="og:image" content="{{ metatags.og_image }}" /> <meta property="og:image:url" content="{{ metatags.og_image_url }}" /> <meta property="og:image:type" content="{{ metatags.og_image_type }}" /> {% endblock %} Now, no problems for the meta tags inside helmet, since it's a accepted element for helmet. The problem is for the {% block metatags %} and {% endblock %}. The compiled page won't have those two, probably because helmet ignores them. I tried also to put manually {% block metatags %} and {% endblock %} in the compilated page and it works. I think I cannot achieve this with just helmet, since it will ignore every tag I put inside which are not recognised (script,meta,noscript,..). How could I do that? The only solution maybe it's call a script after gatsby build and add those manually.. any better solutions? -
Getting the difference of quantity between 2 different django model fields?
I have here 2 django database table class Inventory(models.Model): product_name = models.CharField(max_length = 100) qty = models.PositiveIntegerField() class Order(models.Model): product = models.ForeignKey(Inventory, on_delete = models.CASCADE ) qty = models.PositiveIntegerField() I would like to have an inventory table page wherein I can see the total qty left in Inventory (for example: Inventory.qty - Order.qty) . how to do this in Django ? -
set default image to ImageField for existing objects in django
I have a model which has an ImageField. class A(model.Model): blah = CharField(max_length=10) profile = ImageField(upload_to='uploads/', null=True, blank=True) I want to set a default image for existing data, so I tried saving the file in shell like the following: >>> myapp.models import A >>> from django.core.files import File >>> for a in A.objects.all(): >>> a.profile.save('default.jpg', File(open('/Users/myusername/Pictures/default.jpg', 'rb'))) I was quite happy, until I found out that in myprojectroot/media/uploads/ there are as many defaultblablah.jpg files as the number of A objects. I'd like to know if there's any way to set the same image file with all objects as you do with update() method. Could someone can shed some light on it? Thank you in advance. -
Django how to efficiently export large Excel file
I have a really large database (billions of rows) that a user can query through a website build with django. I would like to offer the possibility for the user to download the results of their query in excel format. Currently the code is like: from excel_response import ExcelResponse qs = data.objects_in(db) qs_results = qs.filter([...]).order_by([...]]) json_data = [['col1, 'col2', 'col3']] for item in qs_results: json_data.append([ escape(item.col1), escape(item.col2), escape(item.col3), ]) return ExcelResponse(json_data, 'title') But this is really slow. The output can sometime have 100,000s of lines (and 20 columns) and take more than 10 minutes to be generated and often times out. How can I output an excel file with a high number of row efficiently? -
Django form : two users (A and B) - check if user B already exist, if yes add it to the channel - username is not defined
I'm facing an issue. My goal is to know if a user already exist in DB. If it's true add it to the channel and create it. There is only two fields in the form for consumer. title of channel name of seller (check if it's valid and if so add it) I don't really why that does not work. class CreateChannelView(CreateView): model = Channel form_class = CreateChannelForm template_name = 'channel_new.html' def form_valid(self, form): form.instance.consumer = self.request.user seller = self.request.POST.get("seller") current_seller = User.objects.filter(username=username(seller)) if current_seller.count()<1: raise forms.ValidationError('Username does not exist') else: existed_seller = User.objects.get(username=username(seller)) form.instance.seller.add(existed_seller) form.save() return super(CreateChannelView, self).form_valid(form) def get_success_url(self): return reverse_lazy('channel:channel_home') class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") -
Best way to validate request parameters in django
I have following url in django: url( r"^supplier/(?P<supplier_receiver_pk>[0-9]+)/assign_license/(?P<supplier_sender_pk>[0-9]+)", AdminSupplierAssignLicenseView.as_view(), name="supplier-assign-license", ), I want to validate these parameters (supplier_receiver_pk, supplier_sender_pk) so in my serializer I tried this by doing this: class AdminSupplierLicenseSerializer(serializers.Serializer): license_sender_id = serializers.IntegerField() total_licenses = serializers.IntegerField() def get_license_sender_id(self): supplier_receiver_pk = self.context["supplier_receiver_pk"] license_sender_id = self.context["supplier_sender_pk"] #more code def validate_total_licenses(self, total_licenses): #more code But that doesn't work, as het gives an error that license_sensor_id is not given. How do you validate request parameters in django? -
Django | How to change nav class with change in URL?
I want to know the best approach to change the html class name according to the change in url. <nav class="navbar navbar-expand-lg fixed-top clean-navbar" > <div class="container"><a class="navbar-brand logo" data-bs-hover-animate="jello" href="#">BootstrapNation</a><button data-toggle="collapse" class="navbar-toggler" data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><i style="color: white;" class="fas fa-bars"></i></button> <div class="collapse navbar-collapse" id="navcol-1"> <ul class="nav navbar-nav ml-auto mr-0"> <li class="nav-item"><a class="nav-link" href="{% url 'home' %}">HOME <i class="fas fa-home"></i></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'snippets' %}">SNIPPETS <i class="fab fa-css3" style="color: purple;"></i></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'premium' %}">PREMIUM THEMES <i class="fab fa-product-hunt" style="color: green;"></i></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'login' %}">LOGIN <i class="far fa-user"></i></a> </li> </ul> </div> </div> </nav> After every time use a nav-item, I want the class to include 'active', like if the url includes 'site.com/snippets' I want the class to say 'nav-item active' I think using request.get_full_path in if tag might be an approach, but that will make a mess. -
How to data submit and page redirect same position after the button click using javascript python Django?
index.html <div class="row"> <div class="col-md-12"> <div class="card shadow-lg"> <div class="card-body" id="div1"> <div class="row"> <div class="col-md-6"> <h5 class="card-title"><i class="fa fa-user-circle" aria-hidden="true"></i> <a href="{% url 'profile' datas.id %}">{{datas.user_id|capfirst}}</a></h5> </div> <div class=" col-md-6 text-right" > {% if request.user.id == datas.user_id_id %} <button class="btn btn-sm btn-outline-primary" onclick="load_post(this, '{{datas.id}}')" id="edit"> Edit</button> {% endif %} </div> </div> <div id="msg"> <hr> {{datas.post}} <hr> </div> <div id="one"> </div> <div class="row"> <div class="col-md-4"> <i class="fa fa-thumbs-up" value="0" onclick="count(this, '{{datas.id}}')" id="odd"></i><span id="add"></span> </div> <div class="col-md-4"></div> <div class="col-md-4 text-right">{{datas.post_date}}</div> </div> </div> </div> </div> inbox.js function load_post(id, data) { const one = id.closest(".card-body"); one.querySelector('#msg').style.display = 'none'; fetch(`/network/${data}`) .then(res => res.json()) .then(out => { const element = document.createElement("textarea"); element.classList.add("form-control"); element.rows = 2; element.id = "body"; element.innerHTML = out["post"]; one.querySelector('#one').appendChild(element); const li = document.createElement("br"); one.querySelector('#one').appendChild(li); const button = document.createElement("button"); button.className = "btn btn-sm btn-success" //button.classList.add("btn"," btn-primary"); button.id="sucees"; button.innerHTML = "SUBMIT"; button.addEventListener('click',() => edited(id, out["id"])); one.querySelector('#one').appendChild(button); }) } function edited(id, data) { var two = document.querySelector('#body').value; fetch(`/network/${data}`,{ method : 'POST', body : JSON.stringify({ post : two }) }) .then(res=>res.json()) .then(out=>console.log(out)) } views.py @csrf_exempt def edit_post(request, post_id): try: post = posts.objects.get(user_id=request.user, pk=post_id) except posts.DoesNotExist: return JsonResponse({"Out":"Data not found"}, status=404) if request.method == 'GET': return JsonResponse(post.serialize()) if request.method == 'POST': data = json.loads(request.body) upt = data.get("post","") post.post β¦