Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django delete item use case : good practice?
Little general explanation. I'm pretty newbie in Django, I have a little knowledge, but nothing as experience. The code that I want ask about is working, but I have a question about good/bad practice. Does my approach is good or at least not bad? Little use case explanation. I have a site with the items. There is a functionality to add the items and now I want to add a possibility to delete the item. Use case : on the page of item user clicks on the button Delete, we will show a page with details about this item and the button "Confirm delete" at the bottom. If user click on the button I delete this item from database. So I create in urls.py path('item/delete/<int:id>/', views.delete_item, {}, 'delete_item'), I create in views.py def delete_item(request,id): if id : cur_item = get_object_or_404(Item, pk=id) else : raise Http404 if request.POST: try : post_item_id=int(request.POST["pk"]) except ValueError : messages.error(request,"Wrong id number") return render(request, 'myapp/item_delete_form.html', {'cur_item': cur_item}) if (request.POST["delete"] == "yes") and (post_item_id == id): Item.objects.filter(pk=id).delete() # Delete was successful, so redirect to another page redirect_url = reverse('items') return redirect(redirect_url) else: messages.error(request, "id number in form not the same as in URL") return render(request, 'myapp/item_delete_form.html', {'cur_item' … -
How to get parent model in child serializer without using depth?
I am new to django, i tried to practice django rest api implementation. models.py from django.db import models class Parentmodel(models.Model): ptid = models.IntegerField(primary_key=True) ptname = models.CharField(default="",max_length=50) def __str__(self): return self.ptname class Studentmodel(models.Model): stid = models.IntegerField(primary_key=True) stname = models.CharField(max_length=50) ptid=models.ForeignKey(Parentmodel,db_column='ptid', related_name="student", on_delete=models.CASCADE) def __str__(self): return self.stname class Marksmodel(models.Model): Marksid=models.IntegerField(primary_key=True) maths=models.IntegerField() physics=models.IntegerField() science=models.IntegerField() stid=models.ForeignKey(Studentmodel,db_column='stid', related_name="marks", on_delete=models.CASCADE) def __str__(self): return self.Marksid serializers.py from rest_framework import serializers from polls.models import Studentmodel, Marksmodel, Parentmodel class MarksSerializer(serializers.ModelSerializer): class Meta: model=Marksmodel fields="__all__" class StudentSerializer(serializers.ModelSerializer): marks=MarksSerializer(read_only=True,many=True) class Meta: model=Studentmodel fields="__all__" class ParentSerializer(serializers.ModelSerializer): student=StudentSerializer(read_only=True,many=True) class Meta: model=Parentmodel fields="__all__" views.py from rest_framework import viewsets from .serializers import StudentSerializer, MarksSerializer, ParentSerializer from .models import Studentmodel, Marksmodel, Parentmodel class Studentapi(viewsets.ModelViewSet): queryset = Studentmodel.objects.all() serializer_class = StudentSerializer class Marksapi(viewsets.ModelViewSet): queryset = Marksmodel.objects.all() serializer_class = MarksSerializer class Parentapi(viewsets.ModelViewSet): queryset = Parentmodel.objects.all() serializer_class = ParentSerializer Above code is working fine. I able to get the correct response if i call parent api. Parentapi Response : [ { "ptid": 1, "student": [ { "stid": 1, "marks": [ { "Marksid": 1, "maths": 100, "physics": 100, "science": 123, "stid": 1 } ], "stname": "Nainika", "ptid": 1 } ], "ptname": "Sabish" } ] Studentapi Response : [ { "stid": 1, "marks": [ { "Marksid": 1, "maths": 100, "physics": 100, … -
Celery no longer connecting to Redis through Heroku
I had my Redis server set up and deployed on Heroku and Celery was fully functional however now it does not want to connect. The host and port recently updated but I have switched this over to my code like I usually do to fix the issue but it still persists. [2021-04-22 09:01:46,999: ERROR/MainProcess] consumer: Cannot connect to redis://:host:port//: Error while reading from socket: (54, 'Connection reset by peer'). My celery is set up as follows and the credentials all match with those on Heroku - os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') app.conf.timezone = 'Europe/London' app.config_from_object('django.conf:settings') app.conf.update(BROKER_URL='redis://:password@host:port', CELERY_RESULT_BACKEND='redis://:password@host:port') In my settings I just have - CELERY_BROKER_URL = 'redis://:password@host:port' If I check heroku redis:credentials REDIS_URL I get - rediss://:password@host:port Is the difference between redis and rediss doing something here? I've also seen on the documentation the usual set up for Redis is - 'redis://:user:password@host:port' - but I haven't had to add a user in before and it has worked fine. There is also no named user when looking at the Redis credentials on Heroku. As I mentioned it was working perfectly fine until a week ago and nothing has changed other than Redis updating as it does periodically. -
Why is the 'r' before strings in python so important?
I am fairly new to the Django framework and for a couple of hours I was getting TemplateNotFound error returned when I tried to map my views.py to my templates directory. This issue was eventually solved just by inputting 'r' before my path to templates in os.path.join(BASE_DIR, 'templates') to become os.path.join(BASE_DIR, r'templates'). I really want to understand better what function it carries out on the string. what is the big idea? -
Filter Foreign Key in Django Graphene Filter using DjangoFilterConnectionField
I am finding a solution for filtering Foreign Key in Django Graphene Filter using DjangoFilterConnectionField. Here is my code: My models: class Team(models.Model): name = models.CharField(max_length=125, validators=[MinLengthValidator(1)]) creator = models.ForeignKey(User, related_name='team_creator', on_delete=models.CASCADE) My schema: class TeamType(DjangoObjectType): class Meta: model = Team filter_fields = ['creator', 'is_active', ] interfaces = (graphene.relay.Node, ) use_connection = True class Query(graphene.ObjectType): team = graphene.relay.Node.Field(TeamType, idname=graphene.Int()) teams = DjangoFilterConnectionField(TeamType) def resolve_teams(self, info, **kwargs): return Team.objects.all() When I exec query to list all teams which created by creator with id 1: query getTeamsCreatedByMe { teams(creator: "1") { edges { node { name } } } } It goes error: { "errors": [ { "message": "['{\"creator\": [{\"message\": \"Invalid ID specified.\", \"code\": \"\"}]}']", "locations": [ { "line": 2, "column": 3 } ], "path": [ "teams" ] } ], "data": { "teams": null } } Please help me with this code. Thanks in advance! -
Django JWT - Add Custom Field to User
I want to add a custom field to JWT User Model like biography and fetch with API. I couldn't handle with it, i'm so confused. I'm getting this error "django.core.exceptions.ImproperlyConfigured: Field name bio is not valid for model User." My models.py as below: from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models from django.db.models.signals import post_save from rest_framework_jwt.serializers import User from tinymce.models import HTMLField class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) Views.py from rest_framework import viewsets, status, permissions from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated, AllowAny from django.contrib.auth.models import User from rest_framework.decorators import action, api_view from .serializers import UserSerializer, UserSerializerWithToken @api_view(['GET']) def current_user(request): """ Determine the current user by their token, and return their data """ serializer = UserSerializer(request.user) return Response(serializer.data) class UserList(APIView): """ Create a new user. It's called 'UserList' because normally we'd have a get method here too, for retrieving a list of all User objects. """ permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = UserSerializerWithToken(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers.py from rest_framework_jwt.serializers import User from .models import Content, Rating from rest_framework import serializers from rest_framework_jwt.settings import api_settings class UserSerializer(serializers.ModelSerializer): … -
how to make function call independent to Django server?
I have a python module which updates database infinitely for multiple connections. To start the work I have a button in UI to initiate the call using ajax and django views action is like below views.py def initiate_all(request): pool = Pool(4) pool.map_async(enableUpdate, [entity] for entity in range(3)) return HttpResponse() for three iterations it calls function and establishes three concurrent connections to update the data like below module.py def enableUpdate(e): while connection_is_alive(): connection to db update the values The above code works perfect where its doing multiprocessing to create 3 connection (in above example) and update database respectively. But if django server is stopped it destroys all objects which intern stops database update work as well. Requirement is ones the user clicks start button from UI, python update code should work even if the django server stops running. How to achieve this ? -
Joblib svm model giving KeyError when opening from nginx server but it works when loading from localhost
I am doing a classification problem i have almost completed my work and everything works perfectly on localhost by classifying with my external svm model but it does not works when i deploy on digital ocean nginx server it gives me keyerror 118 Error Image. Code for loading model filname = "new_bigger_category_classification_svm_model_v5.sav" model_cat = joblib.load(open(filname, 'rb')) Error on terminal: terminal error I am repeatedly getting error when i am trying to predict from online Ubuntu server in digital ocean but works perfectly on local server. Please help me to solve this problem. Thank you! -
How to pass modelform instance fields that are not intended for user input to template in Django
I'm using formsets to pass several modelforms with existing model instances to a template. I'd like to do something in the template for each form depending on the value of a model field (let's call it field_check) for that instance. Field_check is not intended for user input and a required field. If I include field_check into my form without rendering it, I can easily access its value. But then after submitting the form Django complains that field_check is required. What is the recommended way to access the value of field_check without including it as an input field or running into the required field problem? Models.py class MyModel(models.Model): field_check = models.CharField(max_length=50) user_input_field = models.CharField(max_length=50) some_type = models.CharField(max_length=50) Forms.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = [ 'user_input_field', 'field_check', #having this field here creates problems, since it's not intended for user input ] MyFormSet = forms.modelformset_factory(MyModel, form = MyModelForm, extra=0) Views.py def myview(request): this_type = 1 formset = MyFormSet(request.POST or None, queryset = MyModel.objects.filter(some_type = this_type)) if request.method == 'POST': if formset.is_valid(): formset.save() return render(request, 'some_other_template.html') context = {'formset':formset} return render(request, 'mytemplate.html', context) Template <form method="post"> {{ formset.management_form }} {% for form in formset %} {{form.id} # here is the … -
Applying CORS to Django static files
I'm trying to get one project to access resources of another project. I installed django-cors-headers and everything started working fine except for static files. I followed the answer here and while it does work, it's mentioned that this isn't advisable for production environments. Is there an alternative that I can do to serve static files without compromising my production environment? If it helps, I'm trying to access the static file (a .csv) with d3 via the following javascript code: d3.csv('https://127.0.0.1:8200/static/tracks/3CeCwYWvdfXbZLXFhBrbnf.csv') .get(function(data) { // Code here }); }); Accessing my production server yields the following: Access to XMLHttpRequest at 'http://example.com/static/tracks/3CeCwYWvdfXbZLXFhBrbnf.csv' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Production server settings: CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ 'https://example.com', 'http://localhost:8000', 'http://127.0.0.1:8000', 'http://127.0.0.1', ] CORS_ALLOWED_ORIGINS = CORS_ORIGIN_WHITELIST MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'sass_processor', 'corsheaders', ] -
How to use parent loop counter in the nested for-loop to access to a specific row in a json like data in django templates (.html file)
at the following code the interior for loop needs to access to a specific row of entries. In the other words the nested loop should be {% for entry in entries.(topic.id) %} the entries is a JSON like array as the following: entries = [ {'a', 'b', 'c'}, {'d'}, {'e', 'f', 'g', 'h', 'i'}, {'j','k'} . . . ] {% for topic in topics %} <li> <h5> {{topic.id}} - {{topic}} <ul> <small> {% with i=topic.id %} {{i}} {% for entry in entries.i %} <li>{{forloop.counter}} . {{entry}}</li> {% empty %} <li>No entries available!</li> {% endfor %} {% endwith %} </small> </ul> </h5> </li> {% empty %} <li> <h4 style="color: tomato;">There is no available topic(s)</h4> </li> {% endfor %} -
Debug django apps using vim + vimspector
I'am trying run debugging of django, but breakpoints doesn't working. For Example: I created configuration for vimspector enter image description here Add new def() to manage.py enter image description here Run the command: python manage.py runserver Start debugging from vimspector. It attached was successfully, but when I reload web-page it's give to me error "This site can't be reached". I matched it's for piece of code "debugpy.wait_for_client" and trying comment this. In this case web-page reload without error, but breakpoints doesn't work. Ex. information: After running server and debug I see two processes, may be debugpy want attach to process run sever. enter image description here -
Using few specific fields from another
So I was trying to use this fields on my Insuree model which originally came from Policy model policy_category = models.ForeignKey('Policy', on_delete=models.CASCADE, blank=True,null=True,default="Life") policy_length = models.ForeignKey('Policy', on_delete=models.CASCADE, blank=True, null=True, default="") coverage_amount = models.ForeignKey('Policy', on_delete=models.CASCADE) However, I was encountering these errors: Now, I'm not sure if its possible the thing I was trying to do. Any possible approach? -
Django For Beginers - Joinpath error when running manage.py runserver
I am learning Djnago and I am facing an issue I have looked around but can't maange to solve it. So basically on page 45 of Django For Beginners the author says : " Next we need to update config/settings.py to tell Django the location of our new templates directory. This is a one-line change to the setting 'DIRS' under TEMPLATES." Code config/settings.py TEMPLATES = [ { ... 'DIRS': [str (BASE_DIR. joinpath('templates '))], # new ... }, ] So in my settings.py file I have this : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [str(BASE_DIR.joinpath('templates'))], # new 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Unfortunatelly, when I run the manage.py runserver I then get this message : File "C:\Users\User\Desktop\pages\manage.py", line 22, in <module> main() File "C:\Users\User\Desktop\pages\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\User\.virtualenvs\pages-8ZErAoFj\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\User\.virtualenvs\pages-8ZErAoFj\lib\site-packages\django\core\management\__init__.py", line 363, in execute settings.INSTALLED_APPS File "C:\Users\User\.virtualenvs\pages-8ZErAoFj\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Users\User\.virtualenvs\pages-8ZErAoFj\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\User\.virtualenvs\pages-8ZErAoFj\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\users\user\appdata\local\programs\python\python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in … -
how to get only the 'title' attribute value from following data in django
This is the views.py I want to get 'title' attribute from the serialize data views.py class CalculatView(views.APIView): query = CartProduct.objects.latest('id') serializer = CartProductSerializer(query) choose_product = serializer.data.get('product') [sell_id] = choose_product querye = Product.objects.filter(id = sell_id) serializere = ProductSerializers(querye, many=True) choosee = serializere.data print(choosee) output : [OrderedDict([('id', 2), ('title', 'Frock'), ('date', '2021-04-22'), ('image', '/media/products/kids2.jpg'), ('marcket_price', 1.2), ('selling_price', 1.2), ('description', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa'), ('category', OrderedDict([('id', 2), ('title', 'Fashion'), ('date', '2021-04-22')])), ('seller', OrderedDict([('id', 2), ('seller_name', 'CIB - Piliyandala'), ('lat', 6.8018), ('lng', 79.9227), ('date', '2021-04-22')]))])] -
how to set timezone for strawberry on django
I am using django==3.1.7 with strawberry-graphql==0.57.2 create GraphQL APIs. I want the datetime fields that is rendered to the output get affected by django TIME_ZONE, But when I change time zone in settings.py it has no effect. I am thinking of overriding process_result of GraphQLView and check for every field type that is datetime and add time zone to it, but I feel that it's wrong. -
How to increase request timeout error for larger requests in ngnix
I have trained the machine for a few specific tasks. Deploy it into Django with Nginx and Gunicorn on AWS EC2. Whenever I generate a request based on a small input, it works fine. In the case of large input, it takes so much time. I needed that time. Eventually, the "502 Bad Gateway" error message appears. How I can prevent this error. I thought it was nginx request timeout error. So I increased using http{ ... proxy_read_timeout 300; proxy_connect_timeout 300; proxy_send_timeout 300; ... } So, is there a solution? I'm new to StackOverflow, so please bear with me. -
I am not getting the data I want when I call the post request, the response is empty
def spotify_callback(request, format = None): code = request.GET.get('code') error = request.GET.get('error') response = post('http://accounts.spotify.com/api/token', data = { 'grant-type' :'authorization_code', 'code' : code, 'redirect_uri': REDIRECT_URI , 'client_id' : CLIENT_ID, 'client_secret': CLIENT_SECRET }).json() access_token = response.get('access_token') token_type = response.get('token_type') refresh_token = response.get('refresh_token') expires_in = response.get('expires_in') error = response.get('error') if not request.session.exists(request.session.session_key): request.session.create() update_create_tokens( request.session.session_key, access_token, token_type, expires_in, refresh_token) return redirect('frontend:') I am trying to work with Spotify's API but when I sent a request for post with the data shown below it's saying 405: method not allowed -
Is there another issue that can cause css files not been found on django project?
I am sorry to ask very repeated question. However, I have tried my best for many days yet cannot figure it out. Could anyone guide me what I have done wrong? I tried to create a library program by django. This is my files' directory: prophado_lib |_prophado_lib |_ __pycache__ |_ __init__.py |_ settings.py |_ urls.py |_ wsgi.py |_book_management |_ __pycache__ |_ migrations |_ static |_ css |_ style.css |_ Templates |_ index.html |_ __init__.py |_ admin.py |_ apps.py |_ models.py |_ tests.py |_ views.py |_dbsqlite3 |_manage.py Then my code in each file are as follows: index.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/> <h1>{{var1}}</h1> Welcome to Propado School Library! settings.py BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' urls.py from django.conf.urls import url from django.contrib import admin from book_management import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^my_index/', views.index), ] urlpatterns += staticfiles_urlpatterns() fyi, I have already tried other ways with STATIC_ROOT and python manage.py collectstatic , even though I have known that it's for when I would like to make it in to production. -
Django multithreading to run render() as well as store data in a file
I am currently working on a Django application which searches for input words in a database and returns 'True' if words are found. I would like to store the undetected words in a file with the help of a function call during the time 'render()' is called to return the status of input words. How is it possible through multi-threading? Below I have shown my function names: I am currently working on a Django application which searches for input words in a database and returns 'True' if words are found. I would like to store the undetected words in a file with the help of a function call during the time 'render()' is called to return the status of input words. How is it possible through multi-threading? Below I have shown my function names: def store_undetected(): # function to store undetected words return 0 def sentence(request): # function to analyse words from input return render(....) Within 'sentence(request)', I would like to use one thread to call store_undetected() and the other to return render(). -
Reverse for 'password_reset_complete' not found
I am Using PasswordResetView for reset password, but when I Enter new Password and submit the button. Django redirect to this ulrs.py from django.urls import path from Authentication import views from django.contrib.auth import views as auth_view from .forms import * app_name = 'Authentication' urlpatterns = [ path('', views.loginpage, name='loginpage'), path('login', views.handlelogin, name='login'), path('logout', views.handlelogout, name='logout'), path('password_reset', views.password_reset, name='password_reset'), path('password_reset/done/', auth_view.PasswordResetDoneView.as_view(template_name='Authentication_template/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_view.PasswordResetConfirmView.as_view(template_name='Authentication_template/password_reset.html', form_class=SetPasswordForm), name='password_reset_confirm'), path('password_reset_complete/', auth_view.PasswordResetCompleteView.as_view( template_name='Authentication_template/password_reset_complete.html'), name='password_reset_complete') ] here I use custom view for sending email to user. -
KeyError Django rest framework
I am receiving KeyError from the application. I have field patientName in my model, however, the problem raised was patientName. Can anyone please help with this, has been struggling with this for few days. i am not very sure if i make any misstake here. I wanted to use filter here, to receive only the patientNmae, patienNRIC, and patientAddress, however, it fails. view.py from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import PatientDetail from .serializer import PatientSerializer import sqlite3 # Create your views here. @api_view(['Get', 'POST']) # @csrf_exempt def patient_list(request): if request.method == 'GET': data = request.data patientname = data['patientName'] # patientnric = data['patientNRIC'] patientdetails = PatientDetail.objects.filter(patientName = patientname ) # patientdetails = PatientDetail.objects.all() # serialization serializer = PatientSerializer(patientdetails, many=True) # return Json return Response(serializer.data) elif request.method == 'POST': #data = JSONParser().parse(request) serializer = PatientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['Get', 'PUT','DELETE']) @csrf_exempt def patient_detail(request,patientNRIC): try: patientdetails = PatientDetail.objects.get(patientNRIC = patientNRIC) except PatientDetail.DoesNotExist: return HttpResponse(status=404) if request.method == "GET": # serialization, getting one data only serializer = PatientSerializer(patientdetails) # return Json return JsonResponse(serializer.data) elif request.method == "PUT": … -
list of download file without models in django
Can we create a list of download file by specifying to folder path and their is no model related to filefield to handle uploaded pdf file. Saving the uploaded file to specific folder using filehandling method. -
Handle AJAX POST request to render a template in django
I have a problem when making a site with django, I hope you guys can give me a help. After using an AJAX POST, I will get that data to a function in view.py and do my stuff. It works nice, but when I need to render a template with data of my stuff, the browser does not direct me to that template. Can anyone tell me what should I do to handle the AJAX POST request. Thanks a lot and have a nice day. view.py: def get_id_from_ajax(request): print(request) if request.method == 'POST' and request.is_ajax(): print(type(request.POST)) QueryID = request.POST['key'] print('data recieved: '+ QueryID) if type(int(QueryID)) == int: Query_user = allusers.objects.get(id = QueryID) Query_username = Query_user.username Query_teamID = Query_user.teamid Query_rank = Query_user.rank Query_status = Query_user.is_deleted #return HttpResponseRedirect(json.dumps({'username': Query_username})) #return edit_user(request) #return JsonResponse(json.dumps({'username': Query_username}), safe=False) return render(request, 'edit_user.html',{"username": Query_username, "teamid": Query_teamID, "rank": Query_rank, "status": Query_status}) #return redirect('edit_user.html') return render(request, 'edit_user.html') ajax post: btn[i].addEventListener('click', function(e){ var testID = this.id; var getID = testID.match(/\d/g); getID = getID.join(""); console.log(getID); e.preventDefault(); $.post('/testdb/get_id_from_ajax', { key: getID, csrfmiddlewaretoken: csrftoken }); I just need to render a new template with data I got in my view.py. Thank you guys for any help. -
How to authenticate using external endpoint in django
I’m building a webapp with drf which does the authentication by calling an external api. Token received from front end is sent as request parameter. Response contains the Token status (Expired or Active). My app doesn’t have a user model. So all the views should be displayed based on the status of the external api call. To accomplish this, i have added a middleware. If the token status is expired i need to respond with 401 unauthorized json response. I found out drf has HttpResponseForbidden but it returns 403 and http response. which exception or response can i use here? Is it possible to do this in drf authentication classes instead of using middleware? or is there any other way to do this? Below is my middleware code : from rest_framework.exceptions import AuthenticationFailed from django.http import HttpResponseForbidden class AuthMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: # Post call to external api # if Token valid, do nothing # else return Invalid token with 401 code return HttpResponseForbidden("Invalid Token") # currently returns 403 code except Exception as e: print(e) response = self.get_response(request) return response