Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
urls.py icon doesn't have an image of python on it in PyCharm
urls.py without python emblem Hello. I'm working on Django project in PyCharm enviroment. I have a strange problem. In all of my Django apps urls.py files do not have an emblem of python on their icons. And, I do not have an IDLE support for code. If name of that files is changed, then the file becomes common python script. I cannot understand why this is happening. -
Access related table field value in django template
I am trying to access a Django related field value in a Django template: {% for item in order %} <tr> <td>{{ item.id }}</td> <td class="text-left">{{ item.created }}</td> <td class="text-left">{{ item.payments__charge_status }}</td> <td class="text-left">{{ item.shipping_method_name }}</td> <td class="text-right">£{{ item.total_gross_amount }}</td> </tr> {% endfor %} Actual queryset defined in views.py: orders = Order.objects.values().filter(created__range=(start_date, end_date)).filter(Q(payments__charge_status="fully-charged") | Q(payments__charge_status="not-charged")) Payment is in a different table and I can access using payments__charge_status in the view but not in the actual template. Any help is appreciated. -
Permission denied copping file using shutil.copy on python
i have a little problem during copy files between local folder on docker and a network folder who needs userPassword i tried this code but PermissionError: [Errno 13] Permission denied: '/interfaces/ifrs15/QA/Print_dashboard_1___10-15.PNG' import glob import shutil #ifrs15-img is local on docker for line in glob.glob('ifrs15-img/*.*'): print(line) shutil.copy(line, '/interfaces/ifrs15/QA') #/interfaces/ifrs15/QA its a networkfolder -
Django Admin Changelist_View - Adding extra context based on results list
I needed to add a totals row to Django Admin and used this SO answer for it. admin.py from django.contrib import admin from django.contrib.admin.views.main import ChangeList from .models import Employee_Cost class MyChangeList(ChangeList): def get_results(self, *args, **kwargs): super(MyChangeList, self).get_results(*args, **kwargs) q = self.result_list.aggregate(total_cost=Sum('cost')) self.total_cost = q['total_cost'] class Employee_CostAdmin(admin.ModelAdmin): def get_changelist(self,request): return MyChangeList class Meta: model = Employee_Cost fields = ['project','employee','hours','cost'] list_display = ['project','employee','hours'] Now I'm trying to add a graph following this tutorial: Adding charts to Django admin I'm stuck on the following part: Injecting chart data into admin template . admin.py class MyChangeList(ChangeList): def get_results(self, *args, **kwargs): super(MyChangeList, self).get_results(*args, **kwargs) q = self.result_list.aggregate(total_cost=Sum('cost')) self.total_cost = q['total_cost'] class Employee_CostAdmin(admin.ModelAdmin): def get_changelist(self,request): return MyChangeList def changelist_view(self, request, extra_context=None): super(MyChangeList, self).get_results(*args, **kwargs) q = self.result_list.aggregate(total_planned_hours=Sum('revised_hours')) print(q) class Meta: model = Employee_Cost fields = ['project','employee','hours','cost'] list_display = ['project','employee','hours'] I want to base the extra_context on the changelist_view on the result list I got with get_changelist(). The return myChangeList seems to only return to the template and I tried but failed on passinq "q" to changelist_view. Currently, I got the following error message: super(type, obj): obj must be an instance or subtype of type Also, I tried placing changelist_view under the myChangeList class but nothing … -
How to Create SSO kind of Login from Drupal 7 to Django 3
How to Create SSO kind of Login from Drupal 7 to Django 3? Example: I have SaaS Application which is developed on Drupal 7 (Ex. www.abc.com)and I have created new Application Using Django (Ex. www.xyz.com), both Drupal and Django is using the same MySql DataBase. user will log on to www.abc.com and he will do some operation ex: click the button after clicking on the button, the user will redirect to www.xyz.com, and the user should not ask for any login again because the user already logged in to www.abc.com, Can someone help me how to achieve this? Big Thanks in advance -
DJANGO: filter queryset for foreign key
I need to filter the books associated with my serie model My models.py class Serie(models.Model): serie = models.CharField(max_length = 255) author = models.ForeignKey(Author, on_delete = models.CASCADE, null = True) slug = AutoSlugField(populate_from = 'serie', always_update = True) class Book(models.Model): serie = models.ForeignKey(Serie, on_delete = models.CASCADE, null = True) serie_slug = AutoSlugField(populate_from = 'serie', always_update = True, null = True) book_title = models.CharField(max_length=200) slug = AutoSlugField(populate_from = 'book_title', always_update = True, null = True) resume = RichTextField() pub_date = models.DateTimeField(auto_now_add = True, null = True) My views.py class index(ListView): model = Serie template_name = 'serie_book_list.html' ordering = ['id'] def get_queryset(self, *args, **kwargs): context = super().get_queryset(*args, **kwargs) search = self.request.GET.get('buscar', None) if search: context = context.filter( Q(serie__icontains = search) | Q(author__name__icontains = search) | Q(Book.objects.filter(book_title__icontains = search)) ) return context I tried to use this code Q(Book.objects.filter(book_title__icontains = search)), but without success. Cannot filter against a non-conditional expression. -
Link between original field and translation field
I'm using modelsTranslation library, I want to add ar translation only as I'm using the default value as English. It doesn't make any sense to have name-en because name is in English too. -
Pass python list from context to JS function
I have a view that renders a dictionary of data for each country like below: def InvoicingDashboardView(request): # For reference - "c" is the context dictionary, and it's already initialized by this point for client in Client.objects.all(): fte = frame.fte(c['start_date'], c['end_date'], time = 'external', client = client.id) if fte > 0: c['countrys'][client] = { 'name': client.name, 'fte': fte, 'var_fte': fte - frame.fte(c['var_start_date'], c['var_end_date'], client = client.id), 'daily_ftes': [frame.fte(day, day) for day in c['label_days']], } return render(request, 'dashboards/invoicing.html', context = c) As you can see, for example, if i call {{countrys.client.fte}} i'll get the fte for that client. Everything good till now, but i'll need the daily_ftes for a JS function, like below: <div class="dash_countrys_ftes"> {% for country, items in countrys.items %} <div class="dash_country_block"> {% with name=items.name fte=items.fte variation=items.var_fte flag=country.flag.url %} {% include 'dashboards/charts/country_block.html' %} {% endwith %} </div> <script> countryFteVariation("{{items.daily_ftes|escapejs}}") // HERE </script> {% endfor %} </div> The problem is that daily_ftes is a python list. What can i do here in order to javascript read it as list instead of a string? -
AttributeError running Django site on Mac 11.0.1
I'm getting an error running a django site locally that was working fine before I updated my Mac OS to 11.0.1. I'm thinking this update is the cause of the problem since nothing else was really changed between when it was working and now. 10:15:05 worker.1 | Traceback (most recent call last): 10:15:05 worker.1 | File "/usr/local/bin/celery", line 5, in <module> 10:15:05 worker.1 | from celery.__main__ import main 10:15:05 worker.1 | File "/usr/local/lib/python2.7/site-packages/celery/__init__.py", line 133, in <module> 10:15:05 worker.1 | from celery import five # noqa 10:15:05 worker.1 | File "/usr/local/lib/python2.7/site-packages/celery/five.py", line 20, in <module> 10:15:05 worker.1 | from kombu.five import monotonic 10:15:05 worker.1 | File "/usr/local/lib/python2.7/site-packages/kombu/five.py", line 56, in <module> 10:15:05 worker.1 | absolute_to_nanoseconds = CoreServices.AbsoluteToNanoseconds 10:15:05 worker.1 | File "/usr/local/Cellar/python@2/2.7.17_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 379, in __getattr__ 10:15:05 worker.1 | func = self.__getitem__(name) 10:15:05 worker.1 | File "/usr/local/Cellar/python@2/2.7.17_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 384, in __getitem__ 10:15:05 worker.1 | func = self._FuncPtr((name_or_ordinal, self)) 10:15:05 worker.1 | AttributeError: dlsym(RTLD_DEFAULT, AbsoluteToNanoseconds): symbol not found Here is my brew config HOMEBREW_VERSION: 2.6.0 ORIGIN: https://github.com/Homebrew/brew HEAD: 1d5e354cc2ff048bd7161d95b3fa7f91dc9dd081 Last commit: 2 days ago Core tap ORIGIN: https://github.com/Homebrew/homebrew-core Core tap HEAD: fdb83fcfb482e5ed1f1c3c442a85b99223fcabeb Core tap last commit: 27 hours ago Core tap branch: master HOMEBREW_PREFIX: /usr/local HOMEBREW_CASK_OPTS: [] HOMEBREW_DISPLAY: /private/tmp/com.apple.launchd.rZ1F30XomO/org.macosforge.xquartz:0 HOMEBREW_MAKE_JOBS: 8 … -
django use of quotes in url template tag
Why are quotes needed around users:users in the following: <a href="{% url 'users:users' %}">/users</a> is that a shortcut? in myusers.urls I have set app_name = users. Would the following work? <a href="{% url myusers.views.user %}">/users</a> -
AttributeError: 'Moments' object has no attribute 'date_published'
Well I have these models: class Expression(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) date_published = models.DateTimeField(name='Date Published', default=timezone.now) class Meta: abstract = True class Moments(Expression): content = models.TextField(blank=True) And I have another function or rather view function where i try to access the 'date_published' field of a moments object like this: expression.date_published.strftime("%H:%M %p, %d %B, %Y") and I get this error: AttributeError: 'Moments' object has no attribute 'date_published' even though the date_published field is declared. Please help. -
When i click on page this error is raised Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<blog_id>[0-9]+)$']
blog.html {% block content %} <p>Blog's Title: {{ topic }}</p> <ul> {% for feed in blogs %} <li> <p>{{ feed.date_added|date:'M d,Y H:i' }}</p> <p>{{ feed.note|linebreaks }}</p> </li> {% empty %} <li>There are no Blogs Yet.</li> {% endfor %} </ul> #Here is that Delete blog link. <p>Do you want to delete this Blog?</p> <a href="{% url 'mains:delete' deletej.id %}"> Delete This Blog</a> {% endblock content %} views.py ( This is the view for delete Blog ) def delete(request, blog_id): deletej = get_object_or_404(Blog,id=blog_id) deletej.delete() return HttpResponseRedirect('home') urls.py path('delete/<int:blog_id>',views.delete,name='delete'), When i click on Blog page then this Error ( Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<blog_id>[0-9]+)$'] ) is raised. Please Help me in this. I will really appreciate your Help. -
pymysql.err.IntegrityError: (1048, "Column 'dob' cannot be null")
I am trying to use a datepicker for the date of in my forms, i decided to use he input type date which is supported by most some browsers. i keep getting this error anytime i try to create super user or migrate. I have removed my migrations for the app and added them back with python manage.py makemigrations but the problem still persists. i do not want to wipe out the database, i have tried this with postgres(local) and mysql(production) and the error is the same. This is the traceback error. Traceback (most recent call last): File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/cursors.py", line 163, in execute result = self._query(query) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/cursors.py", line 321, in _query conn.query(q) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 505, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 724, in _read_query_result result.read() File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 1069, in read first_packet = self.connection._read_packet() File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 676, in _read_packet packet.raise_for_error() File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/protocol.py", line 223, in raise_for_error err.raise_mysql_exception(self._data) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.IntegrityError: (1048, "Column 'dob' cannot be null") The above exception was the direct cause of the following exception: Traceback (most recent … -
csrftoken in django rest framework - sending through HTTPIE
I'm trying to login through the http form, from DRF: > https://my.site.io/api-auth/login/ Using httpie, i generate a session.json to get the CSRFToken: $ http --session=why -h https://my.site.io/api-auth/login/ Referrer-Policy: same-origin Server: nginx/1.18.0 Set-Cookie: csrftoken=dT2UuBjp7Xei2iqzmD9A9lNNaTZO8ZHHPh098I8mV27v56E0jePTPgQ0KC3LDmpE; expires=Thu, 02 Dec 2021 15:32:49 GMT; Max-Age=31449600; Path=/; SameSite=Lax Vary: Cookie X-Content-Type-Options: nosniff I use the csrftoken from cookies and : http --session=why -h POST https://my.site.io/api-auth/login/ username=user password=pass X-CSRFToken:dT2UuBjp7Xei2iqzmD9A9lNNaTZO8ZHHPh098I8mV27v56E0jePTPgQ0KC3LDmpE -p Hh This is the out put (With both request and response headers): POST /api-auth/login/ HTTP/1.1 Accept: application/json, */*;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Content-Length: 49 Content-Type: application/json Cookie: csrftoken=dT2UuBjp7Xei2iqzmD9A9lNNaTZO8ZHHPh098I8mV27v56E0jePTPgQ0KC3LDmpE Host: my.site.io User-Agent: HTTPie/2.3.0 csrfmiddlewaretoken: dT2UuBjp7Xei2iqzmD9A9lNNaTZO8ZHHPh098I8mV27v56E0jePTPgQ0KC3LDmpE HTTP/1.1 403 Forbidden Connection: keep-alive Content-Length: 3366 Content-Type: text/html Date: Thu, 03 Dec 2020 15:33:37 GMT Referrer-Policy: same-origin Server: nginx/1.18.0 X-Content-Type-Options: nosniff X-Frame-Options: DENY I tried to use X-CSRFToken instead of csrfmiddlewaretoken I can perform the login through a browser, if a browser is working, i don't see as it can be a problem from the Django Rest Framework configuration. Maybe i'm doing something wrong with httpie What can it be? Thanks in advance. -
Postgres-alpine can not connect to Django project container
I am using CentOS 8 and GitLab ci/cd and I'm trying to deploy a Django project, I don't have any idea why the Django container can not connect to Postgres container, you can see all of the configurations below: .env POSTGRES_DB = somthing POSTGRES_USER = user POSTGRES_PASSWORD = pass POSTGRES_HOST = db POSTGRES_PORT = 5432 .env.db POSTGRES_DB=somthing POSTGRES_USER=user POSTGRES_PASSWORD=pass POSTGRES_PORT = 5432 deploy.sh #!/usr/bin/env bash ssh -o StrictHostKeyChecking=no something@my_ip<< 'ENDSSH' cd some-thing/ docker-compose down git pull https:/user:pass@gitlab.com/neo1992/something.git docker login -u user -p pass registry.gitlab.com docker pull registry.gitlab.com/neo1992/some-thing:latest docker-compose up -d ENDSSH docker-compose version: "3.8" services: api: image: registry.gitlab.com/neo1992/something:latest build: context: . container_name: api command: bash -c 'python manage.py migrate --noinput && python manage.py makemigrations && python manage.py migrate --noinput && python manage.py collectstatic --noinput && gunicorn something.wsgi:application -b 0.0.0.0:8000 --capture-output --log-level=info' volumes: - static_volume:/home/something/some-thing/static - media_volume:/home/something/some-thing/media ports: - "8000:8000" depends_on: - db env_file: .env db: image: postgres:12.0-alpine container_name: db volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.db ports: - "5432:5432" nginx: build: ./nginx container_name: nginx ports: - "80:80" volumes: - static_volume:/home/something/some-thing/static - media_volume:/home/something/some-thing/media depends_on: - api volumes: postgres_data: static_volume: media_volume: Django DB settings: Django setting: from envparse import env env.read_envfile() DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": env("POSTGRES_DB", default=""), "USER": env("POSTGRES_USER", … -
Streaming a zip file in Python3
In my Django project, I have large zip files I need to send to a user for them to download. These files can be up to 10Gb big at some points. The files are already in zip format, and I don't want to extract them. Instead, I would like to send say 100mb of the file at a time, wait for the frontend to receive them, and then ask for the next 100mb until the file has been completely read. I can handle the collection and download on the frontend, but how can I perform this request in Django? Disclaimer: I'm a frontend developer, and very new to python. -
why do double quotes inside double quotes work in django
In a html file in django why does this: <link rel="stylesheet" href="{% static "myapp/style.css"%}" /> work and produces the same result as: <link rel="stylesheet" href="{% static 'myapp/style.css'%}" /> -
which framework is better Spring MVC or Django?
Which framework is better Spring MVC or Django, and why? I have a confusion on which is better and if someone has basic idea of both the frameworks then which one should he use for future -
How to restrict form validation for users under 18 years of age in Django
I have a form that allows users to update their birthday on their profile. I only want the form to validate if the user is at least 18 years of age. Here's what I've tried: models.py class Profile(models.Model): birthday = models.DateField() forms.py from django import forms from datetime import date from .models import Profile class ProfileUpdateForm(forms.ModelForm): birthday = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) def clean_birthday(self): dob = self.cleaned_data['birthday'] age = (date.today() - dob).days / 365 if age < 18: raise forms.ValidationError('You must be at least 18 years old') return dob class Meta: model = Profile fields = ('birthday',) views.py @login_required def update_my_profile_view(request): profile = Profile.objects.get(user=request.user) if request.method == 'POST': form = ProfileUpdateForm(request.POST or None, instance=profile) if form.is_valid(): form.save() return redirect('users:my_profile') else: form = ProfileUpdateForm() context = { 'form': form, } return render(request, 'users/my_profile.html', context) At the moment if I enter a date which is less than 18 years from the current day the date is simply not displayed. What I want instead is for the form to become invalid and show the user an error. How can I achieve this please? -
Create object in model having foreigkey relation
I want to create an entry in this Something model in python manage.py shell using this Someting.objects.create(discussion_title="General", user_username="admin", content="Hello") models example class Discussion(models.Model): title = models.CharField(max_length=255, unique=True, blank=False,) users = models.ManyToManyField(User, blank=True, ) class Something(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) discussion = models.ForeignKey(Discussion, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField(unique=False, blank=False) I am getting this error TypeError: Something() got an unexpected keyword argument 'discussion_title' -
Django key value pair to template
I am new to Django, and learning it for a school project. Part of the project is to have a time scheduler. I tought it was best to do with a key - value database structure, so I did. Now I am struggeling with getting it in to my template. This is my models.py key-value model: class generalSetting(models.Model): key = models.CharField(max_length=200, unique=True, null=True) value = models.CharField(max_length=200, null=True) def __str__(self): return self.key views.py: def timetable(request): generalSettings = generalSetting.objects.all() return render(request, 'VulnManager/timetable.html', {'generalSettings':generalSettings}) Here is the table on which I want to have the data <table id="tablePreview" class="table table-borderless table-hover"> <!--Table head--> <thead> <tr> <th></th> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> <th>Thursday</th> <th>Friday</th> <th>Saturday</th> <th>Sunday</th> </tr> </thead> <!--Table head--> <!--Table body--> <tbody> <tr> <th scope="row">Scan?</th> <td><select class="form-control" id="scanMonday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanTuesday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanWednesday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanThursday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanFriday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanSaturday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanSunday" disabled="true"><option>Yes</option><option>No</option></select></td> </tr> <tr> <th scope="row">Time begin</th> <td><input type="text" id="startMonday" onchange="validateHhMm(this);" value="{{generalSettings(key='startMonday')}}" readonly /></td> <td><input type="text" id="startTuesday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startWednesday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startThursday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startFriday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startSaturday" onchange="validateHhMm(this);" value="" readonly /></td> <td><input type="text" id="startSunday" onchange="validateHhMm(this);" value="" … -
how to call django url with javascript?
i am first time using javascript. i want to know how can i use django urls in javascript. i have a problem with using django url link in javascript. i want to render product-detail page and product-update page using django url in javascript. index.js const Story = document.getElementById('approvedList'); const url = 'http://localhost:8000/api/approved/'; getPosts = () => { axios.get(url) .then((res) => { Story.innerHTML = ''; res.data.map((object) => { document.getElementById(".detaillink").onclick = function () { var detailLink = document.attr('id') location.href = "{% url 'detail' pk=object.pk %}" }; document.getElementById(".updatelink").onclick = function () { var updatelLink = document.attr('id') location.href = "{% url 'update' pk=object.pk %}" }; Story.innerHTML += ` <tr> <td>${object.id}</td> <td><a href="#" class="detailLink">${object.title}</a></td> <td> <div class="table-btns"> <a href="" class="updatelink"> Update </a> </div> </td> </tr> `; }) }) .catch(error => console.log(error)) }; getPosts(); setInterval(getPosts, 3000) -
when do you use quotes in django [closed]
I’m learning django and am a little confused about the use of quotes. It seems that you can use double quotes inside of double quotes instead of the standard double quote single quote paradigm. Also, it seems that some references to urls get quoted and others do not. Can someone point me to the documentation on the use of quotes when coding in django? -
Store data in session for Anonymous User in Django
I need to store token in session for Anonymous User. In one view the data is stored and I can see it in request. But in another request session is empty, but keys are equal. I store data as it in docs: request.session['token'] = token Also session in request in view where data was added: {'_SessionBase__session_key': '6isiuup8xdq7nfr34cmog78t6lkc13p3', 'accessed': True, 'modified': True, 'serializer': <class 'django.core.signing.JSONSerializer'>, 'model': <class 'django.contrib.sessions.models.Session'>, '_session_cache': {'access_token': 'access-sandbox-1d05b2ac-81b4-4126-a57a-7c0ba916252e'}} After that, in another view: {'_SessionBase__session_key': '6isiuup8xdq7nfr34cmog78t6lkc13p3', 'accessed': False, 'modified': False, 'serializer': <class 'django.core.signing.JSONSerializer'>} In settings: INSTALLED_APPS = [ ... 'django.contrib.sessions', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', ... ] I read all docs and still can't find the reason of such strange behavior. Or may be I don't understand smth. -
Django Ajax how would i delete the comment using ajax instead of a normal request?
I have code set up so that users can delete comments on an article. However currently, when they delete the comment it will refresh the page and take them back to the top. I'm trying to implement Ajax so that when they delete the comment it'll do it without a page refresh. This is the code I have currently for deleting a comment. index.py <form action="{% url 'add-delete-view' %}" method="POST" class="ui form"> {% csrf_token %} <input type="hidden" name="comment_id" value="{{c.id}}"> <button type="submit" onClick="deleteComment({{c.id}})" id= "{{c.id}}" class="ui primary button c_edit{{c.id}}" name="submit_d_form">delete</button> urls.py path('deleteComment/', views.delete_comment, name='add-delete-view') views.py @login_required def delete_comment(request): comment_obj = Comment.objects.get(id=request.POST.get('comment_id')) comment_obj.delete() return redirect('index') I've attempted to try and implement Ajax but I'm just feeling hopeless in trying to get it work. In index.py I've added function: function deleteComment(comment_id) { var action = confirm("Are you sure you want to delete this comment?"); var comment = $(this) if (action != false) { $.ajax({ method: 'DELETE', url: '{% url "add-delete-view" %}', success: function (data, textStatus, jqXHR) { comment.remove(); }, }); } } But I'm just not sure where to go next or if this will even work. Any help or code would be greatly appreciated. It feels like this simple concept is very …