Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
no such column: accounts_articles.Author_id,
I'm trying to get the author of the article from CustomUser Model using foreignKey but apparently something is missing and I don't know what it is class CustomUser(AbstractUser): email = models.EmailField(unique=True, blank=False,) zip_code = models.CharField(blank=True, max_length=5) username = models.CharField(unique=True, blank=False, max_length=30) class Articles(models.Model): title = models.CharField(max_length=20) content = models.TextField() slug = models.SlugField(blank=True) published = models.BooleanField(default=False) created_at = models.DateField(auto_now_add=True) Author = models.ForeignKey(CustomUser, on_delete=SET_NULL, null=True)# the problem is here -
UUID as primary key throws an overflow error despite trying to use taggit
I am trying to use UUID as a primary key on a model and it throws an Overflow error when using redirect. I looked online for similar problems as I assume it should be quite frequent that people want to do that. I came accross: https://github.com/jazzband/django-taggit/issues/679 So I installed dajngo-taggit and I tried to add the snippet on this link in my code but the problem remains. Below is my current code using the snippet: [models.py] from django.db import models from taggit.managers import TaggableManager from taggit.models import GenericUUIDTaggedItemBase, TaggedItemBase class Person(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) # ... class UUIDTaggedItem(GenericUUIDTaggedItemBase, TaggedItemBase): # If you only inherit GenericUUIDTaggedItemBase, you need to define # a tag field. e.g. # tag = models.ForeignKey(Tag, related_name="uuid_tagged_items", on_delete=models.CASCADE) class Meta: verbose_name = _("Tag") verbose_name_plural = _("Tags") class Car(models.Model): person = models.ForeignKey(Person, null=True, on_delete=models.SET_NULL) brand = models.CharField(max_length=50) colour = models.CharField(max_length=50) # ... [urls.py] # ... urlpatterns = [ # ... path("<uuid:pk>/car/<int:id>/", CarDetail.as_view(), name="car_detail"), # ... ] And the error I get is: OverflowError at /en/person/c8c91051-5773-4c69-9587-92b468186db7/car/1/ Python int too large to convert to SQLite INTEGER Would you have any ideas of what I could try to fix it? I have been on … -
Unable to create account --- Djoser, Django_Rest_Framework
My Custom Model My Custom Serializer My Custom Manager My Error -
Django Error: Reverse for 'signup' not found. 'signup' is not a valid view function or pattern name
When I run the code it gives the message: django.urls.exceptions.NoReverseMatch: Reverse for 'signup' not found. 'signup' is not a valid view function or pattern name. user/home.html enter image description here user/views.py enter image description here user/urls.py enter image description here main/urls.py enter image description here -
Django creating Abstract user models
I am trying to create a user models for me django project where doctor and patient can both signup using same form but will update their profile with different fields, but i got error saying there was clashes even after deleting the previous migrations and SQLite database on my project. here is the error message : ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'users.User.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'users.User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'users.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'users.User.user_permissions'. users.User.groups: (fields.E304) Reverse accessor for 'users.User.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'users.User.groups' or 'auth.User.groups'. users.User.user_permissions: (fields.E304) Reverse accessor for 'users.User.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'users.User.user_permissions' or 'auth.User.user_permissions'. here is the code for the user and profile update` DEPARTMENTS=[ ('Anesthesiology','Anesthesiology'), ('Pharmacy','Pharmacy'), ('Radiology', 'Radiology'), ('Gastroenterology', 'Gastroenterology'), ('Orthopaedics', 'Orthopaedics'), ('Community Medicine', 'Community Medicine'), ('Internal Medicine', 'Internal Medicine'), ('Laboratory', 'Laboratory'), ('Nursing', 'Nursing'), ('Medical Records', 'Medical Records'), ('Cardiology', 'Cardiology'), ('Pediatrics', 'Pediatrics'), … -
How to host api documentation(abc.com/docs) on docs.abc.com on django+gunicorn+nginx setup
We have Django rest API deployed using Nginx through reverse proxy. Sample config: location / { proxy_set_header Host $host; include proxy_params; proxy_pass http://unix:/run/websitebackend.sock; } listen 443 ssl http2; # managed by Certbot ssl_certificate /etc/ssl/private/chain.crt; ssl_certificate_key /etc/ssl/private/private.key; } Now our API documentation(genereted using redoc) is on api.abc.com/docs, which we want to server on subdomain docs.abc.com. How can I achieve this? Thanks in advance! -
Best practice to store the order of table rows?
I have table which has columns like these class AgeAndName(models.Model): name = m.CharField(max_length=20) age = m.IntegerField name age ---- -- John 22 Hitch 38 Heiku 25 Taro 36 Cho 40 Now I want to allow the user to sort as he like, and keep. then I think of two ways. 1.make new column and keep order's class AgeAndName(models.Model): name = m.CharField(max_length=20) age = m.IntegerField order = m.IntegerField name age order ---- -- ----- John 22 1 Hitch 38 5 Heiku 25 3 Taro 36 4 Cho 40 2 2.make one property for model and keep them. class AgeAndName(models.Model): @classmember??? ( I am not sure I have this kind of thing) order = (0,4,2,3,1) name = m.CharField(max_length=20) age = m.IntegerField Which one is the best practice for django?? Or is there any other good way ? -
How can i solve my licensing problem using Django
How can we create the best software licensing algorithm to avoid violation using Django. Users should not be able to use the software by changing the date of the system once the license is expired. -
Enable pdf comment via Python?
i want to enable comment in bunch of pdf . is there any chance to doing this in python???like the following image import os import winerror from win32com.client.dynamic import Dispatch, ERRORS_BAD_CONTEXT ERRORS_BAD_CONTEXT.append(winerror.E_NOTIMPL) my_dir = r"C:\cpsmails" my_pdf = "one.pdf" os.chdir(my_dir) src = os.path.abspath(my_pdf) try: AvDoc = Dispatch("AcroExch.AVDoc") if AvDoc.Open(src, ""): pdDoc = AvDoc.GetPDDoc() jsObject = pdDoc.GetJSObject() jsObject.SaveAs() except Exception as e: print(str(e)) finally: AvDoc.Close(True) jsObject = None pdDoc = None AvDoc = None -
Slice the string from Django template tag's variable
Is it possible to slice the string from Django template tag's variable? Let's say some_variable contain "abcde" I want it to be sliced to be "abc" On Django's template, I tried like this. {{some_variable[:-2]}} It does not work. If it's possible to slice words from Django template tag's variable, please advise me how to do it. -
Django Rest Framework how to serialize a many to many relational Model?
I am doing a project in Django Rest Framework. Now I am trying to serialize many to many relations, but I don't know how this works. Here is my models' code: Model for files def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class Document(models.Model): name = models.CharField(max_length=250, blank=True, null=True) document = models.FileField(upload_to=user_directory_path) def __str__(self): return self.name Model for Expenses and loans class Expenses(models.Model): name = models.CharField(max_length=250, blank=True, null=True) amount = models.DecimalField(default=0.0, decimal_places=2, max_digits=10) date = models.DateField(auto_now=True) additional_files = models.ManyToManyField(Document, blank=True, related_name="expenses") # Upload multiple files def __str__(self): return self.name class Loans(models.Model): name = models.CharField(max_length=250, blank=True, null=True) amount = models.DecimalField(default=0.0, decimal_places=2, max_digits=10) loan_from = models.CharField(max_length=250, blank=True, null=True) date = models.DateField(auto_now=True) additional_files = models.ManyToManyField(Document, blank=True, related_name="loans") # Upload multiple files def __str__(self): return self.name My question: Just want to know how to serialize these additional_files in the Expenses and Loans. It will be much better if give resources and explanations of how that works. -
Delete one of multiple Heroku remote branches (Heroku CLI)
Currently I develop a Django application, which I've deployed on Heroku. intention I just wanted to switch from master to main. Before I've unfortunately done: git push heroku master That's why I have two different remote branches now (heroku/main and heroku/master): (HEAD -> main, heroku/master, heroku/main) What I've tried To delete the heroku/master I've tried the following (which didn't work): git branch -d heroku/master git branch -d master git branch -d heroku:master heroku git branch -d heroku/master git remote rm heroku/master What worked (kind of) Finally I've removed the complete remote using git remote rm heroku Now I don't see the remote on the command line anymore ((HEAD -> main)) But interestingly the app is still available online and in the heroku dashboard. (Now I am going to figure out how to work with the heroku remote again in the command line) But I wonder Isn't there a way to delete the above mentioned heroku/master branch (which is actually just a duplicate of the heroku/main) without removing the complete remote? -
Need to return the User ID along with the access and refresh token while fetching the JWT access token in django rest framework
viewset class CustomRenderer(JSONRenderer): def render(self, data, accepted_media_type=None, renderer_context=None): status_code = renderer_context['response'].status_code response = { "status": "success", "code": status_code, "data": data, "message": None, "user_id": models.Default_User.objects.all(self.id) } if not str(status_code).startswith('2'): response["status"] = "error" response["data"] = None try: response["message"] = data["detail"] except KeyError: response["data"] = data return super(CustomRenderer, self).render(response, accepted_media_type, renderer_context) settings REST_FRAMEWORK= { 'DEFAULT_PERMISSION_CLASS':'rest_framework.permissions.IsAuthenticated', 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=7), 'REFRESH_TOKEN_LIFETIME': timedelta(days=30), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } I need the user id in the response to be fetched while getting the JWT access token call. Currently i couldn't able to fetch the user id along with the responses i coded above. Is there any way to fetch it or else is there any way to decode the token and take the user id and display while getting the token in the code itself. Kindy help me as i am new to this authentication. -
Ubuntu + Django + SQLite - attempt to write a readonly database
I'm hosting my Django project with Apache on a Ubuntu 20.04 server with the standard SQLite database. It works but the database seems to be read-only. When we write to the database we get an OperationalError: attempt to write a readonly database I have tried to change the permissions according to the guide below https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-16-04 I've changed the permissions of the sqlite file to 664 and gave user www-data ownership of the file and the parent folder. Yet I'm still getting the same error. Any ideas what else could be causing this problem? -
'RelatedManager' object has no attribute '_meta'
So I have a view that distuingishs between two different forms by checking the submit buttons name. The first case UserProfileForm works just great but the BankForm case returns the error 'RelatedManager' object has no attribute '_meta' Why's that? # views.py def render_dashboard_profile(request): # Get the user object user = request.user # Get the bank object bank_obj = Bank.objects.get(account_holder=user) # Create a pre-populated form instance for both models user_profile_form = UserProfileForm(instance=user.userprofile) bank_form = BankForm(instance=user.userprofile) # Create Context context = { 'user_profile_form': user_profile_form, 'bank_form': bank_form, 'bank_obj': bank_obj } if request.method == 'POST': form = {} # Determine which form was submitted if 'profile-submit' in request.POST: form = UserProfileForm(request.POST, instance=user.userprofile) # that one works elif 'bank-submit' in request.POST: form = BankForm(request.POST, instance=user.account_holder) # breaks here if form.is_valid(): form.save() return render(request, 'dashboard/dashboard_profile.html', context) else: return render(request, 'dashboard/dashboard_profile.html', context) # forms.py class BankForm(ModelForm): """ A form to change the bank data of a user """ class Meta: model = Bank fields = ['name', 'bic', 'iban'] # models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) surname = models.CharField(max_length=30) .. class Bank(models.Model): """ Stores data about the bank account of a user/investor """ account_holder = models.ForeignKey(User, on_delete=models.CASCADE, related_name='account_holder') name = models.CharField(max_length=30) bic = models.CharField(max_length=10) iban = models.CharField(max_length=30) -
Host Django on VPS Server main IP address not in Host Port
I am trying to deploy a application using Django on VPS server. It is working perfectly. All things are okay. But Here suppose this is my VPS server http://23.234.207.249 but if I click this link it is showing me a apache default page. but if I hit this http://23.234.207.249:8000 after adding port :8000 it is working and showing my application. But I want to show the same in my main IP Address. Which procedure to follow? Here I am deploying with Docker, this is my docker compose file version: '3' services: app: build: . volumes: - .:/django ports: - 8000:8000 image: app:django container_name: django_containe command: python manage.py runserver 0.0.0.0:8000 depends_on: - db db: image: mysql:5.7 environment: MYSQL_DATABASE: 'gascommerce' MYSQL_ALLOW_EMPTY_PASSWORD: 'true' volumes: - ./data/mysql/dbb:/var/lib/mysql -
hey plz help me in my project i am stuck ---->>>> please
hello I am a beginner in django what i want to do is take input through voice in python and simultaneously output it on webpage using django now 1] problem is when i take input using get mehtod it start taking input through voice but without rendering the web page Eg- when start the server it start taking input without loading the page,when all the input are taken then it loads the page and shows us the value 2] when i take input using post mehtod it take input properly as i want but it does not show the output on web page simultaneously, i have seen javasricpt speech to text code snippet were we give input though voice and it shows us on webpage simultaenously but i dont want to use javascript is there any other way please help me my post method code def sample(request): bet = {} if request.method =='POST': TextToSpeech("say your username",230) username=speechtotext(5,'username') TextToSpeech("say your username",230) password=speechtotext(5,'email') print(password) bet.update({'username':username}) bet.update({'eamil':email}) return render(request,'sample.html',context=bet) below is my html code {% extends 'layout.html' %} {% load static %} {% block title %} Welcome !-COMPOSE-! {% endblock %} {% block lay %} <body onclick = "WhichButton(event)"> <div align="center" class="p-5 m-3"> … -
How to test "POST" method via url with dynamic argument (Django Rest Framework)?
I need to test some API endpoints in my app I.e. I want to create "Bookmark" using Django Rest Framework using "toggle_bookmark/<exercise_id>" url How can I substitute a value for <exercise_id> in my test_boomark.py file? This is my urls.py file: from django.urls import path, include from rest_framework import routers from api import bookmark, daily_exercise, like, upload from api.exercise import ExerciseViewSet, exercise_user_info, toggle_done from api.plan import PlanViewSet from api.practice_session import PracticeSessionViewSet from api.practice_session_exercise import PracticeSessionExerciseViewSet app_name = "api" router = routers.DefaultRouter() router.register(r"exercise", ExerciseViewSet) router.register(r"plan", PlanViewSet) router.register(r"practice-session", PracticeSessionViewSet) router.register(r"practice-session-exercise", PracticeSessionExerciseViewSet) urlpatterns = [ path("", include(router.urls)), path("upload-file", upload.upload_file, name="upload_file"), path("exercise_user_info/<user_plan_uid>/<practice_session_exercise_uid>", exercise_user_info, name="get_exercise_user_info"), path("toggle_bookmark/<exercise_id>", bookmark.toggle_bookmark, name="toggle_bookmark"), path("toggle_daily_exercise/<exercise_id>", daily_exercise.toggle_daily_exercise, name="toggle_daily_exercise"), path("toggle_like/<exercise_id>", like.toggle_like, name="toggle_like"), path("toggle_done/<user_plan_uid>/<practice_session_exercise_uid>", toggle_done, name="toggle_done"), ] Here is my test_bookmark.py file: import json from django.urls import reverse from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase, APIClient from rest_framework import status from core.models import User, Bookmark class BookmarkTests(APITestCase): def test_bookmark_api(self): """ Bookmark API Test """ user = User.objects.create_user(email='test@gmail.com', name='lauren') client = APIClient() client.force_authenticate(user=user) client.post('toggle_bookmark/<exercise_id>',{"exercise_id":"123123","exercise":"exerciese1"},format="json") assert response.status_code == 201 -
Apache - HTTPS with one certificate for two different ports - Only one is accessible at a time
I'm trying to host 2 (different) servers on a single domain. One is hosted on port 8000 and the other on 8080. I want both to be accessible with HTTPS using the same certificate. Below is my conf file (both servers use the exact same configuration, just different ports and names). They both work perfectly in HTTP. However only one of the two is accessible in HTTPS for some reason, the other will load infinitely until timeout. <VirtualHost *:8080> OR <VirtualHost *:8000> ServerAdmin webmaster@localhost ServerName example.stratoserver.net ServerAlias www.example.stratoserver.net DocumentRoot /var/www/st-backend ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/st-backend/static <Directory /var/www/st-backend/static> Require all granted </Directory> Alias /static /var/www/st-backend/media <Directory /var/www/st-backend/media> Require all granted </Directory> <Directory /var/www/st-backend/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess st-backend python-home=/var/www/st-backend/stenv python-path=/var/www/st-backend WSGIProcessGroup st-backend WSGIScriptAlias / /var/www/st-backend/project/wsgi.py #HTTPS SSLEngine on Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/example.stratoserver.net/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.stratoserver.net/privkey.pem </VirtualHost> ports.conf Listen 8080 Listen 8000 <IfModule ssl_module> Listen 443 </IfModule> <IfModule mod_gnutls.c> Listen 443 </IfModule> Can anyone point me in the right direction as to why I can't get both working with HTTPS at the same time? I would highly appreciate it. -
DRF NoReverseMatch
I am able to create and save a vote with postman, but when running a unittest with the functionality using reverse, it can't find the URL. I've tried a combination of running this with and without args/kwargs and nothing seems to work. It also appears to be in line with the documentation views.py class EntryViewSet(viewsets.ModelViewSet): @action(detail=True, methods=['post'], permission_classes=[IsAuthenticated]) def vote(self, request, *arg, **kwargs): ... tests.py def test_vote_entry_success(self): self.authenticate_client(self.other_user_data) response = self.client.post(reverse('api:entries-vote'), kwargs={'slug': self.entry.slug}) self.assertEqual(response.status_code, status.HTTP_201_CREATED) error message django.urls.exceptions.NoReverseMatch: Reverse for 'entries-vote' with no arguments not found. 2 pattern(s) tried: ['api/entries/(?P<slug>[^/.]+)/vote\\.(?P<format>[a- z0-9]+)/?$', 'api/entries/(?P<slug>[^/.]+)/vote/$'] I used django-entensions to see map my URLs and the action is showing up as a valid route /api/entries/<slug>/vote/ api.views.EntryViewSet api:entries-vote And the test works when I hard-code the URL response = self.client.post('/api/entries/'+self.entry.slug+'/vote/') -
How to serialize multiple model object?
I am creating an API using Django Restframework which needs data from multiple models. I got many answers for my requirement but it isn't working. I have my models as follows class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.title class Task_extended(models.Model): task_id = models.ForeignKey(Task, on_delete = models.CASCADE,related_name='task_extendeds') field_3 = models.CharField(max_length=200) field_5 = models.CharField(max_length=200) field_4 = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.field_3 Here's my view function @api_view(['GET','POST']) def taskList(request): tasks = Task.objects.all() serializer = TaskSerializer(tasks, many =True) return Response(serializer.data) Serializer.py class TaskSerializer(serializers.ModelSerializer): task_extendeds = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Task fields = "__all__" depth = 1 I am getting the json as following [ { "id": 2, "task_extendeds": [ 1, 2, 3 ], "title": "Start Rest Framework", "completed": false } ] What changes should I do to Serializers.py so that my json output is as following [ { "id": 2, "title": "Start Rest Framework", "completed": false, "task_extendeds": [ { "field_3": "Field 3 Data", "field_4": "Field 4 Data", "field_5": "Field 5 Data" }, { "field_3": "Field 3 Data", "field_4": "Field 4 Data", "field_5": "Field 5 Data" }, { "field_3": "Field 3 Data", "field_4": "Field 4 Data", "field_5": "Field 5 Data" } ], } ] … -
Django Not Found: /assets/js/main.js How Can I Solve this?
This is the error I am facing Not Found: /assets/vendor/venobox/venobox.css Not Found: /assets/vendor/boxicons/css/boxicons.min.css Not Found: /assets/vendor/owl.carousel/assets/owl.carousel.min.css [12/Mar/2022 13:49:17] Not Found: /assets/vendor/icofont/icofont.min.css "GET /assets/vendor/venobox/venobox.css HTTP/1.1" 404 3280Not Found: /assets/vendor/bootstrap/css/bootstrap.min.css [12/Mar/2022 13:49:17] Not Found: /assets/vendor/remixicon/remixicon.css "GET /assets/vendor/boxicons/css/boxicons.min.css HTTP/1.1" 404 3310 [12/Mar/2022 13:49:17] "GET /assets/vendor/owl.carousel/assets/owl.carousel.min.css HTTP/1.1" 404 3343Not Found: /assets/vendor/aos/aos.css [12/Mar/2022 13:49:17] "GET /assets/vendor/icofont/icofont.min.css HTTP/1.1" 404 3292 [12/Mar/2022 13:49:17] Not Found: /style.css "GET /assets/vendor/bootstrap/css/bootstrap.min.css HTTP/1.1" 404 3316 [12/Mar/2022 13:49:17] "GET /assets/vendor/remixicon/remixicon.css HTTP/1.1" 404 3292 [12/Mar/2022 13:49:17] "GET /assets/vendor/aos/aos.css HTTP/1.1" 404 3256 [12/Mar/2022 13:49:17] "GET /style.css HTTP/1.1" 404 3208 Not Found: /assets/js/main.js [12/Mar/2022 13:49:17] "GET /assets/js/main.js HTTP/1.1" 404 3232 my css was not loaded in my template and it shows this error in terminal please help me to solve this -
using django can you build form
[enter image description here][1] can you make form exact same [1]: https://i.stack.imgur.com/D2Nkp.png -
Why the categories is not shown in the dropdown?
<a href="#">Categories</a> {% for categories in links %} <ul class="dropdown"> <li><a href="#">{{ category.category_Name }}</a></li> </ul> {% endfor %} I'm not able to see drop-down list. -
Django button like Without Page Refresh Using Ajax and Load html page with ajax info
I am doing a project which has a like or un-like button for each post on web-page. But when I click on like, I get a page that looks like this (http://127.0.0.1:8000/give_like/2): {"post_to_like": 2} view.py def give_like(request, post_to_like): like = Likes(user=request.user, post = Post.objects.get(id=post_to_like)) checker = [like.post_id for like in Likes.objects.filter(user = request.user)] if post_to_like in checker: Likes.objects.filter(post_id=post_to_like, user = request.user).delete() else: like.save() return JsonResponse({'post_to_like':post_to_like}) how to load the whole page correctly as html but without reloading the whole page and get info that Im already follow this post so i should see button un-like and the rest of the page? js.js var like = document.getElementById("like"); likeDislike(like, function() { fetch(`/give_like/${like.dataset.post_to_like}`) .then(response => response.json()) .then(data => { like.querySelector('small').innerHTML = data.total_likes; }); } ); index.html <small><p id="total_likes" > {{post.current_like}} </p></small> urls.py path("give_like/<int:post_to_like>", views.give_like, name="give_like"),