Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save data in django models taken from bootstrap form?
I'm new in Django and now I'm working on my first project. I created model 'nom' to store data and also bootstrap form in html temlplate. My question is how can I save data in my model after clicking submit button in my form in html. All answers i have found recommended me to create Form as class. Is any easy way to use data from my form? Thanks home.html <!DOCTYPE html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>Title</title> <style> body { margin: 40px } .my-container { border: 1px solid green} .my-row { border: 2px solid blue} .my-col { border: 2px solid red} btn-primary { margin-left: 50px} .align-right { text-align: center; border: 0; } </style> </head> <body> <div class="container my-container"> <form action="{% url 'home' %}" method="Post"> {% csrf_token %} <div class= "row my-row"> <div class="col-3 my-col"> <input type="number" placeholder="0" name="nom200" size="1" /> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if liczba %} {{ liczba }} {% endif %} </span></h3> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if ls %} {{ ls }} {% endif %} </span></h3> </div> </div> <div class= "row my-row"> <div class="col-3 my-col"> <input type="number" placeholder="0" name="nom100" size="1" /> </div> <div class="col my-col"> <h3><span … -
django-elasticsearch-dsl-drf with JSONfield
I'm using django-elasticsearch-dsl-drf package and I have Postgres jsonField which I want to index. I tried to use Nestedfield in the document but without any properties since the json field is arbitrary, But I'm not able to search on that field, and I don't see anything related to that on their documentation. Any idea how can I achieve this? -
Python Django Templates ( For Loops ) add always 2 elements to a div
Hi guys i want to add always 2 elements to a new div container in a django template. has anyone a solution wich works? :D my code is this in the template... <center> <div class="groups-container"> {% for group in featured_groups %} {% if forloop.counter|divisibleby:2 %} <center> <div class="row"> {% endif %} <div class="col-sm-6"> <div class="card"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a class="btn btn-success" href="/groups/join/{{ group.uuid }}">Beitreten <i class="fab fa-{{ group.type }}" aria-hidden="true"></i></a> </li> <li class="nav-item"> <a class="btn btn-primary" href="/groups/info/{{ group.uuid }}">Mehr</a> </li> </ul> <div class="group-category">Kategorie: {{ group.category }}</div> </div> <div class="card-body"> <h5 class="card-title">{{ group.name }}</h5> </div> <div class="card-body"> <p class="card-text">{{ group.short_description }}</p> </div> </div> </div> {% if forloop.counter|divisibleby:3 %} </div> </center> {% endif %} {% endfor %} </div> But the result is wrong :D its like this at the end <center> <div class="groups-container"> <div class="col-sm-6"> <div class="card"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a class="btn btn-success" href="/groups/join/uuid.randomv4">Beitreten <i class="fab fa-whatsapp" aria-hidden="true"></i></a> </li> <li class="nav-item"> <a class="btn btn-primary" href="/groups/info/uuid.randomv4">Mehr</a> </li> </ul> <div class="group-category">Kategorie: 18+</div> </div> <div class="card-body"> <h5 class="card-title">Tolle gruppe</h5> </div> <div class="card-body"> <p class="card-text">Meine tolle Gruppe</p> </div> </div> </div> <center> <div class="row"> <div class="col-sm-6"> <div class="card"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a … -
Getting a response.POST from on click Google Charts to update a Django view
This type of question has been asked several times before on SO, but I can't seem to find a correct answer for my situation. I want to sent a variable from a Google Charts Library to a Django view, I want to use this variable to update my Django Model and View to set initial values in a form and remove a record from a model. and sent it back to my HTML template to render again. I have the following Model form defined in forms.py class PlanningForm(ModelForm): class Meta: model = Planning fields = [ 'persoon', 'project', 'projecttaak', 'datum', 'begintijd', 'eindtijd', 'status', ] widgets = {'datum':DateInput(), 'begintijd':TimeInput(),'eindtijd':TimeInput()} When the form is submitted it adds a new record to the Model I use the Model to draw a Google Charts timeline as following: in views.py def planning(response, persoon, jaar, maand, dag): datum = datetime.date(jaar, maand, dag) persoon = Persoon.objects.get(id=persoon) planning = Planning.objects.all() #filter(datum=datum) planning_form = PlanningForm() planning_form = PlanningForm(initial={'persoon': persoon, 'status':'Actief'}) planning_form.fields['datum'].initial = (str(jaar)+"-"+str(maand)+"-"+str(dag)) planning_form.fields['persoon'].widget = forms.HiddenInput() planning_form.fields['status'].widget = forms.HiddenInput() planning_form.fields['datum'].widget = forms.HiddenInput() if response.method == 'POST': if 'save' in response.POST: planning_form = PlanningForm(response.POST) planning_form.save() #https://docs.djangoproject.com/en/3.1/ref/forms/api/#django.forms.Form.cleaned_data cleaned_data = planning_form.cleaned_data planning_form = PlanningForm(initial={'persoon': persoon, 'status':'Actief'}) planning_form.fields['datum'].initial = (str(jaar)+"-"+str(maand)+"-"+str(dag)) planning_form.fields['persoon'].widget = forms.HiddenInput() … -
Using the object in DetailView
Lets say i have a model named City, which has a name attribute. In my DetailView i want to use that name of the specific city it was clicked on to make some api requests and then send it to the detailview.html. Is there a way to access it? -
How to set up my Django view to GET an external API
trying to set up my Django Rest View to properly pass an external API call. class BucketData(APIView): permission_classes = [IsAuthenticated] def get(self, request, *args, **kwargs): external_api_url = "http://localhost:3000/security?select=symbol,company" res = urllib.urlopen(external_api_url).read() data = json.loads(res) print(data) return Response(data, status=HTTP_200_OK) This doesn't seem to work and I get a: { "detail": "Not found." } error when I test out the URL: api url: urlpatterns = [ path('bucket-data/', BucketData.as_view(), name='bucket-data') ] The localhost:3000 API works, I've tested it using curl, and as well using django shell using the requests library. Also, the data avaiable through localhost:3000 is already packaged in JSON. How can I solve my error? Been trying to for a couple of days and I don't think I'm close. -
It there a way to render a partial(div) only in django and then return a html json reponse
I'm looking for a way to return a JSON response for HTML div located on Django partial template. All I want to update a div section, not the entire HTML page. Similarly to the Laravel PHP framework, they are doing this for rendering the view: if ($request->ajax()) { return \Response::json(\View::make('partial_users_table', array('users' => $users))->render()); } return view('users.index', array('users' => $users)); and in javascript: $.ajax({ url : '/users', dataType: 'json', }).done(function (data) { $('.ajax-box').html(data); location.hash = page; }).fail(function (xhr) { alert('List could not be loaded.'); }); This is what I have tried for far views.py if request.is_ajax: return render(request, 'auth_app/users.html', {'users':users}) return render(request, 'auth_app/users.html', { 'users': users }) and I'm getting just a table without the full page. -
Django not able to load static file
I am trying to make a paint web app in django. My settings.py STATIC_ROOT = '' STATIC_URL = '/static/' When i try the above The project shows no errors . But my project is not able to load the css and javascript file in static folder. If the add static file finders STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) It gives following error raise ImproperlyConfigured("The storage backend of the " django.core.exceptions.ImproperlyConfigured: The storage backend of the staticfiles finder <class 'django.contrib.staticfiles.finders.DefaultStorageFinder'> doesn't have a valid location. -
Unable to intercept 404 error by mail in production (debug=False)
I try to configure django app to receive trace of error (404 and 500) when my app will be in production. I've read Django documentation and configure settings accordingly. I generate 404 error in my code, but receive no email with settings below. ADMINS = [('John', 'john@example.com'), ] MANAGERS = [('John', 'john@example.com'), ] SEND_BROKEN_LINK_EMAILS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' LOGGING = { 'version': 1, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, } }, } -
Can Import Dash from dash
I am working on a django_plotly_dash project. However, after I installed the django_plotly_dash, the django setting shows an error: lib\site-pakages\django_plotly_dash\dash_wrapper.py can't load Dash from dash. I have the dash package installed. I tried to use a python shell and have no problem from dash import Dash. It appears that somehow the lib\site-pakages\django_plotly_dash\dash_wrapper.py can't import Dash only. -
contact form developed in html css and run in django and i got these much error what is the solution ?? I am a amateur trying to learn from youtube
"GET / HTTP/1.1" 200 1938 Not Found: /contactform.css "GET /contactform.css HTTP/1.1" 404 1978 Not Found: /favicon.ico "GET /favicon.ico HTTP/1.1" 404 1966 Forbidden (CSRF cookie not set.): / "POST / HTTP/1.1" 403 2864 "GET / HTTP/1.1" 200 1938 Not Found: /contactform.css "GET /contactform.css HTTP/1.1" 404 1978 List item -
django channels race condition
I'm using django channels to handle websocket connections. If two clients send two messages at the same time I get a race condition using channel's WebsocketConsumer. I'm assuming this happens because every connection to this consumer starts its own thread which is then handled in parallel with the other ones. So I thought I'd switch to AsyncWebsocketConsumer. I put async, await, database_sync_to_async and so on where necessary and everything works, but the race condition issue persists. I thought by using AsyncWebsocketConsumer, every connection would be handled in the same thread and calling async def receive(...) would block the thread so that every received message gets handled in sequence. What am I doing wrong? -
'Connection refused' when running django/postgres project in docker
I'm working on a Django/Postgres project and currently trying to dockerize. Postgresql has always worked fine on my pc, but now I'm having trouble spinning it up on docker. I get this error: web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I've tried a lot of solutions suggested online, but none have solved my problem. Here's all the relevant code: .yml file version: '3.8' services: web: build: context: ./web network: host command: python manage.py runserver 0.0.0.0:8000 volumes: - ./web/:/usr/src/web/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - web_db web_db: image: postgres:12.5-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=username - POSTGRES_PASSWORD=password - POSTGRES_DB=database volumes: postgres_data: env file SECRET_KEY=secret DEBUG=1 DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql_psycopg2 SQL_DATABASE=db_name SQL_USER=username SQL_PASSWORD=password SQL_HOST=localhost SQL_PORT=5432 settings.py DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.postgresql_psycopg2"), "NAME": os.environ.get("SQL_DATABASE", "db_name"), "USER": os.environ.get("SQL_USER", "username"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", ""), } } And here are my configs: sudo nano /var/lib/docker/volumes/project_postgres_data/_data/pg_hba.conf #TYPE DATABASE USER ADDRESS METHOD local all all trust #IPv4 local connections: host all all 127.0.0.1/32 trust #IPv6 local connections: host all all ::1/128 trust local replication all trust host replication all 127.0.0.1/32 … -
How to create views to download mulitple files?(Django)
I want to create views to download multiple files. This view downloads a single file. def submit(request): # converts files and make new output files. paths = [# list of files] base_names = [os.path.basename(path) for path in paths] path = paths[0] # paths, path both are in context def download(request): path = request.GET.get('path') base_name1 = os.path.basename(path) context = {'path': path, 'base_name1': base_name1} with open(path, 'rb') as fh: response = HttpResponse(fh.read()) response['Content-Disposition'] = 'inline; filename='+base_name1 return response The following template downloads a single file that is in the paths list. I want to create a template view that lists all the files in the paths list and download them. Any ideas or suggestions for this. template code: <p>You have successfully converted the file. </p> <p>Code : {{ code }} </p> #values returned from context <p>Number : {{ number }}</p> #values returned from context <p> <a href ="{% url 'download' %}?path={{ path|urlencode }} " download>{{ base_name }} </a> </p> -
unable to authenticate my django application urls
I am new to Django, I am trying to use jwt for my rest-framework API using djano simple jwt, I have an application named data_table which is having some defined urls in its urls.py as below. router = DefaultRouter() router.register('op' , views.op_ViewSet , basename='op-api') router.register('org' , views.org_ViewSet , basename='org') .... .... .... urlpatterns =router.urls as an example, my org serializer, its model and view looks like below, I am using permission_class inside my view. class Organization(models.Model): name = models.CharField(unique=True , max_length=200) class Meta: db_table = "organization" def __str__(self): return self.name class organization_Serializer(serializers.ModelSerializer) : class Meta : model = Organization fields = ['id' , 'name'] class org_ViewSet(viewsets.ModelViewSet) : serializer_class = organization_Serializer permission_classes = [IsAuthenticated] def get_queryset(self) : all_org = Organization.objects.all() return all_org I have registered this application url in the main urls.py as below, it is the main application urlpatterns. urlpatterns = [ ..... path('op-api/', include('data_table.urls')) ] my rest-framework settings is like this. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'NON_FIELD_ERRORS_KEY': 'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } the main problem is that http://127.0.0.1:8000/op-api/ ask me to provide token instead of http://127.0.0.1:8000/op-api/org/ if I provide a token to http://127.0.0.1:8000/op-api/ it gets authenticate, and as response it shows all the urls present in … -
Embedded BPMN editor needs a working download button with django
Currently I have a HTML Page which is embedding a BPMN Modeler via https://bpmn.io/. They way it works is that I've an empty .bpmn file in my media directory and everytime I visit my page e.g. it loads the empty .bpmn file and the user is free to model his own diagram from there. Now I'd like for the user to be able to download his .bpmn file which he created on the page. I've never worked with JS and Django before. I don't really know how to pass my modified .bpmn diagram back to my django view downlad function. Let me show the code I've so far, starting with the bpmn.io script which enables the user to work with the diagram(modeler.html): <link rel="stylesheet" href="https://unpkg.com/bpmn-js@8.0.0/dist/assets/diagram-js.css"/> <link rel="stylesheet" href="https://unpkg.com/bpmn-js@8.0.0/dist/assets/bpmn-font/css/bpmn.css"/> <script src="https://unpkg.com/bpmn-js@8.0.0/dist/bpmn-modeler.development.js"></script> <script> function fetchDiagram(url) { return fetch(url).then(response => response.text()); } var bpmnJS = new BpmnJS({ container: '#canvas', width: '100%', height: '600px', }); async function openDiagram() { const diagram = await fetchDiagram('static/bpmn/empty_bpmn.bpmn'); try { await bpmnJS.importXML(diagram); viewer.get('canvas').zoom('fit-viewport'); } catch (err) { console.error('something went wrong:', err); } } openDiagram(); </script> and the belonging view functions to this(views.py): def modeler(request): return render(request, 'core/modeler.html') def download_bpmn(request): response = HttpResponse(content_type='application/bpmn') response['Content-Disposition'] = 'attachment; filename="your_diagram.bpmn"' return response … -
Function not executing but celery is working
the auto_sms function is working when executed manually on views.py but then I tried to call/do it on tasks.py but its not working. what might be I'm missing here? Thanks! Configuration -> . broker -> redis://:******************************// . loader -> celery.loaders.app.AppLoader . scheduler -> django_celery_beat.schedulers.DatabaseScheduler . logfile -> [stderr]@%INFO . maxinterval -> 5.00 seconds (5s) [2021-01-10 23:50:55,743: INFO/MainProcess] beat: Starting... [2021-01-10 23:50:55,787: INFO/MainProcess] DatabaseScheduler: Schedule changed. [2021-01-10 23:51:27,004: INFO/MainProcess] Scheduler: Sending due task scheduled_task (app1.tasks.auto_sms) [2021-01-10 23:51:55,787: INFO/MainProcess] Scheduler: Sending due task scheduled_task (app1.tasks.auto_sms) [2021-01-10 23:52:25,790: INFO/MainProcess] Scheduler: Sending due task scheduled_task (app1.tasks.auto_sms) @tasks.py from celery import shared_task from app1.views import send_sms from datetime import timedelta from django.http import HttpResponse from django.utils.timezone import now from app1.models import Rainfall @shared_task(name="auto_sms") def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', timestamp__gt=now() - timedelta(days=1), ) count = responses.count() if not (count % 10) and count > 0: send_sms(request) return HttpResponse(200) @settings.py CELERY_BEAT_SCHEDULE = { "scheduled_task": { "task": "app1.tasks.auto_sms", "schedule": 30.0, } } -
Is there any way to Protect Django rest api on Ecommerce
I'm planning to develop REST api using django rest framework and just had a thought about the data security. In Ecommerce websites how can I use something similar to auth token? is there anyway to secure app from Hackers? -
Submitting form in a modal pop-up with Django
I have a problem with submitting a delete form in a modal pop-up with Django class based views. I have a table with objects and each objects has a delete button and this button is linked-in with the modal form. When I click the delete button the modal is opening with the form and on the url is sent the object id in order to delete that object. In my class based view I set the template just the modal form and I included the modal form with the {% include %} in my template from where I acces the modal, the form is not submitting because the object is not deleted after I submit the form and I have some context variables and they aren't displayed on the form. Any help please? My class based view class IncomeDeleteView(DeleteView): model = Income template_name = 'users/delete.html' success_url = reverse_lazy('income') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object_name'] = 'Income' return context def test_func(self): income = self.get_object() if self.request.user == income.author: return True return False my delete.html template <div class="modal fade" id="deleteIncomeModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <form method="POST"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete a Income?</h5> … -
DecimalField in Django UpdateView Raising Validation Error
I have the following in my models.py class Coil(Product): ... cw1 = models.DecimalField(default = 0, null=True, blank=True, decimal_places=3, max_digits=6) cw2 = models.DecimalField(default = 0, null=True, blank=True, decimal_places=3, max_digits=6) cw3 = models.DecimalField(default = 0, null=True, blank=True, decimal_places=3, max_digits=6) I used a function to fill those fields and it worked just fine, now I'm trying to use Django's UpdateView to update those fields when needed, and it raises an error concerning the decimal_places constraint, even if I type something like 0.2 My forms.py looks like this: class CoilForm(forms.ModelForm): class Meta: model = Coil fields = [ "cw1", "cw2", "cw3",] cw1 = forms.FloatField(label="Poids Contôle 1", required=False, widget=forms.TextInput( attrs={ "class": "form-control", "type": "number", } )) cw2 = forms.FloatField(label="Poids Contôle 2", required=False, widget=forms.TextInput( attrs={ "class": "form-control", "type": "number", } )) cw3 = forms.FloatField(label="Poids Contôle 3", required=False, widget=forms.TextInput( attrs={ "class": "form-control", "type": "number", } )) And my views.py looks like this : class CoilUpdateView(UpdateView): template_name = 'production/update_coil.html' form_class = CoilForm success_url = reverse_lazy('production:coil-consulting') @method_decorator(login_required(login_url=reverse_lazy('login'))) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["form_name"] = 'Update Coil' return context def get_object(self): _ref = self.kwargs.get('ref') return get_object_or_404(Coil, ref=_ref) It worked fine with FloatField's, the only problem are DecimalFields... Thank you in advance for … -
Django Model class dynamic field creation
I am trying to create a model form in which m asking for the number of items. once i get the number, there should be that exact number of fields to be filled. How can i do that? class Create_Poll(models.Model): heading = models.CharField("Question", max_length=150,blank=False) items = models.IntegerField("Number of Items",blank=False) i = 0 for i in range(1,items): item = models.CharField("item{i}".format(i=i),max_length=100,blank=False) img = models.ImageField("image{i}".format(i=i),upload_to="pics") How can i use the data from the 'items' field??? please help -
Django loaddata - instance is on database "postgres", value is on database "default"
I need to migrate from sqlite3 to postgres. The dumpdata of the whole database doesn't work so I'm doing it one by one. The problem is that when I try to load users it raises error: ValueError: Problem installing fixture '/.../dbmig/auth.user.json': Could not load auth.User(pk=1): Cannot add "<Group: contractor>": instance is on database "postgres", value is on database "default" This is not true, because the groups were migrated before users. I've created a command that I use: def dumpload(model): json_filename = model+'.json' DBMIG_DIR = os.path.join(settings.BASE_DIR, 'dbmig') json_filepath = os.path.join(DBMIG_DIR,json_filename) with open(json_filepath, 'w') as f: call_command('dumpdata', model, stdout=f, database='default') call_command('loaddata', json_filepath, database='postgres') class Command(BaseCommand): def handle(self, *args, **options): dumpload('auth.group') dumpload('auth.user') -
incorrect padding in django/admin
Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.1.3 Exception Type: Error Exception Value: Incorrect padding Exception Location: C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\base64.py, line 87, in b64decode Python Executable: C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 Python Path: ['D:\Django\django-ecommerce-master', 'C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Lenovo\AppData\Local\Programs\Python\Python39', 'C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Sun, 10 Jan 2021 15:21:22 +0000 why this incorrect padding please give me a solution -
Edit item directly on model click in Django Admin
So, I'm making a really simple website with a following structure: Home page (one page) Services (one page) About (one page) Contacts (one page) So far I have 1 app, 4 models and in Django Admin the structure is following: App name -> Model -> Item -> Editor All I want to do is to skip step 3 in this structure in Django Admin, so when click on Home page I can directly go to edit my Home page. Now I have to click two times, because there is only one unique Item in Home page model, the Home page itself. Basically, if I have only one item in Model (or SQL table), how do I skip the list of items in Django Admin and directly edit the item? There are a few solutions, but they are more like patches: I can rename the item "Edit", but it is quite strange, because then I have to click edit two times. I can create one table (and one model) for all pages, but then it will have like 40-50 columns, also not a good solution. Thanks. -
Django Class based views for DELETE method cannot redirect to ListView
I'm using django 3.1 and class based views. When I send a request that is METHOD_OVERRIDE with DELETE and using POST, it is correctly sent to the delete view I setup. @method_decorator(login_required, name="dispatch") class ServerDetail(DeleteView): # form_class = ServerCreateForm model = Server # template_name = "core/server/create.html" success_url = reverse_lazy("servers-list") def get_success_url(self): if self.success_url: return self.success_url else: raise ImproperlyConfigured("No URL to redirect to. Provide a success_url.") def delete(self, request, *args, **kwargs): user = self.request.user social_token = SocialToken.objects.filter( account__user=user, account__provider="digitalocean" ).first() droplet_id = kwargs["pk"] droplet = digitalocean.Droplet(id=droplet_id, token=social_token.token) droplet.destroy() success_url = self.get_success_url() return redirect(success_url) def post(self, request, *args, **kwargs): return self.delete(request, *args, **kwargs) But it will fail as at the redirect to /servers/ there will be a 405 Method Not Allowed error. However, if I sent a regular POST method to /servers/:id/delete and setup the urls accordingly, the redirection is fine. So basically I cannot use DELETE when I used class based views yes?