Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Optimizing Django Social Media App: Efficient Handling of Profile Privacy and Pagination Logic for Post Retrieval
I am new to Djnago and I am designing my first Social Media App, so I am a bit new to this. I have an API view to get a users profile and their posts. I have implemented logic to check if the requesting user is able to view another users posts based on their profile_privacy and if the requesting user follows them or not. If the requesting user is able to view the users posts, then and only then we query for their posts. My question is: Since the posts are paginated, when the user requests for the profile, it will perform the logic and then get the appropriate posts, however, when we query for the second page of Post data, it will perform the same logic and checks again (check the follow instance to see if the requesting user follows them). Instead of performing this logic for every page query, is there a way to check it only once since for all other page requests we know the user already follows them? One approach was checking if the page being requested is the first page and only perform the checks for that, but that introduces security issues since … -
Getting Origin is not allowed by Access-Control-Allow-Origin when using Django authentication on one url but all origins are allowed
I am running into issues with CORS on Django and React (fetch). Django is set up like this: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "corsheaders", "users", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] CORS_ORIGIN_WHITELIST = ( "http://localhost:3000", "http://127.0.0.1:3000", ) The urls in users: urlpatterns = [ path('login/<str:username>/<str:password>/', login), path('logout/', logout), path('info/', info), ] and views from rest_framework.decorators import api_view from rest_framework.response import Response from django.contrib import auth from django.http.response import HttpResponse # Create your views here. @api_view(['GET']) def login(request, username, password): user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return Response('yes') else: return Response('no') @api_view(['POST']) def logout(request): auth.logout(request) return Response('hmmmmmmm') @api_view(['GET']) def info(request): if request.user.is_authenticated: return HttpResponse('wow, this is really critical information: 5!') else: return HttpResponse('nothing here...') When I do a request from react let [message, setMessage] = useState('waiting...') fetch('http://localhost:8000/users/login/Timoty/foo') .then(res => res.text()) .then(text => setMessage(text)) I get the typical error... What puzzles me the most is the fact that this is a cors issue, I am thinking that maybe I need to do some cookie magic from my react code, but why am I getting cross origin errors then? It … -
Change django.forms.models.ModelChoiceIterator
The choices variable of one of my fields (django.forms.models.ModelChoiceIterator) in ModelForm contains 3 items. In some cases, I want to use only one of them (the first one in the "list") for the actual HTML. Here's a part of the Django Python code: class MyForm(ModelForm): def __init__(self, *args, user=None, **kwargs): choices = self.fields['xxx'].choices qs = choices.queryset qs = qs[:1] ... ... self.fields['xxx'] = forms.ChoiceField( label="xxx", widget=forms.Select( attrs={ 'class': 'form-select' } ), self.fields['xxx'].choices = choices self.fields['xxx'].choices.queryset = qs class Meta: ... model = MyModel fields = ('xxx') ... This throws an error : 'list' object has no attribute 'queryset'" and, obviously, the size and content of choices do not change. choices is an instance of django.forms.models.ModelChoiceIterator How can I reduce the number of items in the choices which will be displayed in the HTML ? -
OSError: /home/ahmad/miniconda3/envs/python3.6/bin/../lib/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /lib/libgdal.so.30)
Title: Error in Miniconda Virtual Environment on Ubuntu 22.04 Description: I recently upgraded my Ubuntu system from 20.04 to 22.04 and encountered an issue my project was running smoothly on Ubuntu 20.04, but after the upgrade, I'm facing the following error: ruby Copy code OSError: /home/ahmad/miniconda3/envs/python3.6/bin/../lib/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /lib/libgdal.so.30) I have tried several solutions I found online, including installing build essentials, Python development headers, and even creating a new virtual environment, but the issue persists. Here are some key details: I'm using Miniconda to manage my Python environment. I have created a virtual environment with Python 3.6 for my Django project. I would greatly appreciate any guidance or solutions to resolve this issue and successfully install GDAL in my virtual environment on Ubuntu 22.04. Thank you for your help! -
Getting Error cors "Request header field responsetype is not allowed by Access-Control-Allow-Headers in preflight response" in django
Error in the browser console Access to XMLHttpRequest at 'https:///some_site/resource1/downloadCSV' from origin 'https://some_site' has been blocked by CORS policy: Request header field responsetype is not allowed by Access-Control-Allow-Headers in preflight response. check the API Method @api_view(["POST"]) def downloadCSV(request): request_body = request.data response = HttpResponse( some_service.call_some_other_service(), content_type="application/octet-streamf", ) today = datetime.today().strftime("%Y-%m-%d") filename = f"{today}_Data.csv" response["Content-Disposition"] = f'attachment; filename="{filename}.csv"' return response main/settings.py INSTALLED_APPS = [ ............. "corsheaders", ........ ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", ] CORS_ORIGIN_ALLOW_ALL = True I can't do it because the other response type header is failing, Please suggest how to allow the responseType =bob so that I will able to download API. CORS_ALLOW_HEADERS = [ # ... 'responsetype', # ... ] -
winerror 5 access denied
i am setting up a virtual environment for django and when i use python -m venv djangoenv a winerror 5 pops up to tell me acess denied please i need help with this. i have been trying the whole day with different versions of vscode and i get the same message. i dont know if it has something to do with the path or i am not just during it right.i am a beginner and i can't seem to spot what exactly the problem is -
Creating and saving a model object with a calculated m2m field Django
New to Django, I don't know if it's still worth it. I'm currently trying to save a model form with a many-to-many field that should be set randomly according to other fields(category, subcategory, number) in the same form. how do I get it to work? class Exam(models.Model): categ=models.ManyToManyField(Category,blank=False) sscateg = models.ManyToManyField(SubCategory,blank = True,null= True) question = models.ManyToManyField (Question,related_name='questionsEx',blank=False) nbquestion = models.IntegerField() def save(self, *args, **Kwargs): super(Exam, self).save(*args,**Kwargs,commit=False) if self.pk: qs=Question.objects.filter(category=self.categ).filter(sscateg=self.sscateg).values_list('id',flat =True) questions = random.sample(qs,self.nbquestion) for quest in questions: self.question.add(quest) super(Exam, self).save(*args,**Kwargs) forms.py class ExamForm(forms.ModelForm): nbquestion = forms.IntegerField(required = False) categ=forms.ModelChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple,required = False) sscateg=forms.ModelChoiceField(SsCategory.objects.all(), widget=forms.CheckboxSelectMultiple,required=False) def save(self, commit=True): instance = forms.ModelForm.save(self, False) self.save_m2m() instance.save() return instance views.py class ExCreateView(LoginRequiredMixin, CreateView): login_url = 'login' template_name = 'MakeEx.html' model = Exam form_class = ExamForm success_url = reverse_lazy('Exams') def form_valid(self, form): instance=form.save(commit=False) instance.save() form.save_m2m() return super(ExCreateView,self).form_valid(form) -
image path is incomplete django
in my-projet (django) The image path is incomplete in some api How can i fix it like when i use this api (categories) i got this Response Note that the image path is complete [ { "id": 1, "name_ar": "تطبيقات توصيل", "name_en": "weew", "icons": "http://127.0.0.1:8000/media/catecgorys/cloud123333_ZCE0xex.svg" }, { "id": 2, "name_ar": "متاجر", "name_en": "stores", "icons": "http://127.0.0.1:8000/media/catecgorys/cloud123333_BSbQU6b.svg" }, ] but when i use some api the entire image path is not displayed like how i can fix it ? { "status": "True", "data": [ { "id": 1, "code": "444", "percentage": "10%", "store": { "id": 1, "name_ar": "", "name_en": "noon", "description": "sdsdsdsdsdsdsd", "url": "noon.com", "logo": "/media/logo/Noon_log.jpeg", "categories": [ { "id": 1, "name_ar": "category 1", "name_en": "category 1", "icons": "/media/Categories/cloud123333.svg" } ] }, "description": "", "type": "", "ratings": { "id": 2, "likes": 1, "dislikes": 1 } } ] } my code : class GetCouponsByCategoryAPIView(viewsets.ModelViewSet): permission_classes = [permissions.AllowAny] queryset = Coupons.objects.all() serializer_class = CouponsSerializer def post(self, request, *args, **kwargs): categorys_id = request.data.get("Categories_id") if not categorys_id: return Response({"error": "Categories_id parameter is required."}, status=status.HTTP_400_BAD_REQUEST) try: category = Categories.objects.get(id=categorys_id) stores = Stores.objects.filter(catecgorys=category) except Categories.DoesNotExist: return Response({"status": "False", "error": "Category not found."}, status=status.HTTP_404_NOT_FOUND) except Stores.DoesNotExist: return Response({"status": "False", "error": "Store not found."}, status=status.HTTP_404_NOT_FOUND) coupons = Coupons.objects.filter(store__in=stores) serializer = CouponsSerializer(coupons, … -
Unable to capture record IDs for Bulk Updating Fields for non-admin users in Django Front End
I'm trying to bulk update fields for a list of records, similar to an Admin Actions type drop down list , for non-admin users in the front end. The process a user follows - Step 1. Come to the candidates.html page Step 2. Select the candidate to whose field is to be updated by selecting the check box of the respective candidate in the candidates.html page which has the table of the candidates and the first column as the check box for selection. Step 3. Click on the mass_update_candidates button to be directed to the mass_update_candidates.html to update the fields with the new value. Step 1 & 2 function correctly, when clicking on the mass_update_candidates button it redirects to the page, however, On clicking Update Button, it is not capturing the selected IDs Please advise. Below are the forms.py, views.py and the different html templates. I do not have any coding experience. I'm trying to learn. This is a pet project I've created to learn. Any help is most appreciated. If you know of a better method to achieve this please do let me know, I'm more than willing to try new ideas. Thank You! Browser Console Message: JavaScript is … -
Why is django query set .filter() only accepting an id / interger, when I want to filter by a field/value?
I am new to django, creating a blog / article sharing website. I have a few databases set up, CRUD is functioning but I'm having trouble getting a bit more creative with the site. For example, on the news articles page, it lists all the articles shared by users. It states the category, the user, the title, the external link and when it was shared. Instead of just listing all of them , I would like to be able to give the user an option to filter either by user who submitted (all articles submitted by admin) or by car I'm trying to filter a database, by the value of one of its fields. So for example I have a model News which has fields like title, website, user, created on . class Article(models.Model): category = models.CharField(max_length=25, null=True) def __str__(self): return self.category class News(models.Model): title = models.CharField(max_length=100, null=True) website = models.CharField(max_length=50, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField( User, related_name='link_like', blank=True) external_link = models.URLField() category = models.ForeignKey(Article, on_delete=models.CASCADE) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() These are passed in from the user in a form when they share a news … -
How do I migrate my current users to aws cognito
I'm in the process of migrating my user authentication system to AWS Cognito. I followed this tutorial here and I can now send the Bearer token to django and it is stored as a user with the username containing the unique sub. The issue I am facing now is, I already have quite a large number of users that are signed up using my previous system, which was a token based authentication method. My question now is, how do I migrate those users to aws cognito, or is there a way to allow sign-ins using both aws cognito and also the token based authentication. Also note that, the user model have relationship with other models; so deleting or removing a user will also delete those data tied to a user. By the way, I am using react and amplify for the frontend authentication. -
Django models dependencies
I am new at Django Python. Need help I am writing Calory Counter. I have models Food (list of foods with calories, etc), Profile (store all selected foods through model Postfood) and Recipes. The question is how I can add recipe to my ration (Profile) . My models: class Food(models.Model): name = models.CharField(max_length=200, null=False) measure = models.CharField(max_length=200, null=True) quantity = models.PositiveIntegerField(null=False, default=0) calorie = models.FloatField(null=False, default=0) carbohydrate = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) fats = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) protein = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) person_of = models.ForeignKey(User, null=True, on_delete=models.CASCADE) recipe = models.ForeignKey('Receipe', null=True, on_delete=models.CASCADE) class Receipe(models.Model): name = models.CharField(max_length=200) content = models.CharField(max_length=1000000) portion = models.PositiveIntegerField(default=1, null=False) calorie = models.IntegerField(default=0, blank = True) carbohydrate =models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) fats = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) protein = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) time = models.PositiveIntegerField(default=20, blank=True) difficulty_level_options = ( ('easy', 'easy'), ('medium', 'medium'), ('difficult', 'difficult')) difficulty_level = models.CharField(max_length=50, choices=difficulty_level_options, default='medium') ingredients = models.TextField(max_length=1000000, null=True, blank=True) img_url = models.ImageField(upload_to='static/recipes', null=True, blank=True, default='static/recipes/no image.jpeg') class Profile(models.Model): person_of = models.ForeignKey(User, null=True, on_delete=models.CASCADE) current_weight = models.IntegerField(default=0, blank=True) goal_weight = models.IntegerField(default=0, blank=True) calorie_count = models.FloatField(default=0, blank=True) food_selected = models.ForeignKey(Food, on_delete=models.CASCADE, null=True, blank=True) exercises_selected = models.ForeignKey(Exercise, on_delete=models.CASCADE, null=True, blank=True) time_hour_exercise = models.IntegerField(default=0, blank=True) calorie_exercise = models.FloatField(null=False, default=0) quantity = … -
django import export not import excel file with foreignkey msssql
i have a resource.py class bankid_resource(resources.ModelResource): class Meta: model = bankID and have model.py class bankID(models.Model): bankIdN = models.CharField(max_length=300, null=True, blank=True, unique=True) userID = models.ForeignKey('UserDetails', on_delete=models.CASCADE, null=True, blank=True) CardN = models.CharField(max_length=300, null=True, blank=True, unique=True) and in my view.py iwant to import excel file with this function def import_bankid_list(request): if request.method == 'POST': bankids = bankid_resource() dataset = Dataset() new_bankids = request.FILES['myFile'] data_import = dataset.load(new_bankids.read()) result = bankids.import_data(dataset, dry_run=True) if not result.has_errors(): bankids.import_data(dataset, dry_run=False) return redirect('import_bankid_list') else: return redirect('') return render(request, 'personel/import.html') but data not import because have a ForeignKey in exported csv file. my database is mssql. i need help to solve the problem any file without ForeignKey will import corecctly. -
The appearance of the admin panel in Django is broken
I am a Django beginner. When I enter the address of the admin panel, I encounter a broken and strange panel: https://s6.uupload.ir/files/screenshot_2023-09-02_155801_0mvm.png -
Not registering logged in user's information into form (Django/Javascript)
I am trying to fill in the logged in user's Name and Email into a a form for a POST request. It is for a an ecommerce website for when they click the Make Payment button, but it keeps coming up withnull for the fields. I think this is why it won't send the request through. I am trying to grab their already registered Name and Email so they won't have to fill them in again. This is my code: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-6"> <div class="box-element" id="form-wrapper"> <form id="form"> <div id="user-info"> <div class="form-field"> <input required class="form-control" type="text" name="name" placeholder="Name" /> </div> <div class="form-field"> <input required class="form-control" type="email" name="email" placeholder="Email" /> </div> </div> <div id="shipping-info"> <hr /> <p>Shipping Information:</p> <hr /> <div class="form-field"> <input class="form-control" type="text" name="address" placeholder="Address" /> </div> <div class="form-field"> <input class="form-control" type="text" name="city" placeholder="City" /> </div> <div class="form-field"> <input class="form-control" type="text" name="county" placeholder="County" /> </div> <div class="form-field"> <input class="form-control" type="text" name="postcode" placeholder="Postcode" /> </div> </div> <hr /> <input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue" /> </form> </div> <br /> <div class="box-element hidden" id="payment-info"> <small>Paypal Options</small> <button id="make-payment">Make Payment</button> </div> </div> <div class="col-lg-6"> <div class="box-element"> <div class="box-element"> … -
Intersection of QuerySet and list of objects
Assume that I have a query set of Product model. products_qs = Product.objects.filter(...) products_list = [<Product 1>, <Product 5>] How can I detect intersection of products_qs and products_list? -
Django returning 500 status code instead of 404 for a not found resources
In my Django project whenever I turn DEBUG to False all my 404 resource not found errors, returns as 500 internal server error. I also don't get a stack trace in my log file for the cause of the error. I just only get internal server error with status code 500. But if DEBUG is set to true, it works fine and I get a 404 not found code for a resource not found error Even some of my static files and images that were not found are all returning 500 internal server error. This happens only when debug is false Works fine when debug is set to true. I read online where allowed host must be set to the actual host and not a "*". I have done all this but it is still not working. I am still getting 500 status code for a resource not found error and no stack trace. I'm using Django 4 python 3.9 -
Django Website Not Displaying Expected Content
I'm new to Django and am building a site for reminders. However, I see a blank page on launch. My base.html has a form for reminders and a display section, index.html has a similar form, and styles.css is for styling. Static paths seem fine, server runs with no errors, and migrations are updated, but still no content. Here's my code: `base.html Reminder FormSet Reminder{% csrf_token %}{{ form.as_p }}Set ReminderReminders{% for reminder in reminders %}{{ reminder.time }} - {{ reminder.title }}: {{ reminder.message }}{% endfor %} ` index.html <form method="post">{% csrf_token %}{{ form.as_p }}<button type="submit">Set Reminder</button></form> styles.css *{margin:0;padding:0;box-sizing:border-box;}body{font-family:'Arial',sans-serif;background-color:#3618bb;color:#4c34a3;}.container{max-width:1200px;margin:0 auto;padding:20px;}h1,h2,h3{margin-bottom:20px;}input[type="text"],input[type="submit"]{padding:10px;margin-bottom:10px;}input[type="submit"]{cursor:pointer;background-color:#333;color:#8b1818;border:none;} Any ideas what's wrong? -
embed video on website using django-embed-video
when run it gives an error: Exception Type: TemplateDoesNotExist at / Exception Value: video.html and also: return render(request,'video.html',{'obj':obj}) views.py: from django.shortcuts import render from .models import Item def video(request): obj = Item.objects.all() return render(request,'video.html',{'obj':obj}) video.html: {% load embed_video_tags %} <!doctype html> <html lang="ru"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Демо Bootstrap</title> </head> <body> <h1>Привет мир!</h1> {% block content %} {% for i in obj %} {% video i.video 'small' %} {% endfor %} {% endblock %} </body> </html> I searched how to fix the error on YouTube and did not find anything -
nginx: serving uwsgi on same port in nginx.conf
I am new to nginx/uwsgi stuff. I have set up nginx to serve static HTML web pages, and uWSGI+DJango for web application. Currently, they are serving at different ports, like: - to access HTML pages: http://my.domain.com/ # port 80 - to access web application: http://my.domain.com:8000/app/** # port 8000 Currently they work fine individually. But my goal is to put them on same port so http://my.domain.com/app/** can access the web applications. Below is the current nginx.conf: ... server { listen 80; location / { root html; } } include conf.d/*.conf; ... Below is conf.d/webapp.conf: upstream django { server unix:///path/to/django/project/webapp.sock; } server { listen 8000; location / { uwsgi_pass django; include /path/to/uwsgi_params; } } Below is uwsgi.ini: [uwsgi] chdir=/path/to/django/project/ module=project.wsgi:application socket=/path/to/django/project/webapp.sock master=True vacuum=True daemonzie=/path/to/django/project/uwsgi.log and uwsgi was started by uwsgi uwsgi.ini. How can I achieve my goal? -
change venv from python 3.5 to python 3.6; Gunicorn does not start
My app on python3.5 works well. But when I make the virtualenv with python3.6 and install the same requirements; Gunicorn doesn't start with below error message in jenkins: + supervisorctl restart myapp myapp: stopped myapp: ERROR (spawn error) and in log file it's written: supervisor: couldn't exec /home/jenkins/myapp/venv/bin/gunicorn: ENOENT supervisor: child process was not spawned Also, the gunicorn package version is 19.8.1. I updated it to 20.0.0 but it doesn't work Any help would be appreciated -
How to install Wagtail 5.1 or above
I am using MacOS. I tried to install Wagtail 5.1 in a venv and I installed pip install wagtail. and wagtail start mysite mysite. Without using cd mysite pip install -r requirements.txt, I directly typed cd mysite and python manage.py migrate. That because I needed to install Wagtail 5.1 and not Wagtail 2.1. But when I tried to python manage.py migrate, It shows many errors including ModuleNotFoundError: No module named ‘wagtail.core’. How could I install Wagtail 5.1 or above as a fresh install? -
Upload images with Django and Whitenoise
i have just deployed a web using Django on Heroku with static files served by whitenoise. All the static files created before deploying works fine but if i want to upload new image (from both admin page and custom form) the image can not be found like below. Any help would be appreciated Can find the image settings.py STATIC_URL = '/staticfiles/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_URL = '/staticfiles/assets/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles/assets/images') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) models.py class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) img = models.ImageField(null=True, default= 'default_product_image.jpg',blank=True) class Meta: verbose_name_plural = "Product Image" I tried uploading from both admin page and form that enable user to upload images but both result the same -
Fetching image using react-pdf <Image> causes CORS issue, whearas it loads fine in React <img>
I've backend built with django and I've installed django-cors-headers to fix cors error. If I try to load images from backend, react is rendering for tag, but fetching image using react-pdf causes CORS error. Here's my react-pdf blank const QRCodeBlank = ({ students }) => ( <Document> <Page style={styles.body}> {students && students.map((student) => ( <View> <Image src={`https://backend.link/media/${student.photo}`} /> <Text>{student.name}</Text> </View> ))} </Page> </Document> ); I've installed django-cors-headers to fix this issue, but there is no any changes. Here's my django settings for django-cors-headers library: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app.apps.AppConfig', 'corsheaders', 'rest_framework', 'rest_framework_simplejwt' ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True -
How do I validate a JWS with a public key
I'm using Saleor and have set up a webhook to my django server. According to their documentation there is in the header a JWS signature using RS256 with payload detached, to verify the signature you can use a public key, which can be fetched from http(s)://<your-backend-domain>/.well-known/jwks.json The JWS is in the format xxx..yyy, so there is no payload, instead the payload is directly in the request.body. The way I have understood JWTs and public keys is that you can verify that the payload is legit by using the token together with the public key to see that the payload was signed with someone using the private key. The problem I have is that I keep getting the exception jwt.exceptions.InvalidSignatureError: Signature verification failed. This is my code: @csrf_exempt @require_http_methods(["POST"]) def saleor_webhook(request): print("Saleor webhook received") jws_token = request.headers.get('Saleor-Signature') response = requests.get(JWKS_URL) jwks = response.json() jwk_dict = jwks['keys'][0] # Convert JWK to PEM public key public_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk_dict)) pem_public_key = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) pem_public_key = pem_public_key.decode("utf-8") # Here is where it fails... decoded = jwt.decode(jws_token, pem_public_key, algorithms=['RS256']) print(decoded) return HttpResponse(status=200) Not sure if this is the right way or not, but I tried to also base64 encode the request.body and put it …