Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error installing uWSGI always when i try it in linux
when i install uWSGI with: pip install uwsgi raise error: *** uWSGI compiling server core *** [x86_64-linux-gnu-gcc -pthread] core/utils.o x86_64-linux-gnu-gcc: fatal error: cannot execute ‘cc1’: execvp: No such file or directory compilation terminated. ---------------------------------------- ERROR: Failed building wheel for uwsgi my ubuntu: 20.04 python: 3.8.10 also i have installed all required packages like: python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools as general question why i always have problem with uWSGI installation? in every VPS, in every Linux i had error Failed building wheel. I confused why others dont face with this problems! -
xterm.js term.onData is not a function
I am programming a terminal application using xterm.js in frontend and django at backend. Everything works fine but when i try to save the input from the user using onData i get it is not a function error. If you have another approach please tell me. I tried getting current line but run into problems if user press backspace or delete. index html: var socket = io.connect({ transports: ["websocket", "polling"] }); const status = document.getElementById("status") const button = document.getElementById("button") var term = new Terminal({ cursorBlink: true, }); term.open(document.getElementById('terminal')); var curr_line = ''; var entries = []; var currPos = 0; var pos = 0; var prompt_startpos = term._core.buffer.x term.onData(data => { console.log("Data received:", data); socket.emit("pty_input", { "input": data }); }); views py: async_mode = "eventlet" sio = socketio.Server(async_mode=async_mode) fd = None child_pid = None def index(request): return render(request, "index.html") def set_winsize(fd, row, col, xpix=0, ypix=0): winsize = struct.pack("HHHH", row, col, xpix, ypix) fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize) def read_and_forward_pty_output(): global fd max_read_bytes = 1024 * 20 while True: sio.sleep(0.01) if fd: timeout_sec = 0 (data_ready, _, _) = select.select([fd], [], [], timeout_sec) if data_ready: output = os.read(fd, max_read_bytes).decode() sio.emit("pty_output", {"output": output}) else: print("process killed") return @sio.event def resize(sid, message): if fd: set_winsize(fd, … -
Django passing extra context from Form View after working on form fields
So I have a form in which I get some data, and I use this data to retrieve an object from some model. But, I am not able to pass the data I retrieved from this object into the context in the is_valid function. It breaks the success redirect logic. What can I do for this situation? -
How to open any encoding CSV without crashing Python?
I'm working on a Django APP that needs to import a CSV database and generate the products in the system, but depending on the CSV encoding the APP is crashing. I tried a way to read the CSV encoding to vary the way to open it, but it still keeps crashing. -
ModuleNotFoundError: No module named 'log_request_id.filters'
While setting up the environment for project, I am getting this error. ModuleNotFoundError: No module named 'log_request_id.filters' LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "tenant_context": {"()": "tenant_schemas.log.TenantContextFilter"}, "request_id": {"()": "**log_request_id.filters**.RequestIDFilter"}, }, ... } I have tried installing, django_log_request_id and log_request_id, also tried to do some changes. -
How to check if an entry is created with one object in another model in entire django project?
Suppose I have a warehouse model. Now before deleting this warehouse object i wanna check that if this particular object is used in some other model or not? class Warehouse(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=250, default=0) email = models.EmailField(max_length=50, default=0) contact = models.CharField(max_length=50, default=0) address = models.CharField(max_length=500, default=0) now I have 1500 different models in my project so i cannot write a query to check whether it's pk exists in them or not so what's the fastest way to do this ? -
my generic view inherited from CreateView in django does not show model fields to fill out when I run my django project
I create an app in django named 'sampleapp' then in models.py I define my model as follows: from django.db import models from django.urls import reverse class Employee(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) mobile = models.CharField(max_length=10) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) and also in forms.py: from .models import Employee from django import forms class EmployeeForm(forms.ModelForm): class Meta: # To specify the model to be used to create form model = Employee # It includes all the fields of model fields = '__all__' then in views.py: from django.shortcuts import render from .models import Employee from .forms import EmployeeForm from django.views.generic.edit import CreateView from django.urls import reverse_lazy class EmployeeCreate(CreateView): model = Employee fields = '__all__' and in urls.py file: from django.urls import path from .views import EmployeeCreate urlpatterns = [ path('', EmployeeCreate.as_view(), name='EmployeeCreate') ] and also I put employee_form.html (an empty html file) in 'myproject/template/sampleapp/employee_form.html'. But when I run my project and go to url "http://127.0.0.1:8000/" I receive an empty html file, a page without any field to fill out (like first_name field last_name field and so on). How can I create an Employee object using django generic view 'CreateView'? -
cannot import name 'load_dotenv' from 'dotenv' with django docker
I try to dockerize django. So I have this Docker file: # pull official base image FROM python:3.9-alpine3.13 # set work directory WORKDIR /usr/src/app EXPOSE 8000 # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add linux-headers postgresql-dev gcc python3-dev musl-dev # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . COPY ./requirements.dev.txt . RUN pip install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' /usr/src/app/entrypoint.sh RUN chmod +x /usr/src/app/entrypoint.sh # copy project COPY . . # run entrypoint.sh CMD ["python3", "manage.py", "runserver"] and Docker compose: version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - .:/app command: > sh -c "python ./manage.py migrate && python ./manage.py runserver 0:8000" env_file: - ./.env volumes: dev-static-data: and my requirements.txt looks like: Django>=4.0.4 djangorestframework>=3.13.1 psycopg2>=2.9.3 drf-spectacular>=0.22.1 Pillow>=9.1.0 drf-yasg==1.20.0 django-cors-headers==3.10.1 django-environ django-dotenv http://github.com/unbit/uwsgi/archive/uwsgi-2.0.zip I can build the docker container. But I can't run it. If I do a docker-compose up. I get this error:" Traceback (most recent call last): dwl_backend-app-1 | File "/usr/src/app/./manage.py", line 5, in <module> dwl_backend-app-1 | from DierenWelzijn.settings import base dwl_backend-app-1 | File "/usr/src/app/DierenWelzijn/settings/base.py", line 15, in <module> dwl_backend-app-1 | … -
My code doesnt work. Please check and help me
When you click the Изменить(Edit) button, nothing happens, it seems to be written correctly, but it does not work.I expect that when I click the Изменить(Edit) button, I can change the existing task, save it, and in case of accidental clicking exit. urls.py: from django.urls import path from . import views app_name = 'todoist' urlpatterns = [ path('', views.index, name='index'), path('add', views.add, name='add'), path('delete/<int:today_id>/', views.delete, name='delete'), path('update/<int:today_id>/', views.update, name='update'), path('edit/<int:today_id>/', views.edit, name='edit'), ] views.py: from django.shortcuts import render,redirect from .models import Today from django.views.decorators.http import require_http_methods def index(request): todos = Today.objects.all() return render(request, 'today.html', {'todos':todos}) @require_http_methods(['POST']) def add(request): tasks = request.POST["tasks"] task = Today(tasks=tasks) task.save() return redirect('todoist:index') def delete(request, today_id): todo = Today.objects.get(id=today_id) todo.delete() return redirect('todoist:index') def update(request, today_id): todo = Today.objects.get(id=today_id) todo.tasks = request.POST.get('tasks') todo.save() return redirect('todoist:index') def edit(request, today_id): todo = Today.objects.get(id=today_id) todo.edit_mode = True todo.save() return redirect('todoist:index') today.html: <title>Todoist</title> <h1>Сегодня</h1> <h2>Задачи</h2> <form method="POST" action="{% url 'todoist:add' %}" >{% csrf_token %} <input type="text" name='tasks' pattern=".{2,}" required title='Минимум два символа!!!'> <button type="submit" class="save btn btn-default">Добавить задачу</button> </form> <ol> {% for todo in todos %} <div> {% if todo.edit_mode %} <form action="{% url 'todoist:update' today_id=todo.id %}" method="POST"> {% csrf_token %} <input type="text" name="tasks" value="{{ todo.tasks }}"> <button type="submit" class="save btn … -
Post method in Django not allowed
I am trying to send post request via Swagger but I am getting Method Not Allowed Error. Url I use is /add. I think the code is fine but there has to be something I am missing. router = Router() @router.post("/add", response={200: None}) def add_new_breached_data(request, data: DataBreachDto): add_new_breach(data) return 200 Data send in request (DataBreacheDto is created for this type of data): { "platform": "Test", "name": "Test1", "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "date": "2023-08-11T09:56:41.604Z", "size": 500 } -
Apache not serving Django static files despite correct Alias and Directory directives
I'm having trouble getting Apache to serve static files for my Django project hosted on a separate server. My main server, http://metadbdev.riken.jp/BEHF, is where the Apache configuration resides. I'm trying to enable the Django server on 192.168.80.86 and serve its static files through the main server. Apache Configuration (httpd.conf): ## BEHF ProxyPass /BEHF/static/ ! Alias /BEHF/static/ /home/julio/repos/event_finder/django_frontend/staticfiles/ <Directory /home/julio/repos/event_finder/django_frontend/staticfiles/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Location /BEHF> ProxyPass http://192.168.80.86:8000 ProxyPassReverse http://192.168.80.86:8000 </Location> Django settings.py static settings: BASE_DIR = Path(__file__).resolve().parent.parent # STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['192.168.80.86','127.0.0.1','http://metadbdev.riken.jp/'] STATIC_URL = '/BEHF/static/' # STATIC_URL = 'http://192.168.80.86/BEHF/static/' STATIC_ROOT = '/home/julio/repos/event_finder/django_frontend/staticfiles/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] Directory Listing: . ├── db.sqlite3 ├── django_frontend │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── nohup.out ├── search_engine │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── migrations │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── static │ ├── images │ └── styles ├── staticfiles │ ├── admin │ ├── bef.png │ ├── images │ ├── lol.txt │ └── … -
How to use a bash variable as id in docker exec command
I have a docker container id stored in a variable in a bash script and i need to use this variable in docker exec command like this : $OUTPUT=containerid docker exec -t $OUTPUT sh -c "python manage.py dumpdata > $backup_file_name"`` this code raise the error below : CommandError: Unable to serialize database: no such table: django_admin_log the docker exec command works perfectly with the id and create the backup of django database but i need to run it with a variable, how can i achieve this goal? i have tried it with the tag -it and -d but still not working -
Will Django channels good for to use asynchronous long running background functionality
While working on request where i need to do long running bulk operation on backend ( which takes almost 15-30 min now) for each individual user to avoid load on database. I see Django channel with Redis as channel layer can helps to achieve this. Will that be good fit to do this as asynchronous long running job separately using Django channels. I saw mostly its used for real time communication not sure will that used for my purpose also. Please suggest thoughts will that be right approach or any other option should i use to perform long running background functionality while using Django. No option tried just explored django channel -
Linkedin 3-legged OAuth throws 'Not enough permissions to access: GET /userinfo'
I was trying to integrate social login for my Django application using linkedin OAuth2. I have followed steps described in their official page here. In step2, I have given 'profile' value for scope parameter, given below are the allowed scopes in my app. The scopes listed in my linkedin app page. I have successfully completed up to step3, and I got access_token successfully. But when I tried an authenticated request using that access token for example, curl -X GET https://api.linkedin.com/v2/userinfo, I am getting an error like b'{"serviceErrorCode":100,"message":"Not enough permissions to access: GET /userinfo","status":403}'. I have tried v2/me, getting the same permission error. Given bellow are the code snippets. def login(request): return render(request, 'login.html') def authenticate(request): redirect_url = f'https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={settings.SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY}&redirect_uri={settings.LOGIN_REDIRECT_URL}&state={settings.STATE}&scope=profile' return redirect(redirect_url) def complete(request): code = request.GET.get('code', None) state = request.GET.get('state', None) url = "https://www.linkedin.com/oauth/v2/accessToken" headers = {"Content-Type": "application/x-www-form-urlencoded"} payload = { 'grant_type': 'authorization_code', 'code': code, 'client_id': settings.SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY, 'client_secret': settings.SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET, 'redirect_uri': settings.LOGIN_REDIRECT_URL } response = requests.post(url, headers=headers, data=payload) if response.status_code == 200: access_token = json.loads(response.content)['access_token'] print(access_token) info_url = 'https://api.linkedin.com/v2/userinfo' headers = {'Authorization': f'Bearer {access_token}'} info_response = requests.get(info_url, headers=headers) print(info_response.content) # getting error here like b'{"serviceErrorCode":100,"message":"Not enough permissions to access: GET /userinfo","status":403}' How do I get permission for the scope 'profile'? As per … -
Questions regarding react in django or react as standalone
I am creating an website using react and Django. To combine Django and react there are 2 ways React in its own “frontend” Django app: load a single HTML template and let React manage the frontend (difficulty: medium) Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication) Now my questions are What are security concerns related to both and which of them is more secure way to do it. In Option-1 we can use both session and token based authentication while in Option-2 we must use token based authentication and XSRF header is needed. Is session based auth better and in what factors it effects If in future I plan to move to react Native for mobile app, which would be more suitable. (I could not find any example when using Option-1) Apparently, Instagram is using session based auth, which means they have used Option-1. Are Option-1 sites SPA based and is Insta SPA based. An extra unrelated question, which is better JWT token auth or Django knox auth. If JWT is better please refer any guide on integrating it with Django. -
jwt decode giving empty username in django unittest while using request.META
I am writing unittests in django with jwt. I am using the following method to authorize self.client.credentials(HTTP_AUTHORIZATION = resp_login.data.get("jwt")) To retrieve the username from the token, I use the following code: def get_payload(request): token = request.META.get('HTTP_AUTHORIZATION') if not token: raise AuthenticationFailed('Unauthenticated!') try: payload = jwt.decode(token, 'secret', options={"verify_signature": False}, algorithms=['HS512']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated!') return payload However, I get the payload as follows: {'username': '', 'exp': 1691987384, 'iat': 1691983784} -
Problem with Django app - ERROR - models - HTTPSConnectionPool(host='www.googleapis.com', port=443): Read timed out. (read timeout=2)
I have part of the application for getting location over Google geolocate APIs. I'm trying to execute this part of code: try: if self.rssi_vector_data and not self.rssi_coords and settings.GOOGLE_LOCATION_API_KEY and not self.rssi_coords_failed: json_data = json.dumps(self.rssi_vector_data) response = requests.post('https://www.googleapis.com/geolocation/v1/geolocate?key=APIKEY', data=json_data, timeout=2) if response.status_code == 200: response_json = response.json() if response_json.get('location'): coords = response_json.get('location') self.rssi_coords = Point(coords.get('lng'), coords.get('lat'), srid=SRID_FORMAT) self.rssi_coords_failed = False self.save(update_fields=('rssi_coords', 'rssi_coords_failed')) return self.rssi_coords_failed else: self.rssi_coords_failed = True self.save(update_fields=('rssi_coords_failed')) return self.rssi_coords except Exception as e: logger.error(str(e)) But I'm getting this error: ERROR - models - HTTPSConnectionPool(host='www.googleapis.com', port=443): Read timed out. (read timeout=2) I tried to write another script with fixed values: import requests import json url = "https://www.googleapis.com/geolocation/v1/geolocate?key=APIKEY" headers = { "Content-Type": "application/json" } data = { "event_type": "rssi_vector", "timestamp": "2023-03-03T16:42:42+00:00", "payload": { "rssi_vector_data": { "considerIp": "false", "radioType": "lte", "cellTowers": [ { "cellId": 0, "mobileCountryCode": 0, "mobileNetworkCode": 0, "signalStrength": 0 } ], "wifiAccessPoints": [ { "macAddress": "E0:23:FF:11:41:90", "signalStrength": -93, "signalToNoiseRatio": 0 }, { "macAddress": "E0:23:FF:11:41:91", "signalStrength": -94, "signalToNoiseRatio": 0 } ] } } } try: response = requests.post(url, headers=headers, data=json.dumps(data), timeout=2) response.raise_for_status() except requests.exceptions.Timeout: print("Expired.") except requests.exceptions.RequestException as e: print("Error:", e) else: response_data = response.json() print(response_data) And it works. Thank you for help! I tried with several python versions and … -
Reverse for 'customuser-detail' with keyword arguments '{'pk': 3}' not found
New user to Django, followed the basics for the DRF quick start. The main thing that I wanted to try was to make a custom user to not depend on the base model and add my custom fields to it. I did it and this is what I have: custom_user.py from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models from django.utils.translation import gettext as _ from rest_framework import serializers from snorlax.managers.custom_user_manager import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): """Custom user to override default user.""" email = models.EmailField(_("email address"), unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_by = models.ForeignKey( "CustomUser", on_delete=models.PROTECT, null=True, db_column="created_by", default=serializers.CurrentUserDefault, related_name="%(class)s_created_by", ) created_datetime = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey( "CustomUser", on_delete=models.PROTECT, null=True, db_column="updated_by", default=serializers.CurrentUserDefault, related_name="%(class)s_updated_by", ) updated_datetime = models.DateTimeField(auto_now=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ("password",) objects = CustomUserManager() class Meta: """Define additional attributes.""" db_table = "users" user_view.py from typing import Self from rest_framework import permissions, viewsets from rest_framework.serializers import Serializer from snorlax.models import CustomUser from snorlax.serializers.user_serializer import UserSerializer class UserViewSet(viewsets.ModelViewSet): """API endpoint that allows users to be viewed or edited.""" queryset = CustomUser.objects.all().order_by("-id") serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] lookup_field = 'id' def perform_update(self: Self, serializer: Serializer) -> None: """ Update the model using the provider serializer.. … -
Unable to create account
I have two models in two different apps, the first model is a custom user model, from abstractbaseuser class, called users and the second model is called wallet the wallet model has a field account which is a foreign key to the users model.This is my problem I want to automatically create a wallet for every newly registered user but after I use this code from django.db.models.signals import post_save from django.dispatch.dispatcher import receiver from .models import Users from userwallets.models import Wallet @receiver(post_save, sender=Users) def create_wallet(sender, created, instance, *args, **kwargs): if created: Wallet.objects.create(owner=instance) I can only create one user then when I try to register another user it says unable to create account please what I'm doing wrong. fyi: I'm using djoser for user registration but a customized one I've tried anything possible no results -
Image Caption with python
I would like to ask for help on the procedure that I must follow to create a program that generates image subtitles, I have been reading about tensorflow and VGG16, but I am not sure what to do, first create a model or automatically generate the image subtitle and save it in a txt? I would appreciate the help I have seen repositories where they only load VGG16 and tensorflow, as well as an .h5 model but I can't understand what this document would have, they also load txt files with image descriptions -
I'm have a variable Topic to a foreign key that produces this error: NameError: name 'Topic' is not defined
I'm working on a django project where I have created a project and an app. In models.py I have two classes: Topic and Entry. When I try to runserver I get an error NameError Topic is not defined. from django.db import models # Create your models here. class Lesson(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the mocel""" return self.text class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) I have tried to migrate and makemigration courses the name of the app. I have rewritten the code and checked for indentation. I'm following the code in a text called Python Crash Course to the letter. At one point my code was working but now I'm getting NameError: name 'Topic' is not defined. But when I do python manage.py runserver 8000 I keep getting the error. -
Django script.js file
I am working on a django project and import javscript code from a script.js file. I am attempting to run a class and am getting a reference error. In the script.js file class RWT { constructor(r, w, t) { this.r = r; this.w = w; this.t = t; } console_r() { console.log(this.r) } }; function test_func() { console.log("this works") } function my_func() { test_func() let new_rwt = new RWT("r", "w", "t") new_rwt.console_r() } In my html file, I have an input that calls my_func(). page.html <body> <input value="a" onclick="my_func()"> <script src="{% static 'js/script.js' %}"></script> </body> I get the error: Uncaught ReferenceError: Cannot access 'RWT' before initialization What am I doing wrong here? -
Django giving error when trying to get path to static file
I'm trying to implement xhtml2pdf, and in my html file, it references a static file. I have the file in my project at jobs/static/jobs/style.css. When using the code xhtml2pdf provides in their docs, I am getting an error when it gets to result = finders.find(uri) saying django.core.exceptions.SuspiciousFileOperation: The joined path (/static/jobs/css/style.css) is located outside of the base path component (/opt/project/myproject/static). If I navigate to the url that the file should be at, http://127.0.0.1:8000/static/jobs/css/style.css, I see the code of the css file, so it is in the generally correct location. This project is being served in a docker container, and there is nothing stored in /opt, so I don't know why it coming up with this "base path component" at (/opt/project/myproject/static). I don't know where it is getting this path. I have searched my entire project, and there is no path, in any file, that includes opt or project. The project is stored in /app in the container. Here is the code I got from their site: from xhtml2pdf import pisa from django.template.loader import get_template from django.http import HttpResponse from django.conf import settings import os import io from django.contrib.staticfiles import finders def link_callback(uri, rel): """ Convert HTML URIs to absolute system … -
Modifying request contents in DRF
As far as I know request objects are immutable and it's bad practice to modify request through closed attributes like request._body or request._data. And since it described everywhere as bad practice, I'm lack of details to understand why it's should be avoided. What is the best approach to dynamically change request (for example if we need to decode value in request.body). As I alternative I can imagine custom Serializer with custom decode serializer.Field but maybe there's more clever solution? Thank you in advance! -
Django Ajax The likes I push disappear when I refresh the page
I implemented the Like function in Django Ajax, but when I refresh the page, the Likes I have pushed disappear. Why? I thought there was a problem with body: post_pk={{ post.pk }}` and looked into it, but could not figure it out. models.py from django.db import models from accounts.models import CustomUser class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ["-created_at"] class Like(models.Model): user_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE) target = models.ForeignKey(Post, on_delete=models.CASCADE) views.py class DeletePost(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post template_name = 'delete.html' success_url = reverse_lazy('home') def test_func(self, **kwargs): pk = self.kwargs['pk'] post = Post.objects.get(pk=pk) return (post.user == self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) like_count = self.object.like_set.count() context['like_count'] = like_count if self.object.like_set.filter(user_id=self.request.user).exists(): context['is_user_liked'] = True else: context['is_user_liked'] = False return context def like(request): post_pk = request.POST.get('post_pk') context = {'user_id': f'{ request.user }'} article = get_object_or_404(Post, pk=post_pk) like = Like.objects.filter(target=article, user_id=request.user) if like.exists(): like.delete() context['method'] = 'delete' else: like.create(target=article, user_id=request.user) context['method'] = 'create' context['like_count'] = article.like_set.count() return JsonResponse(context) detail.html {% extends "base.html" %} {% load static %} {% block title %}{% endblock %} {% block content %} <div class="container"> <div class="alert alert-success" role="alert"> <p>タイトル:{{object.title}}</p> <p>投稿者:{{object.user}}</p> <p>コメント:{{object.content|safe}}</p> …