Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django I Can't add a fields to my model form?
I want to add a fields to my model but it not working. the field that I want to add it content_list = models.TextField(null=True) models.py class number(models.Model): item = models.CharField(max_length=100) num = models.CharField(max_length=100) content = models.TextField() content_list = models.TextField(null=True) def __str__(self): return self.item When I run the manage.py makemigrations is working, so after that I run the manage.py migrate and it give me this error django.db.utils.IntegrityError: NOT NULL constraint failed: new__promo_number.content Thank you for the help! -
django elasticsearch dsl fail save record: error object is not iterable
please help me ! save record in elasticsearch fail model.py model document.py document.py views.py views.py error error error -
Use django template tags in tinyMCE to serve static images from AWS S3
Background: I am using the django-tinymce in the admin interface to create blog-like content and serve multiple images. I'm using AWS S3 to store and serve media and static files. Problem: By default the django-tinymce doesn't allow for template tags like {% static 'img/project/some_name.png' %} inside the TinyMCE editor. Therefore, I have to hardcode the path to the staticfiles which is currently served from AWS S3. Media and static files work fine outside of TinyMCE. Goal/Need: Find a way to serve static files located in AWS S3 from TinyMCE or find another method of creating lengthy content and serving multiple static images from admin interface. I'm fairly new and have been searching on stackoverflow/github and trying out other methods without much success so would appreciate any help/or direction. models.py (truncated to show just tinymce part) class Project(models.Model): title = models.CharField(max_length=255, blank=True) content = HTMLField('content') settings.py (just shows tinymce and aws setup) TINYMCE_DEFAULT_CONGIF = { 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect … -
Why am i not getting the right button when a user like comment reply
i am working on a website where users can comment on a post and also other users can reply to comments on a post and like each comments. I have implemented a comment and like section, but when a user like a comment reply, the right icon do not display (a red heart). I am using heart for like button, just like instagram. When i click on the empty heart button, it gets the value in database but the empty heart do not change to red heart. This problem only occur in comment reply like. Note: On the image i attached the red heart is my comment, that works well. But the empty heart is comment reply like, when clicked it gets count to 1 but the heart do not change to red, how do i make the heart turn red? that is the solution i want. Model: def comment_like_view(request): # post = get_object_or_404(Comments, id=request.POST.get('comment_id')) comment = get_object_or_404(Comments, id=request.POST.get('id')) comment.liked_comment = False if comment.likes.filter(id=request.user.id).exists(): comment.likes.remove(request.user.profile) comment.liked_comment = False else: comment.likes.add(request.user.profile) comment.liked_comment = True context = {'comment': comment} if request.is_ajax(): html = render_to_string('ajax_commentlikes.html', context, request=request) return JsonResponse({'form': html}) views: def comment_like_view(request): # post = get_object_or_404(Comments, id=request.POST.get('comment_id')) comment = get_object_or_404(Comments, id=request.POST.get('id')) comment.liked_comment … -
Why Models aren't loaded yet?
I'm traying to do makemigrations and I have the error: core.exceptions.AppRegistryNotReady: Models aren't loaded yet I'm trying to do something like this, assigning some defaults values and set it on_delete() action in ForeingKey field: ID_POR_DEFECTO = 1 def get_user_defecto(): """ obtener o crear una User por defecto """ return User.objects.get_or_create(username="nouser")[0] def get_sede_defecto(): """ obtener o crear una Sede por defecto """ return Sede.objects.get_or_create(nombre="NO SEDE")[0] class Sede(models.Model): nombre = models.CharField(max_length=200) def __str__(self): return self.nombre class Meta: verbose_name = 'sede' verbose_name_plural = 'sedes' def get_facultad_defecto(): """ obtener o crear una Facultad por defecto """ return Facultad.objects.get_or_create(sede=ID_POR_DEFECTO, codigo="NO CODIGO", nombre="NO FACULTAD")[0] class Facultad(models.Model): sede = models.ForeignKey(Sede, default=get_sede_defecto(), on_delete=models.SET(get_sede_defecto())) codigo = models.CharField(max_length=100) nombre = models.CharField(max_length=250) decano = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.nombre class Meta: verbose_name = 'facultad' verbose_name_plural = 'facultades' In settings: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'res_estudiantil', ] Thanks for your attention. -
Plesk passenger django watch manage.py logs
I am using django over Plesk. For this, it is necessary to install passengers in plesk. https://support.plesk.com/hc/en-us/articles/115002701209-How-to-allow-installing-and-install-Django-applications- When I write python manage.py runserver while working on localhost, I can watch all manage.py logs instantly. But since I am not running this command while working on this plesk passenger, I cannot see any log record. How can I watch manage.py log records instantly? -
Serializers reverse update DRF
Question is .. How can I update Course by ID in a same time if need to update also Status fields for this course? such as name, date. Status is unique per course&users. My view: class CourseEditView(ModelViewSet): serializer_class = CourseSerializer queryset = Course.objects.all() http_method_names = ['patch'] My wrong serializer: class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course My models: class Status(models.Model): name = models.CharField(max_length=256, blank=True) date = models.DateField(blank=True, null=True) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="courses") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADErelated_name="students") class Meta: verbose_name_plural = 'Statuses' verbose_name = 'Status' unique_together = ('user', 'course') class TrainingCourse(models.Model): name = models.CharField(max_length=255) -
How to set default celery queue?
My celery settings in django: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_QUEUES = ( Queue('high', routing_key='high'), Queue('normal', routing_key='normal'), ) CELERY_DEFAULT_QUEUE = 'normal' If I set queue name in my task, it's works. But if I don't, default queue settings doesn't work. # It's ok @periodic_task(run_every=timedelta(minutes=10), name='Delete props', queue='normal') def delete_props(): delete_props() # It doesn't work @periodic_task(run_every=timedelta(minutes=10), name='Delete props') def delete_props(): delete_props() How to set default queue and don't set in in task parameters? -
Is there a way to accelerate Celery Beat with multiple servers?
I have set up my Celery Beat successfully and it executes my tasks exactly like I expect it to. The problem I am facing is that my task is very long. To give you a little more context I am calling an API function every 30 minutes that query some thousands stocks from the stock market and then proceeds to slightly modify and adapt the newly acquired data. Those manipulation are unfortunately essential but are very power hungry. This tasks takes me around 30-35 minutes to complete, which means sometimes my function is not done before the other function is triggered by Celery Beat. This causes my database to store the data in a imperfect chronological order. I planned to query this data every 20 minutes but the delay is forcing me to reconsider. Now even 30 minutes is not enough and I plan to add many other quirks to my function, potentially delaying this query even more. Is there a way for me to split the workload of my function across multiple celery beat servers? I could easily separate my complete stock list in multiple smaller lists that could then be dispatched to different Celery Beat servers so they … -
Why i cannot use gmail smtp in django?
This is my setting: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'prahbari82@gmail.com' EMAIL_HOST_PASSWORD = 'My gmail password' EMAIL_PORT = 587 EMAIL_USE_TLS = True and i use CBV's: from django.contrib.auth import views as auth_views from django.urls import reverse_lazy class UserLogin(auth_views.LoginView): template_name = 'accounts/login.html' class UserPassReset(auth_views.PasswordResetView): template_name = 'accounts/password_reset_form.html' success_url = reverse_lazy('accounts:password_reset_done') email_template_name = 'accounts/password_reset_email.html' class PasswordResetDone(auth_views.PasswordResetDoneView): template_name = 'accounts/reset_done.html' class PasswordResetConfirm(auth_views.PasswordResetConfirmView): template_name = 'accounts/password_reset_confirm.html' success_url = reverse_lazy('accounts:password_reset_complete') class PasswordResetComplete(auth_views.PasswordResetCompleteView): template_name = 'accounts/password_reset_complete.html' But I don't get any errors I also turned on the less secure app! I also use 2 verification but it does not work! -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.UserModel' that has not been installed
I am trying to add an uuid field to the AbstractUser model. When running makemigrations it throws the following error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.UserModel' that has not been installed accounts/models.py import uuid from django.db import models from django.contrib.auth.models import AbstractUser class UserModel(AbstractUser): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Meta: app_label = 'app_auth' db_table = 'user_accounts' def __str__(self): return self.username settings.py INSTALLED_APPS = [ # Django 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # My Apps 'accounts', ] AUTH_USER_MODEL = 'accounts.UserModel' The solutions suggested here didn't help. -
How to use a placeholder inside Django CMS Plugin?
cms_plugin.py @plugin_pool.register_plugin class CarouselPlugin(CMSPluginBase): name = _("Carousel") model = CarouselPluginModel exclude = ['slides'] inlines = [CarouselSlideInline] render_template = "plugins/touts/carousel.html" def render(self, context, instance, placeholder): context['instance'] = instance return context models.py class CarouselPluginModel(CMSPlugin): slides = models.ManyToManyField('CarouselSlide', blank=True, related_name='slider_images') content = PlaceholderField('content') def slide_list(self): return CarouselSlide.objects.filter(carousel=self).order_by('order') def copy_relations(self, oldinstance): self.slides = oldinstance.slides.all() plugins/touts/carousel.html {% load i18n staticfiles cms_tags menu_tags sekizai_tags %} <div class="carousel"> {% render_placeholder instance.content %} <div class="carousel__slider"> {% for slide in instance.slide_list %} <div class="carousel__slider__slide" style="background-image: url('{{slide.image.url}}')"> <div class="carousel__heading"><h1>{{slide.title}}</h1></div> <div class="carousel__sub-heading"> <p>{{slide.sub_title}}</p> </div> {% if slide.button_link %} <a href="{{slide.button_link}}" class="carousel__button button-1">Learn More</a> {% endif %} </div> {% endfor %} </div> </div> I am planning to have two different CMS plugin named as 'Carousel' and 'Carousel Slide'. And as you can guess from their name, I'm trying to put placeholder inside of Carousel plugin so I can put Carousel Slides inside. It looks like CMS Plugin inside CMS Plugin. How can I achieve that kind of structure? -
Iterating Over Static CSS File Names Are Not Displaying The Styles
I have been trying to load static CSS files using an array containing CSS file names. For some reason, even though the file path is correct, the stylesheets don't load. It only occurs while they are being loaded in a for loop and not if they are hard coded 1 by 1. For example, here is what I am trying to render in my views file: def about(request): context = { 'headerCSS': [ 'mysite/css/about.css' ] } return render(request, 'mysite/about.html', context) I then try to load it like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> {% if headerCSS %} {% for iter in headerCSS %} {% with iter as css %} <link rel='stlyesheet' href="{% static css %}"/> {% endwith %} {% endfor %} {% endif %} </head> This is the link that gets created but doesn't work: <link rel='stylesheet' href='/static/mysite/css/about.css'/> However, if I add it without the for loop like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'mysite/css/about.css' %}"> </head> It produces the same link: <link rel='stylesheet' href='/static/mysite/css/about.css'/> Everything works fine even when I just assign the … -
How to replace element on a model data base on django
the question is simple, I want to replace the "content" text data in the database. But I dont know how, I am kinda new to django! thank you for now, it add a new item on my database, But i just want to modify an item that is already on my database. Thanks for the help models.py class number(models.Model): item = models.CharField(max_length=100) content = models.TextField() def __str__(self): return self.item views.py def promo(request): form = numberform() if request.method == "POST": form = numberform(request.POST) if form.is_valid(): numberclean = form.cleaned_data["num"] print(numberclean) test = number(item="numberall", content=numberclean) test.save() else: form = numberform() return render(request, "promo/home.html", {"form": form}) return render(request, "promo/home.html", {"form": form}) forms.py class numberform(ModelForm): class Meta: model = number fields = ["num"] -
UWSGI Multi-site performance decrease after some days active
I have a multi-site server with Nginx and uwsgi running Django instances, and I had noticed that the performance decrease after some days running. I have 8 sites with not more than 100 visits per day in total. If I run Google insights I have 95/100 points in mobile, but after some days I get 80/100 (same page). When I restart uwsgi I get 95 again, the difference could not be very noticeable but google kick my sites from first page results. I think the problem could be in the uwsgi configuration. The server is t2.micro aws instance, 1 cpu 1gb ram. My /etc/systemd/system/uwsgi.service file is: [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target And all ini files in /etc/uwsgi/sites have this configuration: [uwsgi] project = kioner uid = ubuntu base = /home/%(uid) chdir = %(base)/%(project) module = %(project).wsgi:application env=DJANGO_SETTINGS_MODULE=%(project).settings_pro socket=/home/ubuntu/server-config/%(project).sock chmod-socket=666 vacuum=true master = true processes = 1 logto = /var/log/uwsgi/%n.log The system information at this moment is: System load: 0.0 Usage of /: 64.2% of 7.69GB Memory usage: 78% Swap usage: 0% Processes: 114 Is the configuration good for multi-sites? What can I do to know what is causing that? … -
How to update variable in d3 chart using ajax in django
I will update data variable in d3 chart scripts without refreshing the screen using ajax which the variable sent from view.py. How to update it, the variable in d3 chart is {{totalSalesGraph|safe}} htmlFile.html <html> <div class="graphTotalSale"> <div id="graphSale"></div> </div> <script> setInterval(function() { $.ajax({ type: "GET", url: "{% url 'updateData' %}" }) .done(function(response) { // how to update {{totalSalesGraph}} variable in d3 chart. (new value is response.totalSalesGraph) }); }, 5000) </script> <script> var margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 550 height = 120 var svg = d3.select("#graphSale") ... //Read the data var data = {{totalSalesGraph|safe}} ... </script> <html> -
How to get list POST request in django
get post in webservice but dont get list label = request.POST.getlist('label') but label is string value: "label": "['s, l']" this value not list how to get list in django? I uses postman. -
How to store data from html form to postgres database?
I have an HTML form from which data needs to be stored in the Database. My project structure is as: Form - _init_.py - settings.py - urls.py - wsgi.py - manage.py Please list the process for this. I am confused whether there is a need to create a new app(using - manage.py startapp app_name) to display the form or it can be done without a new app. -
How do I enable caching on a django development server?
I am running a development server for Django. I understand the default behaviour is to set Cache-Control: no-cache and Pragma:no-cache in the request headers, however I would like to allow file caching so I can get a better appreciation of page speed. How do I enable caching on a django development server? Per the docs, I have set up a DummyCache and associated middleware but this does not appear to solve the problem. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_KEY_PREFIX = '' CACHE_MIDDLEWARE_SECONDS = 600 I've also been sure to update the middleware with the additional modules (abbreviated for clarity below): MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] -
How do I create a PDF constancy in Reportlab using Django 2 and Python 3?
# PDF Certificates in Reportlab I've been trying to make a certificate but I couldn't class NumberedCanvas(canvas.Canvas): def __init__(self, *args, **kwargs): canvas.Canvas.__init__(self, *args, **kwargs) self._saved_page_states = [] def showPage(self): self._saved_page_states.append(dict(self.__dict__)) self._startPage() def save(self): """add page info to each page (page x of y)""" num_pages = len(self._saved_page_states) for state in self._saved_page_states: self.__dict__.update(state) self.draw_page_number(num_pages) canvas.Canvas.showPage(self) canvas.Canvas.save(self) def draw_page_number(self, page_count): # Change the position of this to wherever you want the page number to be self.setFont('Helvetica', 8) self.drawRightString(211 * mm, 15 * mm + (0.2 * inch), "Page %d of %d" % (self._pageNumber, page_count)) # Part I is a class that contains the model data ACCOUNT PDF CLASS # --------------------------------------_------------------------------------ PART 1 class ExportPDFAccount: def __init__(self, query): self.buffer = BytesIO() self.pagesize = letter self.query = query self.width, self.height = self.pagesize @staticmethod def _header_footer(canvas, doc): canvas.saveState() title = "Estado de cuentas" canvas.setTitle(title) styles = getSampleStyleSheet() # custom styles styles.add(ParagraphStyle('set_title', alignment=TA_LEFT, fontSize=14, fontName="Helvetica-Bold", )) PART 2 # PARTE 2 url = "https://static.coinbtr.com/static/img/coinbtr_logo.png" r = requests.get(url) image = ImageReader(Image.open(BytesIO(r.content))) canvas.drawImage(image, 35, 600, width=8*cm, height=8*cm, preserveAspectRatio=True) set_title = Paragraph(title.upper(), styles['set_title']) set_title.wrap(doc.width + 250, doc.topMargin) set_title.drawOn(canvas, 215, doc.height + doc.topMargin - 40) PART 3 data = [('#', 'Fecha', 'Método', 'Estatus', 'Sub-total', 'Comisión')] set_table = Table(data, colWidths=[35, 100, 100, … -
Does Cookie expiration differs in chrome and firefox?
I have been working with cookies. so watched the docs and some blogs and code the cookies just like below--> def ProouctDetailView(request, slug): item = Item.objects.get(slug=slug) response = render(request, 'product.html', {'item' : item } ) temp = request.COOKIES.get('pro', None) response.set_cookie('pro','{0} {1}'.format(temp, slug)) return response Here I am getting the cookies. As django doesn't provide setting multipe values in a single cookie, I am getting all values together as a string(seperated by a space) and spliting them using split() method. Then I filter to generate the queryset for recently viewed section def HomeListView(request): items = Item.objects.all() recent = None try: slug = request.COOKIES.get('pro').split(" ") recent = Item.objects.filter(slug__in= slug) except: pass return render(request, 'home.html', {'items': items, 'recent':recent}) From cookies,What I am getting are slugs of the items object so that later I can show them in recently viewed section as i didn't provide any max_age field in my set_cookie() method it will set as none which means this cookie will auto expire when user closes the browser session, means shuts down the browser,Right? But the recently viewed section doesn't expires even if I shut down the chrome and restart the chrome. It still there. so the cookie didn't expired in chrome . … -
How to serve dist folder of Vue together with Django using nginx?
I have developed a restful api using Django and I have developed an admin panel using Vue and I have a dist folder. I have bought one VPS (Virtual Private Server). I want to deploy both of them in one server and use Vue developed admin panel instead of default one. I have tried to serve it through django templates and eventually it did not work. I have converted all static url accesses to django like static access urls but it could not find sources which .js files access by loading other sources. How can I handle it using nginx? -
How to get data from form html and formatting to link
I already make website with some form input in html, i need to get my input data, and make it whatsapp link for example, this it my input data and this is my code from input html <section id="contact"> <div class="container"> <h1>Contact Us</h1> <div class=row> <div class="col-md-12"> <form class="contact-form"> <div class="form-group"> <input type="text" class="form-control" placeholder="Your Name" name="nama"> </div> <div class="form-group"> <input type="number" class="form-control" placeholder="Phone Number"> </div> <div class="form-group"> <label for="exampleFormControlSelect2">Pilih Jenis Paket</label> <select multiple class="form-control" id="exampleFormControlSelect2" name="paket"> {% for packet in products %} <option > {{ packet.name }} | Rp {{packet.price}}</option> {% endfor %} </select> </div> <div class="form-group"> <textarea class="form-control" rows="4" placeholder="Your Message"></textarea> </div> <button type="submit" class="btn btn-primary" >Send Message</button> </form> </div> </div> </div> </section> for example the link should be likethis https://api.whatsapp.com/send?phone=628981234567&text=PAKET%205%20HARI%204%20MALAM|Rp%202500000 how can I make this link with just click on Send Message button? -
Filtering querysets in Django Rest Framework
Today i have a really strange behoviour. I have added a custom mixin to my User Viewset to filter the users by username and password and other fields. the code look like the following: class MultipleFieldLookupMixin(object): """ Apply this mixin to any view or viewset to get multiple field filtering based on a `lookup_fields` attribute, instead of the default single field filtering. """ def get_object(self): queryset = self.get_queryset() # Get the base queryset queryset = self.filter_queryset(queryset) # Apply any filter backends filter = {} for field in self.lookup_fields: if self.kwargs[field] is not None: # Ignore empty fields. filter[field] = self.kwargs[field] obj = get_object_or_404(queryset, **filter) # Lookup the object return obj class UserView(MultipleFieldLookupMixin, viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_fields = ['username', 'pwd', 'token_confirm', 'email', 'token_cng_pwd'] i would like the list operation to filter the queryset in every given parameter (so None if none is avalable and all if all are available). But the list endpoint continues to show every user to me, without filtering them. Where am i wrong? Do i have to manually set a filterbackend? am I doing some stupid mistake? Thanks a lot -
Django Like button working for all posts, but not showing with the change of button in Homepage
I have this like button, it works fine for the first post, but for all the other posts below it, it doesn't show any change of button instead the button changes in the first post, but the like gets registered for those specific posts without changing the like for first post. Its quite a weird situation to explain as I am not much familiar with js. view def like_post(request, slug): user = request.user post = get_object_or_404(Post, slug=slug) is_liked = False if user in post.likes.all(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True # return redirect('posts:myhome') context = { 'post':post, 'is_liked':is_liked, 'total_likes':post.total_likes() } if request.is_ajax(): html = render_to_string('posts/like_snippet.html', context, request=request) return JsonResponse({'form': html}) like snippet.html <form action="{% url 'posts:like_post' post.slug %}" method="post">{% csrf_token %} {% if user in post.likes.all %} <a id="like" name="post_id" value="{% url 'posts:like_post' post.slug %}" class="like-btn">{{ post.likes.count}} <i class="fas fa-heart fa-lg" style="color: red;"></i></a> {% else %} <a id="like" name="post_id" value="{% url 'posts:like_post' post.slug %}" class="like-btn">{{ post.likes.count}} <i class="far fa-heart fa-lg" style="color: red;"></i></a> {% endif %} </form> html div function in homepage <div id="like-snip" class="like_snippet mt-1"> {% include 'posts/like_snippet.html' %} <div> js $(document).ready(function(event){ $(document).on('click', '.like-btn', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: pk, data: {'csrfmiddlewaretoken': …