홈>
Django 앱의 데이터베이스에서 객체를 삭제하려고합니다.
아이디어는 html 파일에서 기본을 가져 와서 양식에 게시하는 것입니다. 삭제 요청을 올바른 방법으로 게시하기 위해 기본 키를 전달하는 방법을 이해하지 못합니다.
클래스 기반 뷰 DeleteView에 대해 찾은 모든 것에 갔다. 스택 오버 플로우, 장고 문서 및 기타 소스 모두에서 이것이 어떻게 작동하는지 파악하지 못했습니다.
예 : 장고 삭제 파일 필드
Django 모델에서 레코드를 삭제하는 방법?
Python Django는 현재 객체를 삭제합니다
Django 모델에서 레코드를 삭제하는 방법?
https://docs.djangoproject.com/en/2.2/ 토픽/db/queries/
https://docs.djangoproject.com/en/2.2/ref/class-based-views/generic-editing/#django.views.generic.edit.DeleteView
코드의 주요 스 니펫 아래에 필요한 정보가 없으면 알려주세요.
views.py
class SelectFileDelView(TemplateView):
"""
This view is used to select a file from the list of files in the server.
After the selection, it will send the file to the server.
The server will then delete the file.
"""
template_name = 'select_file_deletion.html'
parser_classes = FormParser
queryset = FileModel.objects.all()
def get_context_data(self, **kwargs):
"""
This function is used to render the list of files in the MEDIA_ROOT in the html template
and to get the pk (primary key) of each file.
"""
context = super().get_context_data(**kwargs)
media_path = settings.MEDIA_ROOT
myfiles = [f for f in listdir(media_path) if isfile(join(media_path, f))]
pk_list = []
for value in myfiles:
pk = FileModel.objects.filter(file=value).values_list('pk', flat=True)
pk_list.append(pk)
file_and_pk = zip(myfiles, pk_list)
context['filename'] = file_and_pk
return context
class FileDeleteView(DeleteView):
"""
This class contains the method to delete a file interacting directly with the API.
DELETE requests are accepted.
"""
model = FileModel
fields = ['file']
template_name = 'delete_success.html'
success_url = '/delete_success/'
def post(self, request):
"""
This method is used to making predictions on audio files
loaded with FileView.post
"""
pk = request.POST.getlist('pk').pop()
try:
return Response(pk, status=status.HTTP_200_OK)
except ValueError as err:
return Response(str(err), status=status.HTTP_400_BAD_REQUEST)
select_file_deletion.html
{% extends "index.html" %}
{% block content %}
<form action="/App/delete/" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<h5>Please select one file at a time from the list below to delete it from the server.</h5>
{% for myfile, pk in filename %}
<p>Are you sure you want to delete "{{ myfile }}"?</p>
<input type="submit" value="Confirm">
<input type="hidden" name="pk" value="{{ pk }}">
<br>
{% endfor %}
<br>
</form>
{% endblock %}
urls.py
urlpatterns = [
# Url to select a file to be deleted and confirm the upload
url('filedelete/', SelectFileDelView.as_view(), name='file_delete'),
url('delete_success/(?P<pk>\d+)/$', FileDeleteView.as_view(), name='delete_success'),
]
models.py
"""
Models.py includes the database structure of the application.
"""
from django.db import models
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_delete
class FileModel(models.Model):
file = models.FileField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
path = models.FilePathField(path=settings.MEDIA_ROOT, default=settings.MEDIA_ROOT)
@receiver(post_delete, sender=FileModel)
def submission_delete(sender, instance, **kwargs):
"""
This function is used to delete attachments when a file object is deleted.
Django does not do this automatically.
"""
instance.file.delete(False)
오류:
IndexError at /App/delete/
pop from empty list
Request Method: POST
Request URL: http://127.0.0.1:8000/App/delete/
Django Version: 2.2.4
Exception Type: IndexError
Exception Value:
pop from empty list
Exception Location: /Users/marcogdepinto/PycharmProjects/DjangoRestDeepLearning/App/views.py in post, line 131
Python Executable: /Users/marcogdepinto/anaconda3/bin/python
Python Version: 3.6.9
UPDATE1: HTML이 아래와 같이 변경되었습니다
<input type="hidden" name="pk" value="{{ pk }}">
이 작업을 수행하면
AssertionError at /App/delete/
.accepted_renderer not set on Response
아래의 전체 역 추적 :
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/App/delete/
Django Version: 2.2.4
Python Version: 3.6.9
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'App',
'debug_toolbar']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback:
File "/Users/marcogdepinto/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/marcogdepinto/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
145. response = self.process_exception_by_middleware(e, request)
File "/Users/marcogdepinto/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
143. response = response.render()
File "/Users/marcogdepinto/anaconda3/lib/python3.6/site-packages/django/template/response.py" in render
106. self.content = self.rendered_content
File "/Users/marcogdepinto/anaconda3/lib/python3.6/site-packages/rest_framework/response.py" in rendered_content
55. assert renderer, ".accepted_renderer not set on Response"
Exception Type: AssertionError at /App/delete/
Exception Value: .accepted_renderer not set on Response
- 답변 # 1
관련 자료
- Django가 기본 빈 URL을 설정했습니다
- JsonResponse를 사용하여 Django 일반 DeleteView 확인 페이지에 오류 메시지를 보내는 방법
- python - Django REST 프레임 워크 API 루트 비어 있음
- 장고 - 빈 슬러그를 고치는 방법?
- 메서드 내에서 Django 리디렉션
- python : 장고 관리자 : JSONField 기본 빈 dict는 관리자에 저장되지 않습니다.
- html - 장고 forloop 내 템플릿에서 배열을 사용하는 방법
- django - queryset이 비어있는 경우 템플릿을 체크인하십시오
- python - Django의 루트 URL에서 빈 응답을 반환하는 방법
- Django Rest Framework의 액션 내에서 페이지를 매기는 방법
- php - Wordpress 위젯 함수에서 변수가 비어 있는지 확인하는 방법
- Django Rest Framework는 빈 JSON을 반환합니다
관련 질문
- python : QuerySet에 중복 인스턴스가 반환되었습니다.
- python : request.data를 빈 사전으로 가져오기
- python : Django 잘못된 자격 증명: 사용자 개체 check_password는 True를 반환하지만 인증 함수는 False를 반환합니다.
- python : 일대다 관계 플라스크
- python : Django REST API를 사용하여 CRUD 작업 수행 시 문제
- python : django에서 일반 숫자를 아라비아 숫자로 변환하는 방법
- Python Django PowerShell 설치 프로그램
- python : django 프로젝트에 sqlite를 설치하는 방법
- python : Django는 이미지를 객체로 React Native FormData 인스턴스로 수신합니다.
- python : Django View의 점심 파이썬 스크립트
request.POST
QueryDict
입니다 양식 입력의 해당 이름/값에 대한 키/값 쌍의 조합문제는 당신이
name
를 추가하는 것을 잊었다는 것입니다 당신의pk
에 입력하면 뷰가request.POST
를 얻을 때 객체,pk
라는 키가 없습니다 ..getlist('arg')
arg
라는 키가 없으면 빈 목록을 반환합니다. 이 발견되고 기본값이 제공되지 않아 오류가 발생합니다.이것은 문제를 해결해야합니다 :
업데이트가져 오는 오류는 원래 문제와 관련이 없으며 새로운 질문으로 생각해야합니다. 즉, 나는 여전히 도움을 줄 것입니다. DRF를 사용한 경험이 없습니다.
문서에 따르면 :
와이즈 비즈또한 :
와이즈 비즈@api_view