Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass Dynamic Value in Html anchor tag using Python Django
I am working on Cuckoo Sandbox and I hope that everyone will understand my question as It is going difficult for me to explain the question. I am working on different files and I am facing some issues. The issue is that I want to call dynamic variable in html anchor tag in Django, but, when I pass the dynamic variable the sidebar disappears automatically. I need your help guys: urls.py file url(r"^(?P<task_id>\d+)/$", AnalysisRoutes.redirect_default, name="analysis/redirect_default"), routes.py file: @staticmethod def redirect_default(request, task_id): if not isinstance(task_id, (unicode, str)): task_id = str(task_id) return redirect(reverse( "analysis", args=(re.sub(r"\^d+", "", task_id), "summary")), permanent=False ) include.html file: <li> <a href="{% url 'analysis/redirect_default' 45 %}"> <div class="parent-icon"><i class='bx bx-home'></i> </div> <div class="menu-title">Summary</div> </a> </li> In HTML file you can see that there is a int number 45. Just need to parse task_id dynamic value in html anchor tag. When I pass task_id variable in replace of 45 the sidebar disappears automatically. Kindly help me to resolve this issue. Thank you -
Jr Python Developer
I know that it is a silly question but how to get a job in the software developer position field? it has been 5 months since I have been learning Django and rest-framework. and I created an E-Commerce website project and still working on it. but I do not how to get a job, every time I apply for a job, it rejects. -
Extending django user model with one to one relation
Im very new to dajngo , im trying to get some more data from user and insert them in profile table my model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True,null=True) location = models.CharField(max_length=30, blank=True,null=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() my form from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from users.models import Profile class UserRegistrationForm(UserCreationForm): first_name = forms.CharField(max_length=101) last_name = forms.CharField(max_length=101) email = forms.EmailField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields=['bio','location','birth_date'] and my view def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'Your profile was successfully updated!') return redirect('home') else: messages.error(request,'Please correct the error below.') else: user_form = UserRegistrationForm() profile_form = ProfileForm() return render(request, 'users/register.html', { 'user_form': user_form, 'profile_form': profile_form }) When i try to save the form i get the error django.db.utils.IntegrityError: NOT NULL constraint failed: users_profile.user_id I know this is because im calling save … -
How to perform annotation in Django model with a many to many relationship?
I have two Django models called Restaurant and RestauranCategory. The Restaurant model has a many-to-many relationship to RestaurantCategory. Please refer to the attached sample model instances. class RestaurantCategory(BaseModel): name = models.CharField(max_length=150) description = models.TextField() class Restaurant(BaseModel): name = models.CharField(db_index=True, max_length=128) is_partner = models.BooleanField(default=True) category = models.ManyToManyField( RestaurantCategory, related_name="restaurant_categories", blank=True, db_index=True, ) Now what I need to do is to perform an annotation from RestaurantCategory to have a new column called restaurant_names and assign a single string that contains all the related restaurants' names. I have added a similar thing that I need to do, new_data = RestaurantCategory.objects.all().annotate( restaurant_names=<should contain all the restaurant names in a single string> ) Is that possible to achieve with annotating? If not what are the options that we can use? I have gone through this StackOverflow question and wasn't able to good idea regarding my issue. -
script.js file location.iataCode failed
In the example made with django on the Amadeus blog page, when writing the script.js file, in the onclick="getLocation(\\'' +location.iataCode+'\\')"> field; I'm getting the error when I look at the codes in the example, it's exactly the same as the code, can you help with this? I'm leaving the script.js file below const toLocationData = document.getElementById("toLocationData"); function handleToLocation(){ let locationE1 = ""; const toInput = document.getElementById("to").value; if(toInput.length >1){ fetch('/api/v1/flight/select_destination/${toInput}').then((response) => response.json()).then((data) => (toLocationArray = data.data)); if(toLocationData) { toLocationData.style.display = "block"; toLocationArray.map((location) => {locationE1 += '<div class="card mb-3 mt-3" onclick="getLocation(\\\\'' +location.iataCode+'\\\\')">\\\\<div class="card-header"><b>Name:<b> ' + location.name + '</div>\\\\ <div class="card-body">\\\\ City Name:' + location.address.cityName + "\\\\ <br />\\\\ Country Name:" + location.address.countryName + '\\\\ </div>\\\\ <div class="card-footer">\\\\ <b>SubType:</b>' + location.subType + "\\\\ </div>\\\\ </div>"; }); } } toLocationData.innerHTML = locationE1; } function getLocation(regionCode){ destinationCode = regionCode; toLocationData.style.display = "none"; } -
No post request with invalid information
in forms.py I have a basic form with 2 fields: class TestForm(forms.Form): name = forms.CharField(max_length=20) email = forms.EmailField() in views.py I just render this form through: def test_form(request): return render(request, 'form.html', {'form':TestForm}) than base.html {% load static %} <head>Testsite</head> {% block content %} {% endblock content %} than form.html {% extends 'base.html' %} {% block content %} <h1>Test!</h1> <form action="" method="post">{% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> {% endblock content %} The problem arises when I click the submit button. When all my information is valid(an @ in mail) a post request gets made and i can retrieve the data with some extra code in the view. But when the information is not valid: no @gmail.com for example this post request doesn't get made. How do I fix this? -
Trying to call .xlsx data in python selenium script 'Object of type Series is not JSON serializable'
This code reads the .xlsx file and collect the mobile number of the user to send message def watbot(request): if request.method == 'POST': file_name = request.POST.get("filename") pre = os.path.dirname(os.path.realpath(__file__)) f_name = file_name path = os.path.join(pre, f_name) f_name = pandas.read_excel(path) count = 0 driver = webdriver.Chrome(executable_path='D:/Old Data/Integration Files/new/chromedriver') for column in f_name['Contact'].tolist(): try: driver.get('https://web.whatsapp.com/send?phone=' + str(f_name['Contact'][count]) + '&text=' + f_name['Messages'][[0]]) sent = False # It tries 3 times to send a message in case if there any error occurred try: sleep(3) click_btn = driver.find_element(By.XPATH, '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[2]/button/span') except Exception as e: print("Sorry message could not sent to " + str(f_name['Contact'][count])) else: sleep(1) click_btn.click() sent = True sleep(2) print('Message sent to: ' + str(f_name['Contact'][count])) count = count + 1 except Exception as e: print('Failed to send message to ' + str(f_name['Contact'][count]) + str(e)) return HttpResponse('messeges') Failed to send message to 7976583223 Object of type Series is not JSON serializable I don't what is wrong with the code as I already tried json.dump() method -
Django aggregate sum of currency (string) + value (float)
I have been doing some calculations using aggregate sum like this: total_value = myModel.objects.aggregate(sum=Sum('price')) The problem is that the field values changed and now instead of floats, the field price is a charfield containing a currency + value. Example: ID price 1 USD 34.33 2 USD 64.33 Expected result: total_value = USD 34 + USD 64 = USD 98.66 What I've tried: I tried to do the sum of price fields ignoring the first 4 characters like this: total_value = myModel.objects.aggregate(sum=Sum('price'[4:])) unfortunately my idea doesn't work. Any help will be highly appreciated -
How to use KafkaConsumer with Django4
I have a Django 4 project and using KafkaConsumer from kafka-python. I want to update django models after receiving a Kafka message. The goal here is to have some Kafka worker running and consuming message, it is also should able to have access to the models in the existing django ASGI app. Is it possible or should this worker be a separate django project? -
DjangoRestFramework: Unit Testing AssertionError: 404 != 200 while Test update
I've started writing unit tests for my API's but am stuck while updating user details received an assertion error of 404!=200. I'm sharing mycode for the reference. Please do let me know my mistake and a brief explanation as I'm new to django rest. I've created only one class "class TestUser(APITestCase):" for testing 2 API is it fine as I'm extending the URL in the update client patch? models.py mport email from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): """ Creates and saves a User with the given email, name and password. """ if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): """ Creates and saves a superuser with the given email, name and password. """ user = self.create_user( email, name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, password=password, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): … -
Integrate Django with Spring Boot
I'm using gRPC microservices. The backend is built on Spring Boot connected with the Mongo database. The front end is implemented on the Django framework. Can you help with how to connect Django with Spring and pass the CURD operations? Thanks Bhavesh Asanabada -
Django ORM queries
I've these tables: class ContestQuestions(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name='contest_question_contest') quetions = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='contest_question_questions') class UserResponse(models.Model): user = models.ForeignKey(User, on_deleted=models.CASCADE, related_name='user_response') response = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name='user_answer') Other related tables I've: class Contest(models.Model): name = charfield date = charfield is_active = bool class Question(models.Model): title = charfield created_at = datetimefield class Answer(models.Model): question = FK(Question) answer = charfield #4 options of 1 question is_true = bool I need to get some stat about every quiz. So from every quiz, I want to know the top 5 most correctky answered questions and most incorrectly answered questions and total number of people who attempted that question. How can I write a query for it? -
I am getting a SignatureDoesNotMatch error while generating a presigned url for aws s3
I am trying to create a presigned url to upload images to aws s3. The server is successfully generating the upload link but when I click on the link, I am getting a SignatureDoesNotMatch error -
Celery task is delayed when another task runs, how do I make sure multi-threading here?
We have a celery worker and a beat scheduler running in production, in a dedicated Kubernetes POD. We used gevent and run celery with concurrency set to 200. celery -A app worker -l info --pool=gevent --concurrency=200 Recently, we needed to have a periodic task to be triggered every 5 seconds. But when there is another celery task in progress (especially the ones that interact with the database), we noticed the task is delayed a lot. Checking the beat-scheduler, the tasks are sent every 5 seconds without problems but they are waiting in the broker. We hoped this periodic task was not affected by other tasks because we used concurrency. Please see screenshot of logs We need to make sure this task runs every 5 seconds regardless of other tasks. -
Django urls configuration
I have an example website using django. I have 2 link "about" and "blog". When I click "blog" it become localhost/blog and nothing problem, but when I click "blog" once more it become localhost/blog/blog and error happen. What's the solution? -
submit form with <a></a> tag via javascript
I use this code to submit my form with a tag but its not working html file <form id="my_form" method="post"> {% csrf_token %} {{form.as_p}} <input type="number" name="conf" ><a onclick="document.getElementById('my_form').submit();" href="{% url 'signup' 0 %}">ارسال کد</a> <br><br> <button type="submit">ثبت نام</button> </form> console log "GET /signup/0 HTTP/1.1" 200 1531 -
Django formset can't got a NaN number in the field name
As you can see , the first form set is using form-0. Which is expected, but for the next item is using NaN. Here is how I did: https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html -
how solve django create model class dynamically
When dynamically creating and generating Model class, modify some properties, fill in the information required by the sub-table, the first time can return the normal result, the second result error, after the analysis of the second result field to retain the first table name: class Object: def __init__(self, **kwargs): self.__dict__.update(kwargs) def _model_new(cls, *args, **kwargs): return cls(*args, **kwargs)enter code here class ShardModel(object): _shard_db_models = {} temp_class = [] def __new__(cls, *args, **kwargs): shard_key = kwargs.pop('shard_key', 0) % cls.Config.table_num model_name = cls.__name__ model_name += '_%s' % shard_key model_class = cls._shard_db_models.get(model_name) if model_class is not None: return model_class # Deep copy attrs attrs = dict() attrs.update(cls.__dict__) if 'objects' in attrs: attrs['objects'] = attrs['objects'].__class__() # Set table name with shard_key meta = Object(**cls.Meta.__dict__) meta.db_table = meta.db_table % shard_key meta.abstract = False attrs['Meta'] = meta attrs['new'] = classmethod(_model_new) attrs['__module__'] = cls.__name__ cursor = connection.cursor() tables = [table_info.name for table_info in connection.introspection.get_table_list(cursor)] # Create model class dynamically model_class = type(model_name, tuple([models.Model] + list(cls.__bases__[1:])), attrs) print(model_class) if meta.db_table not in tables: for cmd in ('makemigrations', 'migrate'): exec_command(cmd, meta.app_label) cls._shard_db_models[model_name] = model_class return model_class this is my model class Nice(ShardModel): user_id = models.IntegerField() user_name = models.CharField(max_length=256) password = models.CharField(max_length=256) class Config: table_num = 3 class Meta: app_label = … -
Python- ValueError: too many values to unpack (expected 2) in Django
Models.py from django.db import models class Userreg(models.Model): username= models.CharField(max_length=100) fname= models.CharField(max_length=100) lname= models.CharField(max_length=100) email= models.CharField(max_length=100) pass1= models.CharField(max_length=100) class Meta: db_table="newapp2" Views.py from app1.models import Userreg from django.shortcuts import redirect, render from django.contrib import messages from django.contrib.auth import authenticate,login,logout def signup(request): if request.method== "POST": username= request.POST['username'] fname= request.POST['fname'] lname= request.POST['lname'] email= request.POST['email'] pass1 = request.POST['pass1'] pass2= request.POST['pass2'] if Userreg.objects.filter(username=username): messages.error(request, "Username already exist! Please try some other username.") return redirect('home') if Userreg.objects.filter(email=email).exists(): messages.error(request, "Email Already Registered!!") return redirect('home') if len(username)>20: messages.error(request, "Username must be under 20 charcters!!") return redirect('home') if pass1 != pass2: messages.error(request, "Passwords didn't matched!!") return redirect('home') if not username.isalnum(): messages.error(request, "Username must be Alpha-Numeric!!") return redirect('home') myuser= Userreg.objects.get(username,email,pass1) myuser.first_name= fname myuser.last_name= lname myuser.save() TRACEBACK: File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Desktop\app\app1\views.py", line 36, in signup myuser= Userreg.objects.get(username,email,pass1,fname,lname) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\sql\query.py", line 1358, in … -
Django nested categories - path getting 404 on child slug
I try to create nested categories with django-treebeard. And in admin this solution work fine. But I need to show this categories. When I try reach root category eq.: /kategorie/wegetarianskie then works fine, but when I try to reach fullslug with children category eq.: /kategorie/wegetarianskie/obiady then I have error 404 and don't know why. Maybe someone have answer. My model: class Category(MP_Node): name = models.CharField(max_length=255, verbose_name='Nazwa kategorii') slug = AutoSlugField(populate_from='name', unique=True) fullslug = models.CharField(max_length=255, verbose_name='Pełny adres kategorii', blank=True) created_at = models.DateTimeField(default=datetime.datetime.now) node_order_by = ['name'] Then with signal I create full slug like this: @receiver(post_save, sender=Category) def save_parentname(sender, instance, **kwargs): if not instance.fullslug: if instance.is_root(): instance.fullslug = instance.slug instance.save() else: catslug = '/'.join([instance.get_parent().slug, instance.slug]) instance.fullslug = catslug instance.save() When child category is save, then signal create full slug like: /kategorie/wegetarianskie/obiady I have also get_absolute_url: def get_absolute_url(self): return reverse('categorydetail', args=[self.fullslug]) View: def category_detail(request, fullslug): category = Category.objects.get(fullslug=fullslug) return render(request, 'categories/category_detail.html', { 'category': category }) Urls: urlpatterns = [ path('wszystkie', views.category_list, name='categorylist'), path('<fullslug>/', views.category_detail, name='categorydetail'), ] -
How can I make the main category page?
Greetings! I have the following code: urls.py re_path(r'^category/(?P<hierarchy>.+)/$', show_category, name='category'), views.py def show_category(request, hierarchy=None): category_slug = hierarchy.split('/') parent = None root = Categories.objects.all() for slug in category_slug[:-1]: parent = root.get(parent=parent, slug=slug) try: instance = Categories.objects.get(parent=parent, slug=category_slug[-1]) except: instance = get_object_or_404(Goods, slug=category_slug[-1]) return render(request, "shop/product.html", {'instance': instance}) else: return render(request, 'shop/categories.g.html', {'instance': instance}) The category model has the structure: id, slug, imagePath, parent I googled a lot and didn't find a good answer to my question. Please help, this script displays only categories at localhost/category/(name of the parent category) and one level higher. And the problem is that I can't make the main category page at all (localhost/category), please help or point me in the right direction to solve this issue! I'm going crazy trying to solve this problem. Tried and google and dig into the documentation. Can't decide at all. -
psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist
I'm trying for the first time to deploy my Django project to heroku, but I'm running in some issues, when trying to: Register/Login heroku run python manage.py makemigrations heroku run python manage.py migrate (also with --fake) This error shows up: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 268, in handle emit_post_migrate_signal( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/sql.py", line 42, in emit_post_migrate_signal models.signals.post_migrate.send( File "/app/.heroku/python/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File "/app/.heroku/python/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/auth/management/__init__.py", line 42, in create_permissions create_contenttypes(app_config, verbosity=verbosity, interactive=interactive, using=using, apps=apps, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/contenttypes/management/__init__.py", line 119, in create_contenttypes content_types, app_models = get_contenttypes_and_models(app_config, using, ContentType) File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/contenttypes/management/__init__.py", line 94, in … -
Django's STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" creates hashed static file names, but doesn't read them
When I run collectstatic everything is as it should be. The appointed STATIC_ROOT directory has all the collected files with original and hashed filenames. When I run the server, however, Django throws me an 500 server error and doesn't load any of the files. When I change STATICFILES_STORAGE to "django.contrib.staticfiles.storage.StaticFilesStorage" instead of "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", everything works fine and the static files with their original filenames are served. Has anyone a clue? Do I need to import "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" somwwhere. I read the whole documentation, but nothing... -
How to get auto fill values(default values) on serializer create method in django?
I have a model like this: class Post(BaseModel): post_user_id = models.CharField(max_length=500, unique=True, default=create_uid) create_uid gerenrates a unique id serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' def create(self, validated_data): print(validated_data['post_user_id']) return super().create(validated_data) For each created post a post_user_id will be generated automatically and the user will not post the post_user_id On print(validated_data['post_user_id']) I want to print the generate number But I get error KeyError -
Why isn't my Jquery code working after the second form submit? Django - Ajax - Jquery
I have a follow/unfollow button. Currently my Jquery is working on the first submit but when I toggle the button again, the Jquery doesn't change any of the elements. html {% for user in followers %} <div class="flist" id="flist-{{ user.profile.pk }}"> <article class="media comment-section"> <a class="mr-2" href="{% url 'user-posts' user %}"> <img class="rounded-circle comment-img" src="{{ user.profile.image.url }}"></a> <div class="media-body mt-1"> {% if user.profile in following %} <div class="remove-follower-div-{{ user.profile.pk }}"> <form method="POST" action="{% url 'remove-follower-js' user.profile.pk %}" class="remove-follower-form" id="{{ user.profile.pk }}"> {% csrf_token %} <button class="btn btn-unfollow unfollow-link" type="submit" style="float:right;" id="unfollow-button-{{ user.profile.pk }}"><span>Following</span></button> </form> </div> {% else %} <div class="add-follower-div-{{ user.profile.pk }}"> <form method="POST" action="{% url 'add-follower-js' user.profile.pk %}" class="add-follower-form" id="{{ user.profile.pk }}"> {% csrf_token %} <input type="hidden" name="profile_id" value="{{ user.profile.pk }}"> <button class="btn btn-follow btn-light side-link mr-4" type="submit" style="float:right;" id="follow-button-{{ user.profile.pk }}">Follow</button> </form> </div> {% endif %} .js file $( document ).ready(function() { $('.add-follower-form').on("submit", function(e) { e.preventDefault(); const profile_id = $(this).attr('id'); console.log(profile_id) const url = $(this).attr('action'); console.log(url) $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'profile_id':profile_id, }, dataType: 'json', success: function(response) { console.log('success') console.log(response) console.log(profile_id) console.log(url) $(`.add-follower-div-${profile_id}`).find('.add-follower-form').attr('action', "/profile/"+ profile_id + "/followers/remove/js"); $(`.add-follower-div-${profile_id}`).find('.add-follower-form').attr('class', "remove-follower-form"); $(`.add-follower-div-${profile_id}`).attr('class', `remove-follower-div-${profile_id}`); $(`#follow-button-${profile_id}`).attr('class',"btn btn-unfollow unfollow-link"); $(`#follow-button-${profile_id}`).empty(); $(`#follow-button-${profile_id}`).append('<span>Following</span>'); $(`#follow-button-${profile_id}`).attr('id',"unfollow-button-"+profile_id); }, error: function(response) { console.log('error', response); } …