Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i use prefetch_related on nested serializer
i have a ProductSerializer and this serializer has photos on another model and serializer. So i want to prefetch photos in ProductSerializer. But i use to ProductSerializer in the a few serializer. I can't override queryset in Views. class RentalProductSerializer(serializers.ModelSerializer): photos = RentalProductPhotoSerializer(read_only=True, many=True) class Meta: model = Product list_serializer_class = ProductListSerializer fields = ['categories', 'stock_code', 'description', 'brand', 'model_name', 'photos', 'url'] class RentalOfferLineSerializer(serializers.ModelSerializer): product_detail = RentalProductSerializer(read_only=True, many=False, source='product') class Meta: model = RentalOfferLine fields = ( 'id', 'product', 'product_detail', 'currency', 'rent_price', 'quantity', ) -
Fill data into Model Form Django and pass id paramater in URL Django
I'm trying fill data into model form and load pages with information field of object. However, I get some error and I don't know fix views.py def profile(request, id): user = get_object_or_404(User, id=id) user_info = get_object_or_404(UserInfor, user_id=user.id) user_form = UserForm(instance=user) profile_form = ProfileForm(instance=user_info) return render(request, 'pages/profile.html', {'user': user_form, 'user_info': profile_form}) urls.py path('profile/id=<int:id>/', views.profile, name='profile') profile.html <form class="form-horizontal" name="form" method="post" action="{% url 'profile' %}"> Error I got NoReverseMatch at /profile/id=2/ Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['profile\/id\=(?P[0-9]+)\/$'] Request Method: GET Request URL: http://127.0.0.1:8000/profile/id%3D2/ Django Version: 2.2.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['profile\/id\=(?P[0-9]+)\/$'] Exception Location: F:\FTEL_CSOC\env\lib\site- packages\django\urls\resolvers.py in _reverse_with_prefix, line 668 Python Executable: F:\FTEL_CSOC\env\Scripts\python.exe Python Path: ['F:\FTEL_CSOC\webping', 'F:\FTEL_CSOC\webping', 'F:\FTEL_CSOC\webping', 'C:\Program Files\JetBrains\PyCharm 2019.1.1\helpers\pycharm_display', 'F:\FTEL_CSOC\env\Scripts\python36.zip', 'C:\Users\vuthe\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\vuthe\AppData\Local\Programs\Python\Python36\lib', 'C:\Users\vuthe\AppData\Local\Programs\Python\Python36', 'F:\FTEL_CSOC\env', 'F:\FTEL_CSOC\env\lib\site-packages', 'F:\FTEL_CSOC\env\lib\site-packages\setuptools-40.8.0-py3.6.egg', 'C:\Program Files\JetBrains\PyCharm ' '2019.1.1\helpers\pycharm_matplotlib_backend'] Server time: Mon, 24 Jun 2019 07:29:28 +0000 -
How can i get value from database in table radio button in ajax ,json and django
how can i get value from database (the value is T and F) in table radio button .the radio button change according to the database -
django template not show ForeignKey items
im new to django im having problem with my foreignkey items not displaying hope you can help me... thank you. here's my models.py class Reporter(models.Model): name = models.CharField(max_length=20) address = models.CharField(max_length=30) def __str__(self): return self.name class News(models.Model): headline = models.CharField(max_length=50) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline and my views.py def index(request): reportlist = Reporter.objects.all() context = { 'reportlist': reportlist } return render(request, 'index.html', context) and my template {% block content %} {% for r in reportlist %} <p>{{r.name}}</p> {% for items in r.item_set.all%} <p>{{items.headline}}</p> {%endfor%} <br/> {%endfor%} {% endblock %} -
Not Found: /en/
Not Found: /en/ Error in Django CMS **Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/en/ Raised by: cms.views.details** Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: '''''''''''''''''''''''''''''''' ^media/(?P<path>.*)$ ^static\/(?P<path>.*)$ ^sitemap\.xml$ ^en/ ^admin/ ^en/ ^ ^cms_login/$ [name='cms_login'] ^en/ ^ ^cms_wizard/ ^en/ ^ ^(?P<slug>[0-9A-Za-z-_.//]+)/$ [name='pages-details-by-slug'] ^en/ ^ ^$ [name='pages-root'] The current path, /en/, didn't match any of these. -
How to give different feedback when is_active is false?
I am implementing token verification for signing up using Django. I set is_active=False as default and change it to True when the user click a verification link sent to their email. But before the user click the link, I wanted to prepare for the case that the user attempt to log in. Because the user did not click the link and is_active did not turn to True, it will give an invalid credential error. However, the thing is I want to differentiate the case who did not complete the verification process from those who made an attempt to log in with wrong username or password. So my question boils down to: How to give different feedback when is_active is False from when username or password were incorrect? How can I customize jwt-graphene-django to return the customized error? This is the only customization code I found for jwt-graphene-django class ObtainJSONWebToken(graphql_jwt.JSONWebTokenMutation): user = graphene.Field(UserType) @classmethod def resolve(cls, root, info, **kwargs): return cls(user=info.context.user) -
styling django forms using reactjs
I learnt about django-forms, and I wanna create a form which looks nice, styling with css and bootstrap and html. but I found that out that I can't do it clean (like creating separate css sheet for styling) and I have to do it through python code which is doesn't look good. is there any way to do this? if I try to handle the whole frontend, do I still need to set some styles through python in backend including django forms? I'm sorry if it is a dumb question but I'm new to reactjs(actually I didn't learn it yet) and I have just a little experience in django. -
Django site preview not updating after model.py change
I am learning django and I am working on models. I created a Product class from django.db import models class Product(models.Model): title = models.CharField(max_length=10) description = models.TextField(blank=False) price = models.DecimalField(max_digits=10, decimal_places=2) featured = models.BooleanField(default=False) int = models.IntegerField(default=10) and I am trying to delete the 'int' field but the django site does not update after the chanage. After deleting a model field(the 'int' field, see the screenshots), and running python manage.py makemigrations python manage.py migrate the live preview does not update and throws an error regarding the erased field. after closing the server and restarting the server(ctrl + c and than python manage.py runserver the page updates and does not throw any errors I am using sqlite. I tried deleting 'pycache' and all the migrations also db.sql3, recreating the superuser but after removing any field I still get the same error. picture 1 -> initial state $ https://ibb.co/Yb6pmgr picture 2 -> after removing 'int' field https://ibb.co/xf1bJQJ picture 3 -> error : $ https://ibb.co/0cPyRZv -
How to run a mysql stored procedure in django with two output parameters when data is received through REST API?
I am working on a django project where I have to use a stored procedure to update multiple tables and it gives two output parameters. There are four input parameters which comes from REST api. The procedure runs properly in phpmyadmin/MySql. In a pure python script it doesn't update the required tables but gives the output properly. In django I am not able to run the procedure. I just want to know how to set the output parameters properly and execute the procedure in django. I have tried it in a seperate python script but it only gives the output parameters and doesn't update the tables. In djando I tried to edit the views.py. pure python script: import mysql.connector from mysql.connector import Error from mysql.connector import errorcode var1 = " " var2 = " " try: mySQL_conn = mysql.connector.connect(host='192.111.11.111', database='Safemode', user='root', password='password here') cursor = mySQL_conn.cursor() x = cursor.callproc('ProcessIOTData',[1,2,"3","2019-06- 21T11:56:33Z",var1,var2]) for result in cursor.stored_results(): print(result.fetchall()) for output in x: print(x) except mysql.connector.Error as error: print("Failed to execute stored procedure: {}".format(error)) finally: if (mySQL_conn.is_connected()): cursor.close() mySQL_conn.close() print("connection is closed") IN Django(views.py). I have also not saved the data from the api as that will also be done the procedure: . . … -
django logging is not coming to log file
django logging configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', }, }, 'loggers': { 'django': { }, 'setting':{ 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } error in debug.log: Watching for file changes with StatReloader Waiting for apps ready_event. Apps ready_event triggered. Sending autoreload_started signal. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/admin/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/sessions/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/messages/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/auth/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/contenttypes/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/django/contrib/staticfiles/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/rest_framework/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/user/locale with glob **/*.mo. Watching dir /home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/corsheaders/locale with glob **/*.mo. (0.001) QUERY = 'SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"' - PARAMS = (); args=() Watching for file changes with StatReloader Waiting for apps ready_event. Apps ready_event triggered. Sending autoreload_started signal. error i am expecting: File "/home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/pymongo/database.py", line 552, in collection_names ReadPreference.PRIMARY) as (sock_info, slave_okay): File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/pymongo/mongo_client.py", line 904, in _socket_for_reads with self._get_socket(read_preference) as sock_info: File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/pymongo/mongo_client.py", line 868, in _get_socket server = self._get_topology().select_server(selector) File "/home/fractaluser/Desktop/Dev/consumerhub/env/lib/python3.6/site-packages/pymongo/topology.py", line 214, in select_server … -
Is there any way to store ssh session object that is generated through paramiko?
I Have connected to my remote server using ssh paramiko library.Once after connected to my server i needed to perform many operations like remote files accessing,password altering etc so now iam creating connection lot of times in every view to make use of this connection object. Now my query is ...Is there any way to make this object availaible in every view until i close the connection... -
deploying e-commerce django project
I want to deploy an application based on Oscar Django framework. I don't know what to use for that. It will be the online-shopping website with the threshold of maximum 3k purchases/month. Which hosting service will be the best for this case with cost effectiveness and enough performance? -
PHP to Django compatibilty
i have a legacy app in php with authentication and everything working properly. Now i have decided to migrate to django for faster user experience since the app already has thousands of users i dont want to change the PHP component. What i want is that my login and user auth is done by existing PHP codebase and after login when the user shifts to django component django should automatically detect the user is signed in by looking at the session table in the mysql database. i have tried to integrate the https://github.com/winhamwr/django-php-bridge this bridge but it seems to be broken and doesn't work. -
AttributeError: 'list' object has no attribute 'iter_rows'
I'd read an excel file, there I'm getting all sheets but when doing this getting that error. views.py from Django.shortcuts import render import openpyxl def index(request): if "GET" == request.method: return render(request, 'file/index.html', {}) else: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) # getting all sheets worksheet = wb.sheetnames print(worksheet) excel_data = list() # iterating over the rows and # getting value from each cell in row for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) excel_data.append(row_data) return render(request, 'file/index.html', {"excel_data": excel_data}) -
How to Filter HTML Content in Template By URL Conditional
How do I create a template filter that only shows a section of code on a specified page? For example, my homepage which is my base_generic has code that is specific to that page. Whenever another page is loaded that code should not be displayed. I know I can use the block system but was wondering if I could also accomplish the task with a combination of the URL and If filter. See code below: # Code for base_generic template {% url 'organizer-homepage' as home_page %} {% if home_page %} Shows Content Only on Specified Page {% else %} Show Alternate on All Other Pages {% endif %} -
How to set lazy module file load path in Angular, js file cannot find in Apache
Code works fine in dev mode. But not work after deploying to apache. Home page path is http://127.0.0.1 , and click lazy-module it will find path from /. My js files are under static folder. Static files loads here , e.g. browser access path is 'http://127.0.0.1/static/4-es5.js' D:/web/staticsites └─4-es5.js └─4-es2015.js └─... └─main-es5.js When I click lazy-router module link console prompt (missing: http://127.0.0.1/4-es2015.js) How to make angular load the path to http://127.0.0.1/static/4-es2015.js ? Apache Config Alias /static D:/web/staticsites <Directory D:/web/staticsites> AllowOverride None Options None Require all granted </Directory> -
Forloop choices of RadioSelect in Django ModelForm
I have list of choices. I want to get value one by one choice in HTML forms.py class ProfileForm(ModelForm): class Meta: model = UserInfor fields = [ 'gender'] widgets = { 'gender': forms.RadioSelect(choices=GENDERS), } labels = { 'gender': "Gender", } view.py def profile(request): user_info = ProfileForm() return render(request, 'pages/test.html', {'user_info': user_info) test.html {% for choice in genders %} <label class="radio-inline" class="radio-inline"><input type="radio" value="???">{{ ??? }}</label> {% endfor %} -
Creating model field to store multiple text inputs in django
i created a form on html with a dynamically increasing text field. how do i store all the inputs from the text fields under the single 'collaborators' attribute in my django models.py? this is my html code: <!DOCTYPE html> <html lang="en"> <head> <title>Central Data Masking Platform</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ var i=1; $('#addCollab').click(function(){ i++; $('#dynamicField').append('<tr id="row'+i+'"><td><input type="text" name="collab" id="collab'+i+'"></td><td><button type="button" name="removeCollab" id="'+i+'" class="removeCollab">x</button></td></tr>') }); $(document).on('click', '.removeCollab', function(){ var button_id = $(this).attr("id"); $('#row'+button_id+'').remove(); }); }); </script> </head> <body> <div class="formGrp"> <form> <div class="collaborators"> <table id="dynamicField"> <tr> <td> <label for="collabID">Collaborator Names: </label> <input type="text" name="collab" id="collab1"> </td> <td><button type="button" name="addCollab" id="addCollab">Add Collaborator</button></td> </tr> </table> <input type="submit" name="submit" value="submit"> </div> </form> </div> </body> </html> python code: class projectDetails(models.Model): project_id=models.BigAutoField(primary_key=True) #collaborators= date_created=models.DateTimeField(auto_add_now=True) -
Django Rest Framework and Auth: GET user with unauthenticated credentials throws 403
I'm using django-rest-auth for API endpoints for my custom user model. Getting user details, I send a GET request to /rest-auth/user/. This works fine with an authenticated user, but is forbidden for an unauthenticated user marked by a 403 Forbidden error. However, I want other users to be able to view each other's details. How can I change this? This test is the one which demonstrates this error: def test_get_user(self): # /rest-auth/user/ (GET) # params: username, first_name, last_name # returns: pk, username, email, first_name, last_name client = APIClient() client.login(username=self.user2.username, password=self.user2.password) path = "/rest-auth/user/" user_data = { "username": self.username, } expected_response = { "pk": self.id, "username": self.username, "email": self.email, "first_name": '', "last_name": '', } response = client.get(path, user_data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, expected_response) -
How can i connect my django like button to ajax to refresh automatically
I have a django project that im working on. Users will be able to like and dislike post....... here is my model class Tweet(models.Model): tweet_user = models.ForeignKey(User, on_delete=models.CASCADE) tweet_message = models.TextField() tweet_date = models.DateTimeField(auto_now_add=True) tweet_like_counter = models.IntegerField(default=0) tweet_picture = models.FileField(null=True,blank=True) def __str__(self): return self.tweet_message class Like(models.Model): user = models.ManyToManyField(User) tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet.tweet_message class Disike(models.Model): user = models.ManyToManyField(User) tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet.tweet_message here is my view from django.views.decorators.csrf import csrf_exempt @csrf_exempt @login_required def like(request, pk): currentTweet = get_object_or_404(Tweet,pk=pk) username = User.objects.get(pk=request.user.id) like_queryset = Like.objects.filter(tweet=currentTweet, user=username) dislike_queryset = Disike.objects.filter(tweet=currentTweet, user=username) if like_queryset.exists(): Like.objects.filter(tweet=currentTweet, user=username).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() if dislike_queryset.exists(): Disike.objects.filter(tweet=currentTweet, user=username).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() like = Like.objects.create(tweet=currentTweet) like.user.add(username) dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() return JsonResponse({ 'like_counter': currentTweet.tweet_like_counter }) @csrf_exempt @login_required def dislike(request, pk): currentTweet = get_object_or_404(Tweet, pk=pk) username = User.objects.get(pk=request.user.id) like_queryset = Like.objects.filter(tweet=currentTweet, user=username) dislike_queryset = Disike.objects.filter(tweet=currentTweet, user=username) if dislike_queryset.exists(): Disike.objects.filter(tweet=currentTweet, user=username).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() if like_queryset.exists(): Like.objects.filter(tweet=currentTweet, user=username).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject … -
How to get label name from labels in Meta class Django ModelForm
In Meta class, I define label name for fields. I want to get label name, I tried but nothing. forms.py class UserForm(ModelForm): class Meta: model = User fields = ['first_name'] widgets = { 'first_name': forms.TextInput(attrs={'type': 'text', 'placeholder': 'First Name', 'class': 'form-control input-md'}) } labels = { 'first_name': "First Name" } views.py def profile(request): user = UserForm() user_info = ProfileForm() return render(request, 'pages/demo.html', {'user': user}) demo.html <label style="margin-left: -48px; margin-right: 48px;" class="col-md-4 control-label">{{ ??? }}</label> -
Cannot import apps in django project with vscode
In vscode I am trying to import Apps in my django project. But as below screen shot, I cannot import my apps in urls.py. I also added my apps into mysettings(INSTALLED_APPS). vscode error -
How create simplest possible template for view with inline formset?
I have my view where I used inline formset, but I don't know how to display this formset in my template, in normal view I would use <form method='POST' action=''> {%csrf_token%} {{form.as_p}} But I don't know how to do this in this case. This is my view: class AddBookView(CreateView): model = Book form_class = AddBookForm formset_class = IndustryIdentifiersFormSet success_url = reverse_lazy('add_book') def get_context_data(self, **kwargs): data = super(AddBookView, self).get_context_data(**kwargs) if self.request.POST: data['identifiers'] = IndustryIdentifiersFormSet(self.request.POST) else: data['identifiers'] = IndustryIdentifiersFormSet() return data def form_valid(self, form): context = self.get_context_data() identifiers = context['identifiers'] with transaction.atomic(): self.object = form.save() if identifiers.is_valid(): identifiers.instance = self.object identifiers.save() return super(AddBookView, self).form_valid(form) def get_success_url(self): return self.success_url -
How to create a search query to search a local JSON file using python?
I just want to search this JSON data shown below when the search button is clicked and it shows the results in a table using Python but I am unsure as to how to create a search query. {"returnCode":0,"message":null,"resultList":[{"poNo":"0000123456","deliveryDock":"D1","dcNo":"DC01","vendorNo":"0001112222","orderDate":"2019-06-07","deliveryDate":"2019-06-02","deliveryTime":"00:00","noOfPallets":"10.0000","source":"MANUAL","status":"Scheduled","auditList":[{"oldDeliveryDock":"D2","oldDeliveryDate":"2019-06-03","oldDeliveryTime":"01:30","changedBy":"XASNH","changedOn":"2019-06-07","reasonCode":"FCST"},{"oldDeliveryDock":"D3","oldDeliveryDate":"2019-06-04","oldDeliveryTime":"03:30","changedBy":"XRCA4","changedOn":"2019-06-07","reasonCode":"WOW"}]}]} This is the design of the search query and the tables where the results should show ` -
How to get my like button in django to work?
I am trying to get my like button to work on my website. You can make "tweets" on my website, but users are not able to like the post. I already have the front end set up with ajax. that works perfect. The problem lies in my views. Here is my models class Tweet(models.Model): tweet_user = models.ForeignKey(User, on_delete=models.CASCADE) tweet_message = models.TextField() tweet_date = models.DateTimeField(auto_now_add=True) tweet_like_counter = models.IntegerField(default=0) tweet_picture = models.FileField(null=True,blank=True) def __str__(self): return self.tweet_message class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet.tweet_message class Disike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet.tweet_message class TweetComment(models.Model): class Meta: ordering = ['-id'] tweetcomment = models.ForeignKey(Tweet, on_delete=models.CASCADE, related_name='tweetcomments') tweetcommentauthor = models.ForeignKey(User,on_delete=models.CASCADE) tweetcommentmessage = models.TextField() tweetcommentcomment_date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweetcommentmessage Here is my view from django.views.decorators.csrf import csrf_exempt @csrf_exempt @login_required def like(request, pk): currentTweet = get_object_or_404(Tweet,pk=pk) user = User.objects.get(pk=request.user.id) like = Like.objects.create(tweet=currentTweet, user=user) like_queryset = Like.objects.filter(tweet=currentTweet, user=user) dislike_queryset = Disike.objects.filter(tweet=currentTweet, user=user) if like_queryset.exists(): Like.objects.filter(tweet=currentTweet, user=user).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() if dislike_queryset.exists(): Disike.objects.filter(tweet=currentTweet, user=user).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() return JsonResponse({ 'like_counter': currentTweet.tweet_like_counter …