Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
google declined when i try to send email confirmation in django
This is the error when I try to send an email confirmation, any help rather than enabling a less secured app thank you (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials kw21-20020a170907771500b00731219a2797sm3559534ejc.210 - SMTP) -
How can I make django require a data migration when a condition changes?
I have a table containing a list of subclasses of a certain class in my django app. How can I make django require a data migration when this table is edited ? Is there some exception I can raise if django is started and one of these classes isn't in the table ? I'd also like to be able to hook into makemigrations so I can generate the correct data migration if possible. -
Docker doesn't see the table in the database after django migration
A Django project can be run in two ways: python manage.py runserver and using docker compose docker-compose up --build If run it the standard way (without docker), it works. If run it with docker, get an error that the database doesn't have the table relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... There are two containers gpanel_gpanel_1 and gpanel_db_1 I have tried migrations in 3 ways python manage.py migrate and docker-compose exec gpanel_db_1 python manage.py migrate and docker-compose exec gpanel_gpanel_1 python manage.py migrate And the last two methods did not display any information about the migration application in the console I also deleted the volumes gpanel_db_1 gpanel_gpanel_1 and re-created the container. But the error is still there. docker-compose.yaml version: "3.9" services: gpanel: restart: always build: . ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/gpanel depends_on: - db environment: - DB_HOST=db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} volumes: postgres_data: -
Python based HMI (communication between python-script and webapp)
I build a machine for quality-checking of assembled parts by capturing images and running a SVM on them. It's written in Python. Right now it's used via command line and displaying the captured images and inference-results in an OpenCV-Window. The main.py also handles other stuff like camera-communication and stepper-motor-control. Now I want to move the prototype to production so it has to be more user friendly. This means I need a webapp as Human-Machine-Interface. For now it just needs a button for the user to start the quality-check (trigger a function) and to display the momentary state ("moving", "idle", "error", "checking" etc.) as well as the resulting image. My initial approach is to just keep the main.py idle-ing until the start-button is pressed. But what would be the best way to interact between the webapp and the main.py? Would Websockets make sense? (I have never used them, just read about it) Or RESTAPI? I originally am a mechanical engineer, just self-taught the necessary python-skills for the task, so it's a little hard for me to properly describe the problem ;) Thanks! -
Django: Couldn't import Django, But django is installed (checked with django-admin --version, returns 4.1)
So i tried this: py manage.py runserver And got this error: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The virtual environmeent is activated (I have a little (venv) next to the path). Thing is, I just reinstalled django-admin via the virtual environment. Not only that but I did django-admin --version And got the result 4.1 Clearly it is installed. I can import django in IDLE just fine, but it won't run manage.py for some godforsaken reason. Any idea on how to fix this? -
How to get MIME type of FileField in DRF and send to parameters?
i hope everyone is good. I want to send mime type of the FileField in drf. but i dont know how to... { "id": 1, "document": "http://127.0.0.1:8000/images/articles_auth_with_user_eZUJmTW.png", "filesize": "239.55 KB", "filename": "articles_auth_with_user_eZUJmTW.png" "mimetype": "" }, This is response i am sending. I want to send mime type here... class DocumentModel(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID") document=models.FileField() class Meta: verbose_name_plural="Documents" ordering=["document"] def __str__(self): return f'{self.document}' @property def filesize(self): x = self.document.size y = 512000 if x < y: value = round(x / 1024, 2) ext = ' KB' elif x < y * 1024: value = round(x / (1024 * 1024), 2) ext = ' MB' else: value = round(x / (1024 * 1024 * 1024), 2) ext = ' GB' return str(value) + ext @property def filename(self): return self.document.name Above is my models file class DocumentSerializer(serializers.ModelSerializer): class Meta: model=DocumentModel fields = ['id', 'document', 'filesize', 'filename'] This is serializer code. Please kindly help ... -
How to let WebSocket in React through Content Security Policy on a deployed server
I am currently using Websockets in React to connect to Django channels. It works locally, but on a deployed server I get the following error, "Refused to connect to 'WEBSOCKET_URL' because it violates the following Content Security Policy directive: "default-src https: data: 'unsafe-inline' 'unsafe-eval'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback." I have tried the meta tag 'meta http-equiv="Content-Security-Policy" content="content-src 'self' ws://URL" /' but my login starts violating the Content Security Policy. Is there a way to add the websocket to the CSP without it interfering with other functions? -
Django/Flask : Rewritting an Flask Azure B2C authentication in Django
I want to use and Azure B2C authentication in Django, however there is no tutorial in Django for it but in Flask. However I never coded in Flask. I used the documentation/tutorial of microsoft that share a github with the flask code to do it : https://docs.microsoft.com/en-us/azure/active-directory-b2c/configure-authentication-sample-python-web-app?tabs=windows https://github.com/Azure-Samples/ms-identity-python-webapp I try to convert it in Django however I have an error that I do not understand ! The error message : Internal Server Error: /login/ TypeError: Object of type HttpResponseRedirect is not JSON serializable Here is the code views.py def index(request) : if not request.session.get("user"): return redirect("login") return render('index.html', user=request.session["user"] ) def login(request): # Technically we could use empty list [] as scopes to do just sign in, # here we choose to also collect end user consent upfront request.session["flow"] = _build_auth_code_flow(scopes=list(json.loads(os.getenv("SCOPE")))) return render(request, "login.html", {'auth_url' : request.session["flow"]["auth_uri"]}) def authorized(request): try: cache = _load_cache(request=request) result = _build_msal_app(cache=cache).acquire_token_by_auth_code_flow( request.session.get("flow", {}), request.args) if "error" in result: return render("auth_error.html", result=result) request.session["user"] = result.get("id_token_claims") _save_cache(cache=cache, request=request) except ValueError: # Usually caused by CSRF pass # Simply ignore them return redirect("index") def _load_cache(request): cache = msal.SerializableTokenCache() if request.session.get("token_cache"): cache.deserialize(request.ession["token_cache"]) return cache def _save_cache(cache, request): if cache.has_state_changed: request.session["token_cache"] = cache.serialize() def _build_msal_app(cache=None, authority=None): return msal.ConfidentialClientApplication( os.getenv("CLIENT_ID"), authority=authority … -
Админка Django не обрабатывает Html теги для постов приложения
Создал приложение на Django, которое выводит посты на сайт. Когда пишу в админке теги html, по типу strong или em и т.д. во время создания поста. Оно так и выводится, то есть не интерпретируется. Как решить данную проблему? -
Docker database does not exist
I am developing using docker in a Django project. For this project I need multiple PostgreSQL database live at the same time to work. So, I put in the env file all the current settings: DB_ENGINE="django.db.backends.postgresql_psycopg2" POSTGRES_USER="zwap_user_settings_db" POSTGRES_DB="zwap_user_settings_db" DB_HOST="zwap_user_settings_postgres" DB_PORT="5432" POSTGRES_PASSWORD=zwap_settings_postgres_db And I created the docker-compose.yml file to create all the needed postgresql instance at once version: '3.7' services: ... zwap_settings_postgres: container_name: zwap_user_settings_postgres image: postgres ports: - 6003:5432/tcp environment: - POSTGRES_USER=zwap_user_settings_db - POSTGRES_PASSWORD=zwap_settings_postgres_db - POSTGRES_DB=zwap_user_settings_db volumes: - zwap_settings_postgres:/var/lib/postgresql/data/ ... volumes: ... zwap_settings_postgres: So, I try to run the Django project and this error occurs: django.db.utils.OperationalError: FATAL: database "zwap_user_settings_db" does not exist and this error appears also in the docker terminal. But I don't understand where is the error. The code is the same everywhere. Maybe it is simply a silly thing that needs to be changes. IF someone knows how to fix, please help me. Thank you -
Secure storage of passwords in the database with the possibility of obtaining the original password?
The user can add his account from a third-party service (login, password), which is the best way to store the password in the database with the possibility of obtaining the original password in the future. -
How pass data from template to Updateview
I'm very new to programming. I would like to pass data from html input to update view and then save it to my database. Tried to search for it but with no luck. Here is my html code: <form action="{% url 'darbai:taskasupdate' pk=taskas.pk %}" method="POST"> {% csrf_token %} <input type="text" name="pavad"> <input type="text" name="atsak"> <button type="submit"/>Update</button> </form> Here is my model: class Taskas(models.Model): pavadinimas = models.CharField(max_length=30, null=True, blank=True) atsakingas = models.CharField(max_length=30, null=True, blank=True) Here is my urls: urlpatterns = [ path('', CreateList.as_view(), name='CreateList'), path('delete/<int:pk>', TaskasDeleteView.as_view(), name='taskasdelete'), path('update/<int:pk>', TaskasUpdateView.as_view(), name='taskasupdate'), ] Here is my view: class TaskasUpdateView(UpdateView): model = Taskas form_class = TaskasForm success_url = reverse_lazy('darbai:CreateList') def post(self, request, **kwargs): self.object = self.get_object() request.POST['pavad'] = self.object.pavadinimas request.POST['atsak'] = self.object.atsakingas -
How to pull variables of the main class from a subclass in django
I have a filter code for the site: def buy_files(request): bdfiles = FeedFile.objects.all() # bdfiles = UploadFile.objects.all() form = FileFilterForm(request.GET) if form.is_valid(): if form.cleaned_data["number_course"]: bdfiles = bdfiles.filter(number_course = form.cleaned_data["number_course"]) if form.cleaned_data["number_semestr"]: bdfiles = bdfiles.filter(number_semestr = form.cleaned_data["number_semestr"]) if form.cleaned_data["subjectt"]: bdfiles = bdfiles.filter(subjectt = form.cleaned_data["subjectt"]) if form.cleaned_data["type_materials"]: bdfiles = bdfiles.filter(type_materials = form.cleaned_data["type_materials"]) if form.cleaned_data["institute"]: bdfiles = bdfiles.filter(institute = form.cleaned_data["institute"]) return render(request, 'chat/files/buyfile.html', {'bdfiles': bdfiles, 'form':form}) And models.py: class UploadFile(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE,related_name='file_created' ,verbose_name='Автор') title = models.CharField(max_length=200, verbose_name='Заголовок') # uploadedfile = models.FileField(upload_to='files/',null=True, verbose_name='Файл') description = models.TextField(blank=True, verbose_name='Описание') createdtime = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания') price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена') number_course = models.IntegerField(null=True, blank=True, verbose_name='Курс') number_semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр') subjectt = models.CharField(max_length=200, null=True,verbose_name='Предмет') type_materials = models.CharField(max_length=200,null=True, verbose_name='Тип работы') institute = models.CharField(max_length=200, null=True, verbose_name='Институт') def __str__(self): return self.title class Meta: verbose_name = 'Загрузка файла' verbose_name_plural = 'Загрузка файлов' class FeedFile(models.Model): file = models.FileField(upload_to="files/") feed = models.ForeignKey(UploadFile, on_delete=models.CASCADE) When I start entering data in the filter on the html page, an error occurs that there are no fields number_semestr, number_course and so on, but there are only fields feed, feed_id, file, id. HTML code of the page: <form action="" method="get" style="width:90%"> {% csrf_token %} <!-- {{form|crispy}}--> <p><label class="form-label" for="{{ form.number_course.id_for_label }}">Курс: </label> … -
DRF Authentication is not working in frontend
So, I created registration app. I added registration API, Login API and User profile API. I tested three API's in Postman it is giving results. In my project I used djangorestframework-simplejwt authentication. When I test with browser it is not working what I have to do please anyone can help me out to achieve this. In settings.py # JWT Configuration REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } # JWT Settings SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=20), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', } INSTALLED_APPS = [ ......... 'rest_framework_simplejwt', ......... ] In Views.py class UserLoginView(APIView): def post(self, request, format=None): q = QueryDict(request.body) query_dict = q.dict() json_object = json.dumps(query_dict, indent=4) reqBody = json.loads(json_object) email = reqBody['email'] password = reqBody['password'] user = authenticate(email=email, password=password) print('user') print(user) if user is not None: token = get_tokens_for_user(user) Account = customer.objects.get(email=email) request.session['email'] = Account.email request.session['id'] = Account.id request.session['name'] = Account.firstname request.session['cust_status'] = Account.cust_status request.session['os_name'] = Account.os_name request.session['user_type'] = Account.flag request.session['username'] = str(Account.firstname) + str(Account.lastname) return Response({'token': token, 'msg': 'Login Success'}, status=status.HTTP_200_OK) else: return Response({'errors': {'non_field_errors': ['Email or Password is … -
How to Join Subqueries in Django ORM
I'm a beginner Django and I have been stuck on the following problem for a while. The basic thing I would like to achieve is that when client makes a GET list api request with a time period parameter (say 3 months) then the server would return an aggregation of the current 3 months data and also show an extra field comparing the difference with previous 3 months. I have models as: class NTA(models.Model): nta_code = models.CharField(max_length=30, unique=True) ... class NoiseComplaints(models.Model): complaint_id = models.IntegerField(unique=True) created_date = models.DateTimeField() nta = models.ForeignKey( NTA, on_delete=models.CASCADE, to_field='nta_code') ... The sample output I would like to get is something like: [ { "id": 1, "nta_code": "New York", "noise_count_current": 30, # this would be current 3m count of NoiseData "noise_count_prev": 20, # this would be prev 3m count of NoiseData "noise_count_diff": 10, # this would be prev 3m count of NoiseData } ... The raw SQL query (in Postgres) is quite simple as below but I'm really struggling on how to make this work in Django. WITH curr AS ( SELECT "places_nta"."id", "places_nta"."nta_code", COUNT("places_noisecomplaints"."id") AS "noise_count_curr" FROM "places_nta" INNER JOIN "places_noisecomplaints" ON ("places_nta"."nta_code" = "places_noisecomplaints"."nta_id") WHERE "places_noisecomplaints"."created_date" BETWEEN '2022-03-31 00:00:00+00:00' AND '2022-06-30 00:00:00+00:00' GROUP BY "places_nta"."id" … -
Multiple container app: execute container from another container
I have a multi container Django app. One Container is the database, another one the main webapp with Django installed for handling the front- and backend. I want to add a third container which provides the main functionality/tool we want to offer via the webapp. It has some complex dependencies, which is why I would like to have it as a seperate container as well. It's functionality is wrapped as a CLI tool and currently we build the image and run it as needed passing the arguments for the CLI tool. Currently, this is the docker-compose.yml file: version: '3' services: db: image: mysql:8.0.30 environment: - MYSQL_DATABASE=${MYSQL_DATABASE} - MYSQL_USER=${MYSQL_USER} - MYSQL_PASSWORD=${MYSQL_PASSWORD} - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} - TZ=${TZ} volumes: - db:/var/lib/mysql - db-logs:/var/log/mysql networks: - net restart: unless-stopped command: --default-authentication-plugin=mysql_native_password app: build: context: . dockerfile: ./Dockerfile.webapp environment: - MYSQL_NAME=${MYSQL_DATABASE} - MYSQL_USER=${MYSQL_USER} - MYSQL_PASSWORD=${MYSQL_PASSWORD} ports: - "8000:8000" networks: - net volumes: - ./app/webapp:/app - data:/data depends_on: - db restart: unless-stopped command: > sh -c "python manage.py runserver 0.0.0.0:8000" tool: build: context: . dockerfile: ./Dockerfile.tool volumes: - data:/data networks: net: driver: bridge volumes: db: db-logs: data: In the end, the user should be able to set the parameters via the Web-UI and run the tool container. … -
Django LDAP search problems
Server Error AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance. Trying to setup Netbox here. Seems like a really cool tool, if I could ever get it working properly due to operator error. I am able to get a login portal when I host the server insecurely -- I have it set to where you must sign in before seeing anything. When I enter a username and password for the super user, or any text, here is what I get. <class 'django.core.exceptions.ImproperlyConfigured'> AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance. Python version: 3.10.4 NetBox version: 3.2.8 Here is two parts of my config file, note that name, user and passwords have been changed. DATABASE = { 'NAME': 'myName', # Database name 'USER': 'myUsername', # PostgreSQL username 'PASSWORD': 'myPass', # PostgreSQL password 'HOST': 'localhost', # Database server 'PORT': '', # Database port (leave blank for default) 'CONN_MAX_AGE': 300, # Max database connection age # Remote authentication support REMOTE_AUTH_ENABLED = True REMOTE_AUTH_BACKEND = 'netbox.authentication.LDAPBackend' REMOTE_AUTH_HEADER = 'HTTP_REMOTE_USER' REMOTE_AUTH_AUTO_CREATE_USER = True REMOTE_AUTH_DEFAULT_GROUPS = [] REMOTE_AUTH_DEFAULT_PERMISSIONS = {} I would appreciate any help/advice you all have to offer. Thanks. -
visual studio code debug configuration for django doesnt recognize test files
I have a standard project setup where my test.py inside of the app folders. When I manually run py manage.py test it recognizes my test files. When using this debug config, it wont run the tests. Found 0 test(s). System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK How can I set them up correctly? launch.json: { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\django_project\\manage.py", "args": [ "test" ], "django": true, "justMyCode": true }, -
Trying to add items in list of lists of tuples
I am making a game picking app and I am stuck on trying to get a summary of points for users. The list is consisting of 18 lists (weeks) with all users and their respective points, sorted alphabetically. I don't know how to create a list with user---> all points combined. Here is an example with only 2 users [[('user1', 25), ('user2 ', 18)], [('user1', 18), ('user2 ', 25)], [('user1', 18), ('user2 ', 25)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)]] -
how to display all the post if url has this id in django templates
<div class="wilipedia-overview__list"> {% for lexicon_item_obj in lexicon_item_obj.all %} <div id="wilipedia-item-{{ lexicon_item_obj.id }}" class="wilipedia-item js-wilipedia-item{% if forloop.counter > 8 %} hidden {% endif %}" data-filter="{% for lexicon_key in lexicon_item_obj.lexicon_key_set.all %}{{ lexicon_key.title }}{% endfor %}"> <div class="wilipedia-item__title"> <h5>{{ lexicon_item_obj.title }}</h5> </div> <div class="wilipedia-item__desc"> {{ lexicon_item_obj.description }} </div> <a href="#" class="js-load-more" style="display: none" data-load-more="Load more" data-load-less="Load less">Load more</a> </div> {% endfor %} </div> {% if lexicon_item_obj.count > 8 %} <a href="#" class="wilipedia-overview__show-all btn --btn-black js-show-all">Show more</a> {% endif %} </div> enter image description here I am implementing the search functionality and search items on base of id and here I want to check url if url has id 12 or more I want to disable the button and dispaly all the items. Anyone has an idea how to do that? -
Permission Denied Error on linux server only, same code works well on windows?
In my project, I have used google drive API. Using google API, I want to create folders and upload some files to a particular folder. When a new company is added to the database, I want to create folders related to that company. The whole code is working on windows perfectly. But in Linux, while creating a folder on the drive it shows permission denied [Error 13]. The actual error comes in the following place: if not os.path.exists(os.path.join(working_dir, token_dir)): os.mkdir(os.path.join(working_dir, token_dir)) Traceback (most recent call last): File "/home/admin/webkorradmin/envwebkorradmin/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/admin/webkorradmin/envwebkorradmin/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/admin/webkorradmin/webkorradmin/invoice_generator/views.py", line 497, in add_company service = init_drive_service() File "/home/admin/webkorradmin/webkorradmin/invoice_generator/google_drive/drive.py", line 14, in init_drive_service service = create_service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) File "/home/admin/webkorradmin/webkorradmin/invoice_generator/google_drive/Google.py", line 24, in create_service os.mkdir(os.path.join(working_dir, token_dir)) Exception Type: PermissionError at /invoice/add-company/ Exception Value: [Errno 13] Permission denied: '/token files' -
How to get data between two dates by getting from inputs?
I'm trying to filter my table with the user inputs. I create a filter that allows the users to choose 2 dates (YYYY-MM-DD). I can reach the input data like: 2022-08-19 2022-08-31 and I have a Case model. I want to get the cases created between these two dates. views.py year_one = self.request.GET.get('year_one') year_two = self.request.GET.get('year_two') cases = Case.objects.filter(date_created=.....).values(fieldname).order_by(fieldname).annotate(the_count=Count(fieldname)) -
How to get access to field using many to many and 'through' in Django?
I need to get the name from ProjectProgramGroup model starting from Project model. I tried to do somenting like this: @property def project_groups(self): return self.project.project_groups but it returns: projects.ProjectProgramGroup.None My models: class Project: short_name = models.CharField(verbose_name='short name', max_length=255) project_groups = models.ManyToManyField('ProjectProgramGroup', through='ProjectGroupRelation') class ProjectGroupRelation: project = models.ForeignKey(Project, on_delete=models.CASCADE) group = models.ForeignKey(ProjectProgramGroup, on_delete=models.CASCADE, verbose_name='group') class ProjectProgramGroup(): name = models.CharField('name', max_length=255) -
How can I get user question from a view that already has a slug
I'm trying to get a user question from public_profile view that uses slug to get user profile information, and now I wanted to get user question in the public_profile view that uses slug, but it gives me Page not found (404) error. I want a users to be able to see other user question in their profile page. How can I solve this problem to get users question when someone visited their profile page? Question model: class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(unique=True, max_length=200) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Question, self).save(*args, **kwargs) def __str__(self): return str(self.title) The view: @login_required(login_url='login') def public_profile(request, slug): profile = get_object_or_404(Profile, slug=slug) questions = get_object_or_404(Question, slug=slug) number_of_likes = Like.objects.filter(post__user=request.user).count() try: number_of_likes = Like.objects.filter(post__user=profile.user).count() except ObjectDoesNotExist: number_of_likes = None context = { 'profile':profile, 'number_of_likes':number_of_likes, 'questions':questions } return render(request, 'public_profile.html', context) my template: <div class="container"> <div class="row justify-content-center"> <div class="col"> <ul class="list-group"> <li class="list-group-item">{{question.title}}</li> </ul> </div> </div> </div> urls: path('userProfile/<slug:slug>/', views.public_profile, name='Public_Profile'), -
Verifying AzureAD access token with Django-REST-framework
Before anything I would like to warn you about my extremely limited knowledge on the subject. Now that you've been warned, what I need to ask is how can I verify and azureAD access token with Django/django-rest-framework. I have a app that I need to sing in to with azureAD, which means I need to get an access token from azureAD, and thankfully this is will be done on the frontend side with Angular what I need to do is verify that token on the backend side with django/django-rest-framework and I have no idea where to start from, can anyone suggest a way to do this or send me in the right direction ? Thank you very much.