Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google App Enge Tutorial - django_cloudsql base.py",
I have been trying to get the GAE example (https://cloud.google.com/python/django/flexible-environment) on my Mac - Installed virtualenv and it works up to the python.py make migrations part. The error: (env) s-MacBook-Pro:django_cloudsql jv$ pip install psycopg2-binary Collecting psycopg2-binary Using cached psycopg2_binary-2.7.4-cp36-cp36m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl Installing collected packages: psycopg2-binary Successfully installed psycopg2-binary-2.7.4 (env) jvs-MacBook-Pro:django_cloudsql jv$ python manage.py makemigrations Traceback (most recent call last): File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/psycopg2/init.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: received invalid response to SSL negotiation: U The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 24, in execute_from_command_line(sys.argv) File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/core/management/init.py", line 371, in execute_from_command_line utility.execute() File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/core/management/init.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 92, in handle loader.check_consistent_history(connection) File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/db/migrations/loader.py", line 275, in check_consistent_history applied = recorder.applied_migrations() File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 61, in applied_migrations if self.has_table(): File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 255, in cursor return self._cursor() File "/Users/jv/Desktop/Projects/django_cloudsql/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line … -
how to gracefully prevent specific instance from being deleted
I have a Django application that has a model like this: class Foo(models.Model): name = models.CharField(max_length=100) I have a specific instance in this model that it's name is 'bar' (for example) and I want to prevent this instance from being deleted. I've created a signal receiver like this: def protect_foo_bar(sender, instance, using, **kwargs): if instance.title != 'bar': pass else: raise ProtectedError(protected_objects=instance, msg='You cannot delete this object') and I've connected this receiver to pre_delete signal like this: pre_delete.connect(receiver=protect_foo_bar, dispatch_uid='protect_foo_bar_signal', sender='app_name.foo') When I try to delete this specific object from Django's admin panel, it returns an exception. Is it possible to force the admin panel to show an error like you cannot delete this object and not returning an exception to the user? -
Object of type 'A' is not JSON serializable
I've the following get_or_create method. class LocationView(views.APIView): def get_or_create(self, request): try: location = Location.objects.get(country=request.data.get("country"), city=request.data.get("city")) print(location) return Response(location, status=status.HTTP_200_OK) except Location.DoesNotExist: serializer = LocationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): return self.get_or_create(request) def post(self, request): return self.get_or_create(request) This works fine for creating a new location, However if the location exists, I get the following error, TypeError: Object of type 'Location' is not JSON serializable [16/Mar/2018 10:10:08] "POST /api/v1/bouncer/location/ HTTP/1.1" 500 96971 This is my model serializer, class LocationSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) class Meta: model = models.Location fields = ('id', 'country', 'city', 'longitude', 'latitude') What am I doing wrong here -
Graphene Django DjangoFilterConnectionField with nested filters
I'm trying to achieve the following using graphene-django's DjangoFilterConnectionField: { allUsers(username_Icontains: "abc") { edges { node { id demographics (name_Icontains: "xyz") { id name } } } } } I know that in graphene django, it's possible to have nested filtering using graphene's List But I'm not sure if I can work this out using DjangoFilterConnectionField. I have the following graphene (relay) schema: class UserNode(DjangoObjectType): class Meta: model = User interfaces = (Node,) filter_fields = { 'username': ['exact', 'icontains', 'in'], } class DemographicNode(DjangoObjectType): class Meta: model = Demographic interfaces = (Node,) filter_fields = { 'name': ['icontains'], } class Query(ObjectType): user = Node.Field(UserNode) all_users = DjangoFilterConnectionField(UserNode) demographic = Node.Field(DemographicNode) all_demographics = DjangoFilterConnectionField(DemographicNode) In the docs it's suggested to introduce each filter on the connected node as well. So it would be like this: class UserNode(DjangoObjectType): class Meta: model = User interfaces = (Node,) filter_fields = { 'username': ['exact', 'icontains', 'in'], 'demographic__name': ['icontains'] } But I think there must be a better way to do this since I have to do this for more than 20 nested Nodes. -
How to make join using 2 foreign keys in django without raw query?
I have two seemingly unrelated tables that have unique pair of same foreign keys: class Car name = models.CharField() color = models.ForignKey(Color) driver = models.ForgnKey(User) class Meta: unique_together = (('color', 'driver'),) class Bicycle name = models.CharField() color = models.ForignKey(Color) driver = models.ForignKey(User) class Meta: unique_together = (('color', 'driver'),) For some reason I want to get query that have access to both of them. Simply to avoid querying in loop as the page is already complex. I can make raw query: query = Car.objects.raw( '''SELECT * from car INNER JOIN bicycle ON car.color_id = bicycle.color_id AND car.driver_id = bicycle.driver_id''' ) For compatibility reason I want to avoid raw query as it does not work in django admin panel and probably other places. Is there a way of making that query so the end result give me new column: car_query = Car.objects.something( Bicycle, join_with=('color', 'driver'), newfield='bicycle') print(car_query[0].bicycle.name) and is not a raw query: car_query.order_by('created') I have tried something like that: query = Car.objects.select_related('color').prefetch_related( Prefetch('color__bicycle_set', queryset=Bicycle.objects.filter(driver=F('driver')), to_attr='bicycle') ) But of course F('driver') relates to current queryset not the Car. Is this idea wrong? What should I do instead? -
Django Model form changing a field instance type on submit?
I have created a model form whereby I have overwritten and changed a foreign keys instance type so I could filter the list of options by site. However on submit of the form I need to change it back to its original instance type, which I though would be done on form save, but when I print out the save I do not see any output in console. it seems the error occurs before save? forms.py class CircuitSubnetForm(forms.ModelForm): class Meta: model = CircuitSubnets fields = ['circuit', 'subnet',] def __init__(self, *args, **kwargs): site_id = kwargs.pop('site_id', None) self.is_add = kwargs.pop("is_add", False) super(CircuitSubnetForm, self).__init__(*args, **kwargs) self.fields['subnet'].queryset = DeviceSubnets.objects.filter(device__site_id=site_id) self.fields['subnet'].label_from_instance = lambda obj: '{} - {}{}'.format(obj.device.hostname,obj.subnet.subnet,obj.subnet.mask) views.py class AddCircuitSubnet(CreateView): form_class = CircuitSubnetForm template_name = "circuits/circuit_subnet_form.html" @method_decorator(user_passes_test(lambda u: u.has_perm('circuits.add_circuitsubnet'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.circuit_id = self.kwargs['circuit_id'] self.site = get_object_or_404(Site, pk=self.site_id) self.circuit = get_object_or_404(Circuit, pk=self.circuit_id) return super(AddCircuitSubnet, self).dispatch(*args, **kwargs) def save(self, commit=True): form = super(AddCircuitSubnet, self).save(commit=False) print(vars(form)) form.subnet = Subnet.objects.get(id=form.subnet.subnet.id) form.save() return form error: Cannot assign "<DeviceSubnets: DeviceSubnets object>": "CircuitSubnets.subnet" must be a "Subnet" instance. -
Other Frameworks with Database creation for tests like Django
I'm looking for other Frameworks that have the functionality to create a database for tests like Django does and then destroys it. Have the migrations functionality is critical. Thanks -
Remove permissions on django
I wanted to know if something happens if I remove the permissions that are created by default in the database 1,'Can add log entry',1,'add_logentry' 2,'Can change log entry',1,'change_logentry' 3,'Can delete log entry',1,'delete_logentry' 4,'Can add permission',2,'add_permission' 5,'Can change permission',2,'change_permission' 6,'Can delete permission',2,'delete_permission' 7,'Can add group',3,'add_group' 8,'Can change group',3,'change_group' 9,'Can delete group',3,'delete_group' 10,'Can add user',4,'add_user' These are some of the permissions that appear in the database when the migration is made, something happens or I delete some of the permissions? -
Django Silk Profiling error
I am trying to use django-silk profiler in my development environment. The page renders successfully but in the console the following error is shown and no profiling data is available in the silk page. Exception when performing meta profiling, dumping trace below Traceback (most recent call last): File "site-packages/silk/middleware.py", line 122, in _process_response collector.finalise() File "site-packages/silk/collector.py", line 183, in finalise profile.queries = profile_query_models File "site-packages/django/db/models/fields/related_descriptors.py", line 509, in __set__ % self._get_set_deprecation_msg_params(), TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use queries.set() instead. I am using python 3.6 and django 2.0.3. -
Django url doesn't hit relevant function
I've the following url definition for an endpoint, url(r'^register/(?P<location_id>[\w.-]+)/$', RegisterView.as_view(), name='register'), I'm posting to this url in the following manner, http://127.0.0.1:8000/api/v1/bouncer/register/1/ I get a 500 server error even before the post hits the relevant function, What am I doing wrong here, Here's the stack trace, Internal Server Error: /api/v1/bouncer/register/1 Traceback (most recent call last): File "/Users/melissa/Dropbox/xdrive/ftb/ftb_core_backend/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/melissa/Dropbox/xdrive/ftb/ftb_core_backend/env/lib/python3.6/site-packages/django/utils/deprecation.py", line 93, in __call__ response = self.process_request(request) File "/Users/melissa/Dropbox/xdrive/ftb/ftb_core_backend/env/lib/python3.6/site-packages/django/middleware/common.py", line 61, in process_request path = self.get_full_path_with_slash(request) File "/Users/melissa/Dropbox/xdrive/ftb/ftb_core_backend/env/lib/python3.6/site-packages/django/middleware/common.py", line 99, in get_full_path_with_slash 'url': request.get_host() + new_path, RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/api/v1/bouncer/register/1/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. [16/Mar/2018 09:27:21] "POST /api/v1/bouncer/register/1 HTTP/1.1" 500 62822 -
Django : "detail": "Authentication credentials were not provided."
I'm using django rest framework. These are my settings for REST FRAMEWORK, REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ) # 'DEFAULT_PERMISSION_CLASSES': ( # 'rest_framework.permissions.IsAuthenticated', # ), } When I post to a simple endpoint, I get the following error, { "detail": "Authentication credentials were not provided." } What am I doing wrong here. Any help appreciated. -
Django getting error 403 while creating multiple ibjects
I'm getting 403 error while creating multiple objects. Here's code: uploaded_files = request.FILES.getlist('image') for f in uploaded_files: photo = Photo.objects.create(gallery=g, image=f) -
django - inlineformset - crispy - how to display non-field error
I have the following CreateView class CreatePerson(CreateView): model=Person form_class=PersonForm def get_context_data(self, **kwargs): context = super(CreatePerson, self).get_context_data(**kwargs) if self.request.POST: context['address_formset'] = AddressInlineFormSet(self.request.POST) else: context['address_formset'] = AddressInlineFormSet() return context def form_valid(self, form): context = self.get_context_data() formset = context['address_formset'] if formset.is_valid(): self.object = form.save() formset.instance = self.object formset.save() return super().form_valid(form) else: return self.render_to_response(self.get_context_data(form=form)) and the following form {% load static crispy_forms_tags %} ... {% csrf_token %} {% crispy form %} {{ address_formset.management_form }} {% for formset in address_formset %} {% crispy formset %} {% endfor %} ... How do I display the duplicate key error in the formset model. I have tried this way. form_errors = formset.errors return self.render_to_response(self.get_context_data(form=form,form_errors=form_errors)) and {{ form_errors }} which gives the following display in the form. [{}, {'__all__': ['Please correct the duplicate values below.']}] How do I render it in crispy way? Thanks -
How to run travisCI using Django testing framework
I have a Django project that I'm building using TravisCI which is supposed to be running the test class I have. For some reason, when the build runs, it succeeds, but the output of the job says that 0 tests were run: I was originally using the command python manage.py test to run the build, but for some reason, it didn't seem to be working so I then ran the command python src/manage.py test FileUploadTestClass.test_uploaded_file but this results in an import error for the test class. What is the proper way to run the django testing framework using TravisCI? .travis.yml language: python python: - "2.7" # setup environment env: - DJANGO_VERSION=1.11.2 - DJANGO_SETTINGS_MODULE='di_photouploader.settings.production' # install dependencies install: - pip install -r requirements.txt # run test scripts script: - python src/manage.py test -
Ordering a list of querysets by latest record
I'd like to implement a private messaging function in Django, where a member can see his/her messages in one page, separated as conversations. The conversation with the most recent message sent or received by the member should appear on top. What I tried: all_messages = Message.objects.filter(Q(sender=member) | Q(receiver=member)) other_members = all_messages.values_list("sender", flat=True).distinct() conversations = [] for sender in other_members: if sender == member.id: try: conversation = all_messages.filter(sender=member).exclude(receiver__in=other_members) conversations.append(conversation) except: continue else: conversation = all_messages.filter(Q(sender=sender, receiver=member) | Q(receiver=sender, sender=member)) conversations.append(conversation) The problem here is that when the member receives a new message, related conversation goes up; but when he sends a new message, conversation order doesn't change. To sum up, how can I sort properly the conversations by the most recent last message in them? Thanks! -
Django; error on printing JSON response in Firefox console
Urls.py: from .views import get_data app_name = 'javascript' urlpatterns = [ path('', views.index, name='index'), path('api/data', get_data, name='api-data'), ] Views.py: from django.http import JsonResponse def get_data(request): dictionary = {'Name':'John'} return JsonResponse(dictionary) def index(request): return render(request, 'javascript/index.html') Index.html: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $.ajax({ method: "GET", url: "/api/data/", success: function(dictionary){ console.log(dictionary) }, error: function(error_data){ console.log("errorrr") console.log(error_data) } }) </script> Using AJAX, I want to print dictionary contents upon index.html load. However, I get an 'errorrr' in the Firefox console: errorrr 127.0.0.1:8000:30:3 Object { readyState: 4, getResponseHeader: getResponseHeader(), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(), overrideMimeType: overrideMimeType(), statusCode: statusCode(), abort: abort(), state: state(), always: always(), catch: catch(), … } Is there any mistake in how my jQuery is written? -
How to encode a file in FileField using s3 to base64 in django?
I have a project that need to convert the file stored in a model's FileField to Base64 format, but I'm not sure how to do it. I tried using open(model_instance.file_field.file), it doesn't work I tried using base64.b64encode(model_instance.file_field.file), also doesn't work -
Django select 2 multiple select slow load
I'm a beginner and I've been playing around with the multiple select option of select2.js. In a historical school database we have over 300k student_id's. I can get the select2 option to work, but it's extremely slow and takes forever to load. I've seen other pages with select 2 load massive amounts of data and work fine. I'm using the following to javascript to load select2. $(document).ready(function () { $('.js-example-basic-multiple').select2(); }); In Django i'm loading the data in my template with: <script src= "{% static '/search/user_select2.js' %}" type="text/javascript"></script> <div class="col"><h4 style="margin-top: 0"><strong>Student ID List</strong></h4><select data-placeholder="Choose a list of 3-4 User ids..." class="js-example-basic-multiple" value = "{{ userid }}" style="width: 1110px" required> {% for user in userid %} <option value="{{ user }}"> {{ user }}</option> {% endfor %} </select> userid is defined with the following arg in my view: def multisearch(request): userid = STudent.objects.filter(student_status_id = 1).values('studentid') print(userid) args = {'userid':userid} return render(request, 'multisearch.html',args) -
How to check user first time login and redirect to different template?
When a user attempts to signin, I want to check if its his first time logging into the application and if so display user/firstlogin.html template. If its not his first time display user/profiletemplate. I'm currently using django-allauth for my authentication but can't seem to figure out how their signals work -
Count of related entities over two ManyToMany relations to the same Model in Django
Given roughly these two models: class Person(models.Model): name = models.CharField() class Resource(models.Model): people_contributing = models.ManyToManyField( Person, related_name='resouces_contributing_to' ) people_involved = models.ManyToManyField( Person, related_name='resources_involved_in' ) For all persons I want to get the count of resources he/she is either contributing to OR involved in. I tried the following: resources = Resource.objects.all() participations = Person.objects.filter( Q(resouces_contributing_to__in=resources) | Q(resources_involved_in__in=resources) ).annotate( count=Count('id') ).values('pk','name','count').order_by('-count') print(participations) This gives me a list of tuples like this: [ # (id, name, count) (1, 'John Doe', 12), (2, 'Jane Doe', 5), (3, 'Donald Trump', 3), ] However if a person is both contributing and involved the resource will be counted twice because the resource will be joined twice to the person table. What I want is to join the resource in an XOR manner. How do I have to change my queryset to prevent this? I am using postgresql and Django 1.11. -
Django admin custom ArrayField widget
The current admin widget for ArrayField is one field, with comma as delimiter, like this (text list): This isn't ideal because I would have longer texts (even 20 words) and contain commas. I could change the delimiter to be something else but that still doesn't help with unreadable content in admin. What I would like is having a list of fields, that I can alter in admin. Something similar to the following image I could use another table to solve this, but I wonder if it's possible to solve it this way. -
Want to achieve searching function in django admin page for multiple tables
I am currently working on django 2.0.2 admin page. I have three tables, which are 'metabolites', 'gene' and 'reactions.' The structure of each class is defined as below: class Genes(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Genes' class Metabolites(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255, blank=True, null=True) compartment = models.CharField(max_length=255, blank=True, null=True) charge = models.CharField(max_length=255, blank=True, null=True) formula = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Metabolites' class Reactions(models.Model): id = models.CharField(max_length=255, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) metabolites = models.TextField(blank=True, null=True) lower_bound = models.CharField(max_length=255, blank=True, null=True) upper_bound = models.CharField(max_length=255, blank=True, null=True) gene_reaction_rule = models.TextField(blank=True, null=True) subsystem = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Reactions' As you can see, the 'reaction' class also included 'metabolites' component. A typically reaction actually involved more than two metabolites. What I want to do is, create a search field on the admin page(not the page of each class), and when I type in the reaction id, the searching result can display the reaction and all the involved metabolites, and when I … -
Bug in project built with Django 2.0 Celery 4.1.0
I have an inconvenience at the moment of validating tasks that celery executes in my project built in Django. I am validating that if it is time to change the status of a tender in the database. When doing the validation, It never showed true and decided to print the dates: the current datetime with the datetime at which the bidding status should be changed. The local time (UTC-5) was normal and the one in the database shows it to me with 5 more hours (UTC). settings.py # CELERY STUFF BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectdeps.settings.local') app = Celery('projectdeps') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) from __future__ import absolute_import import os import django from celery import Celery from django.conf import settings from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectdeps.settings.local') django.setup() app = Celery('projectdeps') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.timezone = 'America/Bogota' @periodic_task(run_every=timedelta(minutes=1),name='verificar_estado_licitaciones') def verificar_estado_licitaciones(): cont = 0 licitaciones = … -
The empty path didn't match any of these. url.py
I am unable to connect my templates/index.html, urls, views.py # howdy/urls.py from django.conf.urls import url, include from howdy import views from howdy.views import hello urlpatterns = [ url(r'^index/$', views.index), ] PFA project folder hierarchy -
CSRF protection when not using forms to submit data
I have a list (that is forms in a formset) of files and for each item I have a button that can delete these files and their corresponding database records. Currently I am using an AJAX/JQUery call to achieve this. The button does not submit some kind of form but rather makes a POST request via AJAX ' directly' and I am wondering whether or not this is a safe way to do this w.r.t. CSRF? I have tried a number of things like adding the CSRF token to the header as per the documentation and using the @csrf_protect decorator. The function works and doesn't throw any errors but I'm not sure whether this is because the CSRF check are comming through or whether they simply never take place. When I look at my request.POST the CSRF-token is not listed, which is the case when I use a standard form approach. views.py @csrf_protect def delete_file(request): if request.method == 'POST': file_id = request.POST.get('file_id') try: SFile.objects.get(FILE_ID=file_id).delete() except: file_id = 0 return JsonResponse({'file_id':file_id}) raise Http404 AJAX/JQuery $('#file-list').on('click','.delete-file-button', function(event){ event.preventDefault(); var file_id2 = $(this).attr('id') var post_url = $(this).attr('data-url'); form_data = {file_id: file_id2} var csrftoken = getCookie('csrftoken'); $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && …