Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why Django migrate command not able to create tables in database for specific app
I've a model named Attendance and it contain following migrations applied in postgresql db. attendance [X] 0001_initial [X] 0002_delete_leave [X] 0003_alter_holiday_options_alter_shift_options [X] 0004_delete_holiday_alter_shift_holidays [X] 0005_delete_shift [X] 0006_initial [X] 0007_alter_leave_options [X] 0008_alter_leave_comment_alter_leave_is_regularized [X] 0009_attendance [X] 0010_alter_attendance_options_attendance_created_at_and_more [X] 0011_attendance_status [X] 0012_attendance_is_regularized [X] 0013_alter_attendance_is_regularized [X] 0014_remove_attendance_date_attendance_start_date_and_more [X] 0015_attendance_end_date [X] 0016_alter_attendance_end_date [X] 0017_alter_attendance_end_date_and_more [X] 0018_leavetype_remove_leave_half_day_and_more [X] 0019_leave_leave_type when I run python manage.py migrate with or without app label it does not create tables in db. I've not set managed=False and tried to delete all migrations from django_migrations table but no luck. -
Why doesn't Django set the cookie when the view is called
I am trying to set and unset a Django cookie based on a form with a checkbox. When the checkbox is checked I would like the cookie to be set. Passing the value of the checkbox to the view is working correctly, but setting and unsetting the cookie is not. This is the view: def filter(request): tasks = list() if request.POST.get('today') == 'yes': tasks.extend(Task.objects(when='today')) print('get tasks today') response = render(request, 'index.html', {'tasks': tasks}) if request.POST.get('today') == 'yes': response.set_cookie('today', 'yes') print('set cookie today') else: response.set_cookie('today', 'no') print('cookie not set today') return response Whether or not to set the cookie is determined by this code: {{request.COOKIES.today}} <form action="filter" method="POST"> {% csrf_token %} <input type="checkbox" name="today" value="yes" {% if request.COOKIES.today == 'yes' %}checked{% endif %}> Today</div> <input type="submit" value="Show" class="btn btn-warning col-12 btn-sm"/> </form> In my template I use {{request.COOKIES.today}} to check the value of the cookie. What's happening is strange. If I click the checkbox the cookie is not set, as I expect it to be and the checkbox is not checked when the page reloads. But if I select the checkbox again, then the cookie is set and the checkbox is selected. Am I making a mistake somewhere, or missing something. … -
Design for a Contest-Oriented Platform - Handling Shared Kernel
I'm creating a HackTheBox-like platform with Django using Domain-Driven Design. It supports both individual and enterprise users who can solve challenges and participate in contests. Enterprise members also have exclusive challenges and contests. My system is divided into four Django apps: Users, Enterprises, Challenges, and Contests, each handling related tasks. I plan to treat challenges as a shared kernel accessed by both Users and Enterprises apps. However, I'm uncertain how a user can retrieve and solve a challenge within this design. Am I structuring these Django apps effectively for my requirements? How can I manage a shared kernel for challenges to let users retrieve and solve them? Any key endpoints missing? Any advice is appreciated. Thanks! -
solr search in Django application
There are questions in database. Solr search is giving results, but I want the ranking of the questions based on the text I'm searching. But search giving results based on id's of the questions. In solr.xml file I have the schema based on that indexing is happening. What should i do the xml file to get the search results based on ranking. -
How to display filtered data in serializer's source attribute Django Rest Framework
I've added an additional action to my ModelViewSet as below. I have a manager function which it's name is related_interests and it should filter the user interests. I put source attribute to my serializer to get filtered interests however, I'm getting all of them in my response. class MyModelViewSet( viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin ): """ModelViewSet with create, list, retrieve and custom_action operations""" queryset = MyModel.objects.all() serializer_class = serializers.MyModelSerializer @action(detail=False, methods=['post']) def custom_action(self, request): queryset = MyModel.objects.related_interests() serializer = self.serializer_class(queryset, many=True) return responses.http_ok_with_dict(serializer.data) And here is my serializer; class UserWithInterestSerializer(serializers.ModelSerializer): licenses = InterestSerializer(read_only=True, source="interest_set", many=True) class Meta: model = User fields = "__all__" class MyModelSerializer(serializers.ModelSerializer): user = UserWithInterestSerializer(read_only=True) class Meta: model = MyModel fields = ["user"] How can I fix this issue? Thanks! -
How to run async tests in django?
I use async django views and async test cases accordingly. When I run tests separately by one test cases it works okay, but when I run a batch of tests I get error: RuntimeError: Task <Task pending name='Task-139' coro=<AsyncToSync.main_wrap() running at /opt/venv/lib/python3.11/site-packages/asgiref/sync.py:353> cb=[_run_until_complete_cb() at /usr/local/lib/python3.11/asyncio/base_events.py:180]> got Future attached to a different loop According to django docs "Django will automatically detect any async def tests and wrap them so they run in their own event loop." So I guess there is some loops conflict? Maybe anyone knows how to fix this error or any patch how to run many async tests in django? -
Django multiuser
this it the review model on my movie project class Parent(models.Model): title=models.CharField(max_length=50,blank=True,null=True) # slug=models.SlugField(max_length=50,unique=True,default=title) user=models.ForeignKey(User,on_delete=models.CASCADE,default='user') movie=models.ForeignKey(Movie,on_delete=models.CASCADE) date=models.DateField(auto_now_add=True) score=models.IntegerField(blank=True,null=True) review=models.TextField(max_length=5000,blank=True,null=True) class Meta: abstract=True def __str__(self): return self.title class Audience_Review(Parent): pass And this is my syntax for displaying the movie review. def view_movie(request,mslug): status='' user=request.user movie=Movie.objects.get(slug=mslug) watchlist=Watchlist.objects.all() reviews=Audience_Review.objects.filter(movie=movie) return render(request,'moviesingle.html',{'mov':movie,'watchlist':watchlist,'review':reviews}) What changes i should make for changing this as a multi user program. Example: if i post a review from user A and then logged on to user B, the review is showing as written by B (the current logged in user), I need to show it as written by A (the user who post the review) even when logged as another user.I tried to filter the syntax by user, but then it wont show while logged as another user. Also need to take personal score from each user and calculate the average score by calculating all ratings from different users for the same movie. -
I've got problems pipenv installing django
pipenv install django get erreor OSError: [WinError 1920] Systemet kan ikke få adgang til filen(System can't acces): 'C:\Users\Bruger\AppData\Local\Microsoft\WindowsApps\python.exe\Scripts. I have tryed to move Python from C: to D:, tryed to make a path to pipenv, turned of virusprogram.This is an image of windows app folder (https://i.stack.imgur.com/tOwYn.png) -
Page not found (404) error in my django site
i have created a school dashboard system site..here i have given some usrls most of them are working fine just two of them are not working. These are my urls urlpatterns = [ path('admin/', admin.site.urls), path('',views.home_view,name=''), path('adminclick', views.adminclick_view), path('teacherclick', views.teacherclick_view), path('studentclick', views.studentclick_view), path('adminsignup', views.admin_signup_view), path('studentsignup', views.student_signup_view,name='studentsignup'), path('teachersignup', views.teacher_signup_view), path('adminlogin', LoginView.as_view(template_name='school/adminlogin.html')), path('studentlogin', LoginView.as_view(template_name='school/studentlogin.html')), path('teacherlogin', LoginView.as_view(template_name='school/teacherlogin.html')), path('afterlogin', views.afterlogin_view,name='afterlogin'), path('logout', LogoutView.as_view(template_name='school/index.html'),name='logout'), path('admin-dashboard', views.admin_dashboard_view,name='admin-dashboard'), path('admin-teacher', views.admin_teacher_view,name='admin-teacher'), path('admin-add-teacher', views.admin_add_teacher_view,name='admin-add-teacher'), path('admin-view-teacher', views.admin_view_teacher_view,name='admin-view-teacher'), path('admin-approve-teacher', views.admin_approve_teacher_view,name='admin-approve-teacher'), path('approve-teacher/<int:pk>', views.approve_teacher_view,name='approve-teacher'), path('delete-teacher/<int:pk>', views.delete_teacher_view,name='delete-teacher'), path('delete-teacher-from-school/<int:pk>', views.delete_teacher_from_school_view,name='delete-teacher-from-school'), path('update-teacher/<int:pk>', views.update_teacher_view,name='update-teacher'), path('admin-view-teacher-salary', views.admin_view_teacher_salary_view,name='admin-view-teacher-salary'), path('admin-student', views.admin_student_view,name='admin-student'), path('admin-add-student', views.admin_add_student_view,name='admin-add-student'), path('admin-view-student', views.admin_view_student_view,name='admin-view-student'), path('delete-student-from-school/<int:pk>', views.delete_student_from_school_view,name='delete-student-from-school'), path('delete-student/<int:pk>', views.delete_student_view,name='delete-student'), path('update-student/<int:pk>', views.update_student_view,name='update-student'), path('admin-approve-student', views.admin_approve_student_view,name='admin-approve-student'), path('approve-student/<int:pk>', views.approve_student_view,name='approve-student'), path('admin-view-student-fee', views.admin_view_student_fee_view,name='admin-view-student-fee'), path('admin-attendance', views.admin_attendance_view,name='admin-attendance'), path('admin-take-attendance/<str:cl>', views.admin_take_attendance_view,name='admin-take-attendance'), path('admin-view-attendance/<str:cl>', views.admin_view_attendance_view,name='admin-view-attendance'), path('admin-fee', views.admin_fee_view,name='admin-fee'), path('admin-view-fee/<str:cl>', views.admin_view_fee_view,name='admin-view-fee'), path('admin-notice', views.admin_notice_view,name='admin-notice'), path('teacher-dashboard', views.teacher_dashboard_view,name='teacher-dashboard'), path('teacher-attendance', views.teacher_attendance_view,name='teacher-attendance'), path('teacher-take-attendance/<str:cl>', views.teacher_take_attendance_view,name='teacher-take-attendance'), path('teacher-view-attendance/<str:cl>', views.teacher_view_attendance_view,name='teacher-view-attendance'), path('teacher-notice', views.teacher_notice_view,name='teacher-notice'), path('student-dashboard', views.student_dashboard_view,name='student-dashboard'), path('student-attendance', views.student_attendance_view,name='student-attendance'), path('aboutus', views.aboutus_view), path('contactus', views.contactus_view), ] These two urls are making errors- path('admin-dashboard', views.admin_dashboard_view,name='admin-dashboard'), path('admin-teacher', views.admin_teacher_view,name='admin-teacher'), this is the error m getting- Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin-dashboard/ -
How to create the function and pass it into the context using extra_context in the template [closed]
I'm trying to do what this Article says, and the answer says to simply create a function to do this. How would I go about that? I have tried creating a function that gets the requests from the form and getting the foreign key with the same id but I can not seem to make it work. Thanks(: -
How to Index over Filtered set of a model through elasticsearch_dsl 's Persistence API
This is my code documents.py code class Blog(Document): title = fields.TextField() date_posted = fields.DateField() class Index: name = "blog_index" settings = {"number_of_shards": 1, "number_of_replicas": 0} class Django: model = Blog fields = ['title','date_posted'] This is my models.py code class Blog(models.Model): """ Blog Model fields are defined here """ title = models.CharField(max_length=255, null=True) date_posted = models.DateField(blank=True, null=True) But I don't want to populate all of my objects of Blog, I only want to populate those objects who are getting passed with these filter example filter = Blog.objects.filter(title__isnull=False).distinct() -
how to make changing link upload_to imagefield in django
in my product model there is a category field, it refers to another table, in the category table there is a title field, I would like each image to be saved in a folder with the name of the corresponding category__title class ProductImage(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='...') product = models.ForeignKey(Product, on_delete=models.CASCADE) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) class Category(models.Model): title = models.CharField(max_length=150, verbose_name='title', unique=True) -
Django Sending Mail to smtp.office365.com fails with [Errno 8] nodename nor servname provided, or not know
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = smtp.office365.com EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = env.str("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = env.str("EMAIL_HOST_PASSWORD") SERVER_EMAIL = env.str("SERVER_EMAIL") DEFAULT_FROM_EMAIL = env.str("DEFAULT_FROM_EMAIL") The system errors with ../3.10/lib/python3.10/socket.py", line 955, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 8] nodename nor servname provided, or not known The strange part is this configuration worked until a week ago. The system has been solid and error free since March and just last week all email started failing. Fails from my local machine, fails from my dev server and also fails from my prod server and there has been no code pushes to prod in 2 months. So something must have changed with o365? I have changed my mail server to sendgrid and the code functions just fine. Does anyone have any advice on how to further troubleshoot this? Microsoft is useless. Says is its my DNS. Which is incorrect because this is a linux machine running in Azure and will resolve everything else including a telnet on port 587 to smtp.office365.com. -
Implementing Secure Server-Level Authentication for Django Web Service on IIS with MS Power Automate
I have a Django web service hosted on IIS (Internet Information Services) that is frequently invoked by Power Automate (formerly Microsoft Flow). However, I'm facing challenges when trying to integrate Power Automate with the Django web service using Windows Authentication. The objective is to ensure that Power Automate can securely access the API endpoints of the Django web service, but at the same time, I want to avoid storing any plain text passwords on the server and disable Anonymous Authentication. I'm seeking guidance from the Stack Overflow community on how to overcome these challenges and implement a secure solution for integrating Power Automate with the Django web service using Windows Authentication. Specifically, I'd like to understand: Configuring IIS for Windows Authentication: What are the necessary steps to enable and configure Windows Authentication in IIS to authenticate Power Automate requests? Credential management best practices: Since storing plain text passwords is not an option, what are the recommended methods for securely managing and authenticating with the Django web service without exposing sensitive information? Handling Power Automate integration: Are there any specific considerations or adjustments needed in the Django web service to seamlessly integrate with Power Automate using Windows Authentication? Thank you for … -
403 error with azure app service and custom domain
Deploying an Azure web app with database, when accessing the site from my custom domain, I get a 403 error but not when accessing the site from the azurewebsites.net url. App is written in Python with the Django framework and using a Postgresql database. What can I do to resolve the 403? I've passed the custom domain variable in the configuration and added to ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS. I've passed the custom domain variable in the configuration and added to ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS -
Django: Getting a DoesNotExist exemption on the terminal but data is selected
I'm working on project 4 for CS50W (network). I have a weird issue I just noticed: urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create_post", views.create_post, name="create_post"), path("<str:username>", views.profile, name="profile") ] view giving problem: def profile(request, username): user = User.objects.get(username=username) posts = Post.objects.filter(owner=user).order_by('-timestamp') print(f'Current username: {user.username} ({user.email})') return render(request, 'network/profile.html', { 'username': user, 'followed': user.followers.filter(username=request.user.username), 'posts': posts }) Terminal log: **Current username: FernandoBorea (fernando@email.com)** [26/Jul/2023 00:40:25] "GET /FernandoBorea HTTP/1.1" 200 2651 Internal Server Error: /favicon.ico Traceback (most recent call last): File "/home/fernandoborea/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/fernandoborea/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fernandoborea/studies/CS50W/TestingCICD/project4/cs50w-project4/network/views.py", line 104, in profile user = User.objects.get(username=username) File "/home/fernandoborea/.local/lib/python3.10/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/fernandoborea/.local/lib/python3.10/site-packages/django/db/models/query.py", line 637, in get raise self.model.DoesNotExist( network.models.User.DoesNotExist: User matching query does not exist. [26/Jul/2023 00:40:26] "GET /favicon.ico HTTP/1.1" 500 71927 As you can see, the user variable does get a User instance back as it is printed to the terminal and everything on the site works perfectly, but I have no idea why I'm getting the error reported on the terminal. Another strange … -
docker compose changing ownership to root
Running into an issue where the following will change the ownership of all files within the folder: docker compose run --rm app django-admin startproject core . It's changing the ownership to 999:myself. I'm running this from the myself:myself account, or 1000:1000. I tried defining the user with the following, but it seems the --user flag is no longer available --user $(id -u):$(id -g) I am in the docker group and not executing anything as root (though I know docker does). I do not see anything in the docs that allow me to specify the UID\GID. Using python:3.11.4-alpine3.18 Docker version 24.0.4 If I reassign ownership to whom it should be, the docker compose up just reassigns it back to 999:myself. How do I work around this? -
Django MSSQL Cannot insert explicit value for identity column in table 'tblSORequestFromEmail' when IDENTITY_INSERT is set to OFF
When I run this on an external database SORequestFromEmail.objects.create(subject='test') I get this error, why is that? django.db.utils.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot insert explicit value for identity column in table 'tblSORequestFromEmail' when IDENTITY_INSERT is set to OFF. (544) (SQLExecDirectW)") I was not even specifying a value for the ID in the query, see below for model definition class SORequestFromEmail(models.Model): id = models.IntegerField(primary_key=True, db_column='ID') fromemail = models.TextField(db_column='FromEmail', blank=True) fromname = models.TextField(db_column='FromName', blank=True) subject = models.TextField(db_column='Subject', blank=True) description = models.TextField(db_column='TextDescription', blank=True) cc = models.TextField(db_column='CC', blank=True) datetimereceived = models.DateTimeField(db_column='DateTimeReceived') class Meta: db_table = u'tblSORequestFromEmail' -
How to open files outside of the django project?
I am building a django view which return the name of the town given the longitude and lattitude passed in an HTTP request. To performs these computations, I wrote a function that needs to open a Geojson file located outside the django project. This function in the same file as the view : /home/erwan/Images/eosya_app/backend/api/municipality/compute_municipality_view.py In this function, I perform the following open but django does not find the file. with open('../../../database/unparsed_data/administrative_boundaries/my_file.geojson','r') as f: I made some research and learn that I have to define a base directory path in the settings to be able to access external files. I added the following line to my setting.py : BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) FILES_DIR = os.path.abspath(os.path.join(BASE_DIR, '../database/unparsed_data')) I updated the file path accordingly in my function : file_path = os.path.join(settings.FILES_DIR, '/administrative_boundaries/france-geojson-master/departements.geojson') But django is still unable to find the file. Additionnaly the print does not match the expected path. It look like the FILE_DIR is not taken into account. Here is the result of the print : /administrative_boundaries/france-geojson-master/departements.geojson I also tried to verify my project root path, without success : print(settings.SITE_ROOT) AttributeError: 'Settings' object has no attribute 'SITE_ROOT' What am I doing wrong and how to access my geojson file in this function … -
How to insert a Python script into a website with DJango?
I'm absolutely new to DJango. I'm trying to make the user input text into a HTML textbox, then transform that text in Python and output it on the website.I've fiddled around with the documentation and MDN's tutorial but couldn't get it to work. 1) How do I "point" my DJango files to function on my website? 2) Where do I insert the Python code? 3) How do I receive input/send output from/to the website? I can't simply use JS for this because I need to use an API that is only available for Python. -
HTTPSConnectionPool Max retries exceeded with url Failed to establish a new connection: [Errno 111] Connect when running on server,but not on local PC
When I run this code in the local system, I get an answer easily, but when I put it on the host, I get an error. HTTPSConnectionPool(host='test.com', port=8000): Max retries exceeded with url: /api1 (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7fb28512da90>: Failed to establish a new connection: [Errno 111] Connection refused')) import json import http.client from django.shortcuts import render, HttpResponseRedirect from django.urls import reverse from django.contrib import messages from .forms import RegisterForm from .models import MyUser def register_view(request): if request.user.is_authenticated: return HttpResponseRedirect(reverse('account:dashboard')) form = RegisterForm() if request.method == "POST": mobile = request.POST.get('mobile') user_national = request.POST.get('input-natiionalID') try: if "mobile" in request.POST: user = MyUser.objects.get(mobile=mobile) messages.error(request, "شماره موبایل تکراری می باشد و قبلا ثبت شده است") return HttpResponseRedirect(reverse('account:register_view')) # Send OTP except MyUser.DoesNotExist: form = RegisterForm(request.POST) if form.is_valid(): try: user = form.save(commit=False) # Send OTP otp = helper.get_random_otp() # helper.send_otp(mobile, otp) # Save OTP za = national_code_check(user_national) user.otp = otp user.code_nationality = request.POST.get('input-natiionalID') user.is_active = False if za == True: # Make an HTTP POST request to the API user_name = "test" password = "test" national_identification_number = user.code_nationality phone_number = user.mobile api_url = "mysite.com" api_port = 8000 api_path = "/api1" payload = { 'username': user_name, 'password': password, 'national_mobile': phone_number, 'national_identification_number': national_identification_number, } payload_json … -
ORM / Template organization
I have 4 models.. let's say: Modal BigBox: small_boxes = ManyToMany ..... Model SmallBox ..... Model Item ..... Model Big_box_small_box_items: big_box = fk(BigBox) small_box = fk(SmallBox) Item = fk(Item) ..... In my template I want to go to a template for a big box and see a list of items in each small box. I have a working page now but it involves lost of nesting logic inside the view and an inefficient number of database hits. My head is swimming a bit as a hobbyist and I would appreciate any pointers. -
input date is not saved while all other inputs are saved
due_date input is not saved after submitting the form / POST. Nothing is registered in the DB but no error is shown in the console as well. All data are saved except the due_date input, I do not understand where is the error. I tried hundreds possibilities but all of them failed. I appreciate million times your help. Thank you !! Model from datetime import date from django.db import models from django.contrib.auth.models import User class Todo(models.Model): title = models.CharField(max_length=100) memo = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) due_date = models.DateField(null=True, blank=True) datecompleted = models.DateTimeField(null=True, blank=True) important = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title Form from django import forms from .models import Todo class TodoForm(forms.ModelForm): class Meta: model = Todo fields = ['title', 'memo', 'due_date', 'important'] due_date = forms.DateField( widget=forms.DateInput(format='%m/%d/%Y'), input_formats=('%m/%d/%Y', ) ) view @login_required def createtodo(request): if request.method == 'GET': return render(request, 'todo/createtodo.html', {'form':TodoForm()}) else: try: form = TodoForm(request.POST) newtodo = form.save(commit=False) newtodo.user = request.user newtodo.save() return redirect('currenttodos') except ValueError: return render(request, 'todo/createtodo.html', {'form':TodoForm(), 'error':'Bad data passed in. Try again.'}) HTML Form <form method="POST"> {% csrf_token %} <div class="form-group"> <label for="title">Title</label> <input type="text" name="title" class="form-control" id="title" required> </div> <div class="form-group"> <label for="due_date">Due</label> <input type="date" class="form-control" id="due_date" value="{{todo.due_date}}"> </div> <div … -
502 Gateway error - ngnix on django application
I have an already running sites one is the main (user-facing) and one staging website. They're in django and have been running for years, but during one of my builds i started encountering a "502 bad gateway error" when I clicked on some of the pages. The changes I made were not towards any of the ngnix configs or even server changes. Before it used to run smoothly. However this issue remains on Chrome (works fine on safari) and when i clear cache on chrome it starts to work again for around 10 minutes and then something or the other gives bad gateway. Also if i copy paste the link into a different chrome profile it'll probably work and vice versa. (the different profiles on chrome don't have any different extension or different setting..). It honestly seems random and i don't know how to solve this at all. Any help/ tips would be appreciated -
Microsoft Graph API, cant retrieve profile picture with django
I'm having the issue that requesting the photo from the Microsoft Graph API does not retrieve the photo and actually returns a 404 error. xff/xd8/xff/xe0/x00/x10JFIF/x00/x01/x01/x01/x00%60/x00%60/x00/x00/xff/xdb/x00C/x00/x08/x06/x06/x07/x06/x05/x08/x07/x07/x07/t/t/x08/n/x0c/x14/r/x0c/x0b/x0b/x0c/x19/x12/x13/x0f/x14/x1d/x1a/x1f/x1e/x1d/x1a/x1c/x1c%20$./'%20%22, i get this is the base64 decoded jpeg, however i cant figure out how to use it to actually display an image in a html page. Here is the code in my views that is creating the request, which is in my initialize context view: def initialize_context(request): ## non relevant code ## graph_photo_endpoint = 'https://graph.microsoft.com/beta/me/photo/$value' headers = {'Authorization': 'Bearer ' + token} photo_response = requests.get(graph_photo_endpoint, headers=headers) if photo_response.status_code == 200: context['photo_data'] = photo_response.content photo_response.headers['Content-Type'] = 'image/jpeg' ## non relevant code ## return context Which is retrieved by my view that needs to load the photo, which the user needs to be signed in for to access: @azure_ad_login_required def profile(request): context = initialize_context(request) return render(request, 'profile.html', context) Here is the html code to define the photo: <img class="profile_pic" src="{{ photo_data }}" alt="Profile Picture" style="width:100%"> And this is what my graph_helper looks like: import requests import base64 from requests_oauthlib import OAuth2Session graph_url = 'https://graph.microsoft.com/v1.0' def get_user(token): # Send GET request to retrieve user information from Microsoft Graph API user = requests.get('{0}/me'.format(graph_url), headers={'Authorization': 'Bearer {0}'.format(token)}, params={'$select': 'displayName,mail,mailboxSettings,userPrincipalName,givenName,companyName,surName,jobTitle'}) user.headers['Content-Type'] …