Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fix not found error when posting a form?
I created a comment model for my product for an ecommerce_website. when I click the reply button I get404 page not found error and my reply comment cant not be saved but my normal comment worked. reply comment didn't work this is my comment model in comment app class Comment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, blank=True, null=True) email = models.EmailField() content = models.TextField() posted_on = models.DateTimeField(default=timezone.now, editable=False) active = models.BooleanField(default=False) parent = models.ForeignKey('self', null=True, blank=True, related_name='replies', on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) this is my view in product app def product_detail(request, *args, **kwargs): selected_product_id = kwargs['productId'] product = Product.objects.get_by_id(selected_product_id) if product is None or not product.active: raise ("not valid") comments =product.comments.filter(active=True, parent__isnull=True) new_comment=None if request.method == 'POST': # comment has been added comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): parent_obj = None # get parent comment id from hidden input try: # id integer e.g. 15 parent_id = int(request.POST.get('parent_id')) except: parent_id = None # if parent_id has been submitted get parent_obj id if parent_id: parent_obj = Comment.objects.get(id=parent_id) # if parent object exist if parent_obj: # create replay comment object replay_comment = comment_form.save(commit=False) # assign parent_obj to replay comment replay_comment.parent = parent_obj # normal comment # create comment object but do … -
Getting specific data after button click - Django
I am creating a donation application that allows donors to donate stuff. I have a screen, called available supplies.html which renders out all of the donations from the database using a for loop. Each donation is displayed in a user-friendly way, and contains a button that allows them to see details about that specific donation. When the button is clicked, the user is redirected to a page, which I want to contain details about the donation that they clicked on My problem is that I can't figure out how to display a specific donation from my model, for example if my user clicked on an apple donation, I want to get the details for this donation and display it on another page My model: class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) quantity = models.IntegerField(blank=True, null=True,) The unfinished view: (Instead of displaying all of the donations, I want to get the specific details for the donation clicked on in the previous page) def acceptdonation(request): donations = Donation.objects.all() context = {} return render(request, 'acceptdonation.html', context) NOTE I have been struggling with this for a while, I'm not sure if its an easy fix or not. As an incentive, … -
How to bulk update with multiple values?
Here I have list of dates which I want to update in my Model. models class MyModel(models.Model): fk = models.ForeignKey(A, on_delete=models.CASCADE, related_name='dates') date = models.DateField() # views dates = self.request.POST.getlist('date') if dates: objs = [] for date in dates: objs.append(MyModel(date=date, fk=fk)) MyModel.objects.bulk_create(objs) Now I got problem while implementing bulk_update method. I tried this. for date in dates: MyModel.objects.update_or_create(date=date, fk=fk) But this will return get return more than .. objects if there are dates with same value and if all date value unique then it creates another instead of update -
There is any missing import function
Error in django [Code][2]tps://i.stack.imgur.com/FdPLe.png Exception page -
django rest framework update nested serializer by id
How to update a list in a nested serializer by id I have a user who has multiple contacts Example: contact serializer class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = [ 'id', 'name', 'last_name' ] user serializer class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[ UniqueValidator(queryset=User.objects.all()) ] ) contacts = ContactSerializer(many=True) class Meta: model = User fields = [ "email", "contacts" ] def update(self, instance, validated_data): contacts_data = validated_data.pop('contacts') contacts = (instance.contacts).all() contacts = list(contacts) instance.name = validated_data.get('name', instance.name) instance.save() # many contacts for contact_data in contacts_data: contact = contacts.pop(0) contact.name = contact_data.get('name', contact.name) contact.last_name = contact_data.get('last_name', contact.last_name) contact.save() return instance I want to update contacts by ID, for now it works, but it only updates the first contact in the list Any ideas or recommendations? -
Python ModelFormSets
Recently I have been trying to learn more about Python Forms and Formsets. I have been trying to apply a queryset on to a modelform_factory function. However, everytime it results in this "init() got an unexpected keyword argument 'queryset'" error. From documentation I thought that you could pass a model query onto a modelformset after it has been initialized with that model. Hey is a small section of my example code. PolicyFormSet = modelform_factory(model=PolicyProcedures, fields='__all__') formset = PolicyFormSet(queryset=PolicyProcedures.objects.filter(auditid=request.session["auditID"]).distinct()) Am I missing something fundamental here? I am only trying to display a list of forms with initial data from the mysql database. -
django.db.utils.IntegrityError: null value in column "old_column" violates not-null constraint
I get a very strange error in my tests: django.db.utils.IntegrityError: null value in column "old_column" violates not-null constraint E DETAIL: Failing row contains (68, , f, , null, f). But "old_column" does not exist in my DB any more. It was there some hours ago, but this column was renamed to a different name. If I check the database with psql mydb or manage.py dbshell and then inspect the db with \d appname_tablename then I clearly see that "old_column" does not exist any more. I have no clue why the DB (PostgreSQL) thinks that this column is still there. -
How to encode json passed from django by javascript in template
I path json object to template as context, and want to use this in template. it look like this in source code of browser var json = "{'meta': {'chord_style': 'bossa' How can I encode this string as json object??? -
How to pull data specific to a user on login for a dashboard?
I am trying to build a user dashboard in Django. A lot of the things I have found online are for one to one relationships, which is fine, but they are for things like user -> order and pulls the data for a specific order thats only one table. I need to iterate over multiple tables and look for a one to one relationship then pull that data for the user. What I am trying to do, is when the user logs in, the system searches through records across different models, then when there is a match with the user, like email match, and it returns all of that data to their user dashboard. Example: User Email = Order Type 1 --- Order Type 2 (has User Email) --- Order Type 3 | User <-> Order Type 2 | returns Data Record from Order Type 2 in dashboard for User Is this a One to One or a One too Many even though there is only one data record for each user? -
How can I restrict user to to view only specific page having a dynamic URL?
I am doing a project in which I have created a model form for employee details. Now, I want the user to be able to update only their records through the employee form and the URL of this employee form is dynamic. In this project, I am populating the user authentication model from views.py and have not provided the option for creating the user from the front end because the idea behind not providing the option for user creation from the front end is to create a user automatically when someone creates a new employee record. So, to populate the user authentication model, for the employee whose record has been created recently. I am applying the concatenation on the first name, last name and on the primary key to generate a user name and for the password, I am generating a random password. on the home page, I have generated a list view of Employee records and also provided a link for view (to see the complete details of a particular employee) and another link for updating the records which is a dynamic URL (update/<int: id>/). Now, I want the user to be able to only update his record not … -
How do I create a search bar that filters through the names of entries and displays a list of them? (I am working on CS50 Project 1)
This is my code in Django that makes the search bar work. def search(request): entry_list = util.list_entries() query = request.GET.get("q", "") if query in entry_list: return redirect(get_entry, query) if query in entry_list == "i": filtered_i = [entry for entry in entry_list if 'i' in entry] return render(request, "encyclopedia/index.html", { "entries": filtered_i }) The error statement: The view encyclopedia.views.search didn't return an HttpResponse object. It returned None instead. If you remove the if statement, the search bar will be able to filter i but only i. How do I make this work for every letter in the alphabet? -
Django: os.path.join (BASE_DIR, 'home') is not working correctly
Django: os.path.join (BASE_DIR, 'home') is not working correctly. 'os' is not defined but I already defined it. How to solve the problem. The following screenshot demonstrates it very well. enter image description here The following exception generating over and over again. enter image description here -
How to send an email to currently logged in user Django
I am currently trying to set up a view so when the user visits the path /clip it will send an email to the user's inbox. Eg. I visit path, email turns up in my inbox. I am using this: from django.core.mail import send_mail def clippy(request): current_user = request.user subject = "test" message = "testing" recipient_list = [current_user.email] send_mail(subject, message, recipient_list) I'm using 3.0.4 and get this error when I visit the path: send_mail() missing 1 required positional argument: 'recipient_list' Can anyone help? Thanks -
creating serializer and views for multiple image upload and many-to-many relations to tags
I had to repost this question because my model became more complex. I am trying to create a multiple image upload with image-tagging. "Tags" have a many-to-many relationship with "Images". The forms are in the React.js in the front-end. I am trying to understand how to write a serializer and view for this. I have not seen a clear solution to this online. upload/models.py from django.db.models.fields import UUIDField from django.contrib.postgres.functions import RandomUUID def upload_path(instance, filename): return '/'.join(['images', str(instance.image), str(instance.hashtags), str(instance.shape), instance.date_created, filename, filename, ]) class Themes(models.Model): theme = models.CharField(max_length=10, default=None) class Image(models.Model): image = models.ImageField(blank=True, null=True) contributor = models.ForeignKey( 'accounts.User', related_name='+', on_delete=models.CASCADE, default='0') caption = models.CharField(max_length=100) id = UUIDField(primary_key=True, default=RandomUUID, editable=False) class Shape(models.Model): shape = models.ImageField(blank=True, null=True) contributor = models.ForeignKey( 'accounts.User', related_name='+', on_delete=models.CASCADE, default='0') id = UUIDField(primary_key=True, default=RandomUUID, editable=False) class HashTags(models.Model): hashtag = models.ManyToManyField(Image, through='Post', default=None) class Post(models.Model): theme = models.ForeignKey(Themes, on_delete=models.CASCADE, default=None) image = models.ForeignKey(Image, on_delete=models.CASCADE) shape = models.ForeignKey(Shape, on_delete=models.CASCADE) hashtags = models.ForeignKey( HashTags, on_delete=models.CASCADE, default=None) date_created = models.DateTimeField(auto_now_add=True, null=True) upload_data = models.ImageField(upload_to='upload_to') upload/serializer.py from rest_framework import serializers from .models import Image, Shape, HashTags, Post, Themes class ThemesSerializer(serializers.ModelSerializer): class Meta: model: Themes fields: ('theme') class HashTagsSerializer(serializers.ModelSerializer): class Meta: model = HashTags fields = ('hashtag') class ImageSerializer(serializers.ModelSerializer): hashtags_list = HashTagsSerializer(many=True, … -
Django: Module import error with shell_plus --notebook
In a Django project: python manage.py shell_plus --ipython is loading as expected with model imports, e.g., working just fine. When trying to python manage.py shell_plus --notebook Jupyter will start. But when trying to create a new django shell plus notebook I will get the following import error: [I 12:43:00.851 NotebookApp] Kernel started: 68eac163-4064-41ac-824d-5c839562814c, name: django_extensions [IPKernelApp] WARNING | Error in loading extension: django_extensions.management.notebook_extension Check your config files in /home/pumpkin/.ipython/profile_default Traceback (most recent call last): File "/home/pumpkin/miniconda3/envs/django22/lib/python3.7/site-packages/IPython/core/shellapp.py", line 261, in init_extensions self.shell.extension_manager.load_extension(ext) File "/home/pumpkin/miniconda3/envs/django22/lib/python3.7/site-packages/IPython/core/extensions.py", line 87, in load_extension if self._call_load_ipython_extension(mod): File "/home/pumpkin/miniconda3/envs/django22/lib/python3.7/site-packages/IPython/core/extensions.py", line 134, in _call_load_ipython_extension mod.load_ipython_extension(self.shell) File "/home/pumpkin/miniconda3/envs/django22/lib/python3.7/site-packages/django_extensions/management/notebook_extension.py", line 10, in load_ipython_extension style=no_style(), File "/home/pumpkin/miniconda3/envs/django22/lib/python3.7/site-packages/django_extensions/management/shells.py", line 152, in import_objects setup() File "/home/pumpkin/miniconda3/envs/django22/lib/python3.7/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/pumpkin/miniconda3/envs/django22/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/home/pumpkin/miniconda3/envs/django22/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/home/pumpkin/miniconda3/envs/django22/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/pumpkin/miniconda3/envs/django22/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, … -
Django Offline Forms
I am looking to build a web-app that focuses on users submitting forms. Sometimes the users may be in a remote area with limited connection and I am looking for information on how the web app can hold the form submission until a network connection is established. What packages or resources are available for this use-case? -
how to return query in key value like formate, how to add multiple queries to return Response
class Movie(models.Model): production_house = models.CharField(max_length=50) title = models.CharField(max_length=100) genre = models.CharField(max_length=100) year = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) # When it was create updated_at = models.DateTimeField(auto_now=True) # When i was update creator = models.ForeignKey('auth.User', related_name='movies', on_delete=models.CASCADE) class ProductionHouse(models.Model): p_name = models.CharField(max_length=50) p_address = models.CharField(max_length=100) owner = models.CharField(max_length=50) i am working on an existing project, all the tables are flat, no foreign key. i have to return query from two tables. see the models, i need to return ProductionHouse as key and all the movies that are prouduced by this ProductionHouse will be value. for more clarity "ProductionHouse1":{ "title":"title1" "genere":"genere1" all the fields }, { "title":"title2" "genre":"genere3" all the fields } "ProductionHouse2":{ "title":"title1" "genre":"genere1" all the fields }, or simple "productionHouse1":{ movies queryset1 movies queryset2 movies queryset3 ... }, "productionHouse2":{ movies queryset1 ... }, and so on -
Count number of queries with DEBUG=False
In my Django application, I want to count the number of queries made by each endpoint. I want to run this in production, so I cannot rely on any of the techniques I found with regular Django SQL logging that is only enabled when DEBUG=True, like adding a SQL logger or relying on django.db.connection.queries. Is there a context manager that works similar to self.assertNumQueries() in test cases that can be run in production like this? def my_view(request): with count_sql_queries() as nr_queries: response = business_logic() logger.debug(f'There were {nr_queries} queries made') return response -
How do I safely delete a model field in Django?
I need to delete fields from an existing django model that already have a few object associated with it. Deleting the fields from models.py gives me an error (obviously as there are table columns still associated with them). The data in body2 and body3 are not necessary for my app. I have copied that data from those fields to the body field. How would I go about deleting these fields without dropping the table entirely and thereby losing all my data? class Post(models.Model): #some fields body =EditorJsField(editorjs_config=editorjs_config) body2 =EditorJsField(editorjs_config=editorjs_config) body3 =EditorJsField(editorjs_config=editorjs_config) I deleted body2 and body3 and ran migrations and when creating a new object, I get errors such as this. django.db.utils.IntegrityError: null value in column "body2" of relation "second_posts" violates not-null constraint DETAIL: Failing row contains (20, Wave | Deceptiveness, and unpredictability of nature, 2021-07-19 13:40:32.274815+00, 2021-07-19 13:40:32.274815+00, {"time":1626702023175,"blocks":[{"type":"paragraph","data":{"tex..., null, null, Just how unpredictable is nature? Nature is all around us, yet, ..., image/upload/v1626702035/dfaormaooiaa8felspqd.jpg, wave--deceptiveness-and-unpredictability-of-nature, #66c77c, l, 1, 1, 0). This is the code that I'm using to save the sanitized data(after I've deleted those fields of course.) post = Posts.objects.create( body=form.cleaned_data.get('body'), # ) -
error loading django module with Python 3.8.10 and conda
I'm completely new to Python, and I'm struggling with the following error: "There was an error loading django modules. Do you have django installed?" I've installed Anaconda correctly, and succesfully installed Python 3.8.10 (both on Mac OS 11.4). I've succesfully created the conda environment: $ conda env create -f my_env.yml and made sure django is installed within conda: conda install django Which gives: Collecting package metadata (current_repodata.json): done Solving environment: done # All requested packages already installed. pip install django also gives the following: (my_env) mycomputer:~ mycomputer$ pip install django Requirement already satisfied: django in ./opt/anaconda3/envs/my_env/lib/python3.8/site-packages (3.2.5) Requirement already satisfied: asgiref<4,>=3.3.2 in ./opt/anaconda3/envs/my_env/lib/python3.8/site-packages (from django) (3.4.1) Requirement already satisfied: pytz in ./opt/anaconda3/envs/my_env/lib/python3.8/site-packages (from django) (2021.1) Requirement already satisfied: sqlparse>=0.2.2 in ./opt/anaconda3/envs/my_env/lib/python3.8/site-packages (from django) (0.4.1) (my_env) mycomputer:~ mycomputer$ However, when I run the following: python3 manage.py migrate It still tells me there's an error and asks if django is installed. Where am I going wrong? I see django in conda: conda list | grep django Gives me django 3.2.5 pyhd3eb1b0_0 But I don't see the path in the Python.Framework: python3 import sys for p in sys.path: print(p) Returns only: /Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8 /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages Any suggestions greatly appreciated as I've spent hours … -
How do I create different users (eg 'author' and 'commenter') in Custom User?
Need help w some fundamentals related to Django's User--and CustomUser(s): Working on Mozilla Django Tutorial's mini blog challenge, I created a CustomUser in app "accounts" (using tips from this tutorial). CustomUser appears as two foreign-key items in model Post in the app "blog": author and commenter. How do I define permissions/privileges for author and commenter? In CustomUser? or in views.py? Or should I have two separate classes for them? The complete code is on GitHub # accounts/models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass # Should I create the author and commenter classes here? #settings.py AUTH_USER_MODEL = 'accounts.CustomUser' #blog/models.py class Post(models.Model): post = models.TextField(max_length=1000) author = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="posts", on_delete=models.CASCADE ) -
TypeError: 'str' object is not callable , error while iterating 2 lists
I am implementing bulk create but while iterating using destructuring i am getting this error, my view job_skill_set = [] for job_skll, job_lvl in zip(job_skill_, job_skill_level): skil_set = Skillset.objects.get(skill_name=job_skll) job_skill_set.append(Job_Skillset( skill=skil_set, job_post=job_pst, skill_level=job_lvl)) Job_Skillset.objects.bulk_create(job_skill_set) return redirect('/users/dashboard') error TypeError: 'str' object is not callable trace Traceback (most recent call last): File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\atif\PycharmProjects\my_proj\mysite_jobportal\job_management\views.py", line 50, in create_job for job_skll, job_lvl in zip(job_skill_, job_skill_level): Exception Type: TypeError at /users/create_job/ Exception Value: 'str' object is not callable -
Django Rest : failed to update custom user model with Serializer
I'm trying to update custom user model and here's what I'm doing. class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to="users", null=True, blank=True) birthday = models.DateField(blank=True, null=True,) gender = models.CharField(max_length=100, choices=Gender_Choices, blank=True, null=True,) class UserUpdateSerializer(serializers.ModelSerializer): user_profile = ProfileSerializer(source='user') class Meta: model = User fields = ('user_profile',) def update(self, instance, validated_data): user_profile_data = validated_data.pop('user_profile' ,None) if user_profile_data is not None: instance.user_profile.profile_pic = user_profile_data['profile_pic'] instance.user_profile.birthday = user_profile_data['birthday'] instance.user_profile.gender = user_profile_data['gender'] instance.user_profile.save() return super().update(instance, validated_data) class ProfileAPI(generics.UpdateAPIView): queryset = Profile.objects.all() serializer_class = UserUpdateSerializer permission_classes = (permissions.IsAuthenticated,) def get_object(self): queryset = self.filter_queryset(self.get_queryset()) # make sure to catch 404's below obj = queryset.get(pk=self.request.user.id) return obj after I did all this it now if I make a put request {"user_profile":["This field is required."] and when tried to make a patch request it doesn't update at all. can you please help me what i'm doing wrong. -
Django sow list of file paths created
I have a Django app that successfully receives photos as input and creates another output file i want to display the output file once created. in the code bellow I'm passing 2 lists, the photo files (input) and the output reports. currently the output_list is passed empty, i need it to get output report as the app creates the output files Views: from .models import Photo, Output_reports class DragAndDropUploadView(View): def get(self, request): photos_list = Photo.objects.all() output_list = Output_reports.objects.all() return render(self.request, 'photos/drag_and_drop_upload/index.html', {'photos': photos_list, 'outputs': output_list}) def post(self, request): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) -
why doesn't 'follow' button on Django work?
I have built user folloing functionality with Ajax, so a user can follow/unfollow another user. The problem is that when I click "follow" button nothing happens and the number of subscribers doesn't change. urls.py urlpatterns=[path('users/',user_list,name='user_list'), path('users/follow/',user_follow, name='user_follow'), path('users/<str:username>/',user_detail,name='user_detail'), path('',PostList.as_view(), name='index'), path('<str:username>/new/',News.as_view(), name='new'), path('<str:username>/', user_posts, name='profile'), path('<str:username>/<int:post_id>/', post_view, name='tak'), path('<str:username>/<int:post_id>/add_comment/', comment_add, name='add_comment'), path('<str:username>/<int:post_id>/edit/', Update.as_view(), name='edit'), views.py @login_required def user_list(request): users = User.objects.filter(is_active=True) return render(request,'user_list.html',{'section': 'people','users': users}) @login_required def user_detail(request, username): user = get_object_or_404(User,username=username,is_active=True) return render(request,'user_detail.html',{'section': 'people', 'user': user}) @ajax_required @require_POST @login_required def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create(user_from=request.user,user_to=user) else: Contact.objects.filter(user_from=request.user, user_to=user).delete() return JsonResponse({'status':'ok'}) except User.DoesNotExist: return JsonResponse({'status':'error'}) return JsonResponse({'status':'error'}) user__detail.html {% extends "base.html" %} {% load thumbnail %} {% block title %}{{ user.get_full_name }}{% endblock %} {% block content %} <h1>{{ user.get_full_name }}</h1> </div> {% with total_followers=user.followers.count %} <span class="count"> <span class="total">{{ total_followers }}</span> follower{{ total_followers|pluralize }} </span> <a href="#" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}un{% endif %}follow"class="follow button"> {% if request.user not in user.followers.all %} Follow {% else %} Unfollow {% endif %} </a> {% endwith %} {% endblock %} {% block domready %} $('a.follow').click(function(e){ e.preventDefault(); $.post('{% url "user_follow" %}', { id: $(this).data('id'), …