Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Simple POST Class View Not Working
I am experimenting with Django class based views and for some reason this simple post view does not seem to be working. When looking at my terminal it gets stuck on the GET method / validation of the csrf token. It is either not being validated or not saving to the database and therefore not being redirected to the thank-you page. I am not sure how to solve this issue. It definitely is not being saved to the DB, but as far as I am aware everything is correct here. I also am using a class based form which is why I am simply just calling form.save() The code is as follows: class ReviewView(View): def get(self, request): form = ReviewForm() return render(request, 'reviews/review.html', { 'form': form }) def post(self, request): form = ReviewForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/thank-you') return render(request, 'reviews/review.html', { 'form': form }) Any help or ideas is greatly appreciated! -
Django Admin Custom User password not getting hashed+salted
I've created a custom user to use email instead of the username. This is the code that works models.py # Overriding the default users model from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.db import models from django.contrib.auth.models import AbstractUser class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email and registered it to the admin modal for a more flexible list. (admin.py) from django.contrib import admin from .models import CustomUser @admin.register(CustomUser) class CustomUserADM(admin.ModelAdmin): list_display = ("email", "is_staff", "is_active") … -
how to deal with __init__ in serializers.ModelSerializer?
I need to create a dynamic serializer and inside it I need to get the method (GET/PUT/..) and the pk value if the url look like this url/1/ or url/2/ where 1 and 2 are pks. class DynamicSerializer(QueryFieldsMixin, serializers.ModelSerializer): def __init__(self, * args, **kwargs): super(DynamicSerializer, self).__init__(*args, **kwargs) modelname = self.Meta.model.__name__.lower() method = '' is_owner = False pk = None user = self.user class Myser(DynamicSerializer): class Meta: model = models.Model fields = '__all__' Myser(Mode).data I think there is somthing like slef.list, self.delete, self.create in the views where it looks like this class ItemView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): MyModel = None def get_object(self, pk,): try: return self.MyModel.objects.get(id=pk) except self.MyModel.DoesNotExist: raise status.HTTP_404_NOT_FOUND def get(self, request, pk, format=None): item = self.get_object(pk) serializer = self.serializer_class(item, many=False) return slef.item(request) #<= this -
Send message using Django Channels from outside Consumer class from new Process
I am building an REST Api in Django for training and predict some data. I have a websocket connection with the purpose of having bidirectional communication. For non-blocking server when someone wants to train a new model I decide to use a new Process from multiprocessing. All work good but i can't send back a message when training is over from that Process. This is my consumer.py class import json from asgiref.sync import sync_to_async from channels.generic.websocket import AsyncJsonWebsocketConsumer, AsyncWebsocketConsumer import time import asyncio from multiprocessing import Process from .train import train from threading import Thread from channels.layers import get_channel_layer class Consumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.channel_layer.group_add("gossip", self.channel_name) await self.accept() async def disconnect(self, close_code): pass # Receive message from WebSocket async def receive(self, text_data): print(text_data) await self.send(text_data=json.dumps({ 'message': text_data })) data = "Works good" p = Process(target=train, args=(data,)) p.start() # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) async def sendMessageTrain(self): await self.send(text_data=json.dumps({ 'message': "Model success trained" })) async def notify(self, event): print("In notify method: Notify") print(event["content"]) await self.send(text_data=json.dumps({ 'message': event["content"] })) Channles layer settings: CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" # "BACKEND": "channels_redis.core.RedisChannelLayer", # "CONFIG": … -
How to solve unsupported locale setting in pandas
Error at ... unsupported locale setting cats = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье'] cat_type = CategoricalDtype(categories=cats, ordered=True) locale.setlocale(locale.LC_ALL, 'rus_rus' if sys.platform == 'win32' else 'ru_RU.UTF-8') df['w_date_to'] = df['w_date_to'].dt.day_name(locale='Russian').astype(cat_type) My Ubuntu server local settings: *locale -a* C C.UTF-8 POSIX ... en_US.utf8 ... ru_RU.utf8 ru_UA.utf8 *locale* LANG=en_US.UTF-8 LANGUAGE=en_US:en ... LC_ALL=C Thanks in advance. -
How to manage Postgres Enum type in Django?
I had used django-mysql to manage MySQL enum type from Django. Recently I am using the Postgres database for my Django project. To manage the Postgres Enum, I could not able to find any library. There is a db_type() method in Django to manage custom type. But the problem is Postgres enum must be created first at database and after that, I can use it. Here is a code sample for Postgres enum. CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'); CREATE TABLE person ( name text, current_mood mood ); Is there present a library at all? If not, how could I be able to achieve the Postgres enum management from Django? -
I want to create work schedule for employees for crm system in django REST
**I could not find any helpful resource or any libs related to this.I have tried this library :https://github.com/rodrigoamaral/django-fullcalendar but it didnt help me ** -
What do I return if I override dispatch() method in Django?
So I am trying to write controller logic for my page search field. It suppose to search posts by title and display them. I am trying to implement a verification that the search field isn't empty and while at it I am also trying to let user know if there weren't posts to display. I am trying to do so via HttpResponses. The problem is I can't place'em in get_queryset method because it's supposed to return querysets not http responses, so I placed them in "view" part of CBV i.e. dispatch method and it works fine. But now I don't understand what to do to display the result when there's actually some posts found. I get Exception Value: The view blog.views.Search didn't return an HttpResponse object. It returned None instead. So what do I do to display posts when there are actually some to display? Thanks beforehand! My search field: <div class="email" align="right" style="margin: 100px 0 0 150px"> <h2 class="sidebar-title" align="center">Search Post</h2> <form action="{% url 'search' %}" method="get"> <input type="text" name="s" placeholder="Search Post"> <input type="submit" value="look up"> </form> </div> My view: class Search(ListView): """Searching Posts""" template_name = 'blog/posts_by_search.html' context_object_name = 'posts_found' paginate_by = 2 def dispatch(self, request, *args, **kwargs): """HttpResponse … -
Authentication fails during login testing
I am trying to test custom login (with pytest) but authentication fails returning None. Here is views.py from rest_framework.authtoken.views import ObtainAuthToken from my_auth.api.serializers import UserLoginSerializer class LoginAuthToken(ObtainAuthToken): serializer_class = UserLoginSerializer serializers.py from django.contrib.auth import authenticate from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from rest_framework.authtoken.serializers import AuthTokenSerializer class UserLoginSerializer(AuthTokenSerializer): username = None email = serializers.EmailField( label=_("Email"), ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') if email and password: user = authenticate(request=self.context.get('request'), email=email, password=password) # returns None if not user: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg, code='authorization') # raises else: msg = _('Must include "email" and "password".') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs tests.py import pytest from django.urls import reverse from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.test import APIClient @pytest.fixture def test_user(): user = MyUser.objects.create( email='test@m.com', first_name='Firstname', last_name='Lastname' ) user.set_password('pass5678') return user @pytest.mark.django_db def test_login(test_user): client = APIClient() response = client.post( path=reverse('login'), data={ 'email': 'test@m.com', 'password': 'pass5678', }, format='json', ) assert(response.status_code == status.HTTP_200_OK) token = Token.objects.get(user=test_user) assert(token.key == response.data['token']) Terminal output: ========================================================================================================== test session starts ========================================================================================================== platform linux -- Python 3.8.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 django: settings: news_project.settings (from ini) rootdir: /home/andrei/NEWS/news_project, configfile: pytest.ini plugins: lambda-1.2.4, Faker-8.4.0, common-subject-1.0.5, … -
Why is the Post model that I create in the admin panel not showing in the admin panel?
I do not understand why when I create a Post model in the admin panel, it is not displayed on my server in the admin panel enter image description here here is the code admin.py `from django.contrib import admin from .models import Post admin. site.register(Post)`, here is the code models.py `from django.db import models class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() def __str__(self): return self.title` I will be glad to any of your advice and help -
TypeError at /ap1/checkbooks/ 'type' object is not iterable; return [auth() for auth in self.authentication_classes] TypeError: 'type' object is
I am getting django Error while using rest django concept. How to solve the below error of django i can't able to open the webpage in my browser. please let me know how to solve the issue.All the codes are below. Any help appreicatable . TIA Settings.py """ Django settings for pro1 project. Generated by 'django-admin startproject' using Django 3.2.3. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-_=f2k%yr6l&3sbcz#dpt5ec8t+7aw_i^2p*$$z0kt0iq!u0iag' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'ap1', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'pro1.urls' ''' REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', # for restriction ) }''' # for restriction access REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.AllowAny', ), } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { … -
Django Form to Model Before Save
I have a Django model called Family, and a Django form called FamilyForm. I save the form in a view as follows: if request.method == 'POST': form = FamilyForm(request.POST) if form.is_valid: form.save() messages.success(request, 'Successfully added the family') else: messages.error( request, 'There was a problem with adding the family') However, my problem is that I would first like to convert this form to a Family object before saving it as I would like to assign some missing properties. Any idea how to convert the form to a Model object so that I can make the changes before saving? -
Getting SMTPServerDisconnected Error when trying to send email in django
I am trying to send an email with gmail in Django but I am getting SMTPServerDisconnected error. I have tried everything from enabling lesssecuredapps to DisplayUnlockCaptcha but still getting the same error. Any help would be greatly appreciated! Here is the setting.py for email config Here is the send_mail in my views.py The error I've been getting -
The best way to extract a large zip file in the background regardless of the template changing (or other external issues occurring) in Django?
I want to upload a zip file that contains 1 GB or more image data. I have a function that renders a basic Django template that uploads the zip file in the server and then later extracts it using the zipfile module and stores these images. My only worry is that when the user suddenly moves around the site or a network error (or some other external issue) occurs, the function gets interrupted and the extraction, as well as the database storage progress, stops. In short, duplication occurs. If I try to re-run the function again, the 'already stored' images get stored again and later saved to the model. I am not sure how to proceed with the file extraction and storage once the python function gets interrupted. What should I do? This my code so far: def upload(path, id): try: with zipfile.ZipFile(path, mode='r', allowZip64=True) as file: document = Mymodel.objects.get(id=id) directory_to_extract = f"media/{document.path}" file.extractall(directory_to_extract) except zipfile.LargeZipFile: print("File size is too large.") return 0 #returns an error finally: file.close() os.remove(path) Note: The parameter 'path' is the temporary file path moved to the stored path in the directory. The parameter 'id' is the zip file id that gets stored in the model … -
Authentication & Authorization based on JWT Token in Django rest
I am just a newbie with Django, python. I try to build 1 simple API Collection include CRUD basic, and authentication, authorization. I have 1 simple Views like: @api_view(['GET']) @permission_classes([IsUser]) def get_test(request : Request): return JsonResponse({"message": "success"}, status = status.HTTP_200_OK) and IsUser is: class IsUser(IsAuthenticated): def has_permission(self, request : Request, view): token = request.query_params.get('token') if token: role = jwt.decode(token.split(" ").__getitem__(1), key="secret_key",algorithms="HS256").get('role') if role == 'User': return True else: return False return False My purpose wants to parse the JWT token and authorization based on that. I wonder don't know if my way is really correct? Can anyone give me some comments as well as documentation to better understand this issue? I don't use any other lib because I want to code by myself at first to understand the flow. Thanks for helping me. -
How to add Bar chart for my values in database using django
I have 4 columns in my database(userid,month,value1,value2).I need to add a bar graph to compare two values(value1 and value2) for the same month and retrieve it in a bar chart like shown below models.py from django.db import models from django.contrib.auth.models import User class graphinput(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) Month = models.CharField(max_length=30) Value1 = models.IntegerField() Value2 = models.IntegerField() I need my graph to look like this like comparing two values(value1 and value2) for a same month.. -
Django translation resolution order
I have my base code strings written in Spanish. I want to use another lang as base lang, and sets it in LANGUAGE_CODE, for example, 'de'. I have de.po in locale. I set 'es' as user lang. I have es.po in locale with all empty msgstr values. translation.activate('es') In this case, Django loads the LANGUAGE_CODE value 'de' as default, and loads the 'de' msgstr values as user lang, not the base code strings. The django docs says: When an English variant is activated and English strings are missing, the fallback language will not be the LANGUAGE_CODE of the project, but the original strings. For example, an English user visiting a site with LANGUAGE_CODE set to Spanish and original strings written in Russian will see Russian text rather than Spanish. Maybe a bug? -
Django AJAX : submitting form to different url
Consider having a page url of (localhost:8000/tests). my form in the page submit the form data to url (localhost:8000/add/model) what I'm trying to do is to get the response and render the form template with success or fail message in same page (localhost:8000/tests). the submitting working fine but rendering the form back to the page (localhost:8000/tests) the response render to separate page on url (localhost:8000/add/model) and render form template only views.py: @login_required(login_url="/login/") def add_user(request): done = [] fail = [] context = {} crud = CRUDHandler() form = UserForm(request.POST or None) context['user_form'] = form if 'save' in request.POST: if form.is_valid(): new_user = crud.c_user( username = form.cleaned_data.get('username'), first_name = form.cleaned_data.get('first_name'), last_name = form.cleaned_data.get('last_name'), email = form.cleaned_data.get('email'), ) done.append("User | "+str(new_user.first_name)+" | added successfully!") #change to the right page else: fail.append("Somthing went wrong, new user can't be created!") #change to the right page context['done'] = done context['fail'] = fail return TemplateResponse(request,'components/forms/single_instance_form.html',context) Form_Handler.js $('#form').on('submit', function(event){ event.preventDefault(); var form_anchor = $(this).attr('id') console.log(form_anchor) submit_form(form_anchor); }); function submit_form(form_anchor) { $.ajax({ url : $(form_anchor).attr('action'), // the endpoint type : "POST", // http method // data sent with the post request data : { 'context': $(form_anchor).serialize(), 'csrfmiddlewaretoken': '{{ csrf_token }}', }, // handle a successful response success : … -
Nuxt Auth 'loginWith' function doesn't send data to DRF
I recently tried to combine Nuxt.js with Django. Nuxt.js has a module called Nuxt Auth (I use @nuxtjs/auth-next), which is pretty straightforward and simple to use. However, I ran into a problem when I tried to get the post data when using $auth.loginWith(...) in a Django APIView. When I print out request.POST, it returns an empty QueryDict. When I log in with the standard DRF forms, I get my token as expected (I use JWT for authentication). I first thought that I did something wrong in my Nuxt.js frontend, so I cloned some repos on GitHub to see how they have done it (tickstudiu, ammezie). I then tried to combine their frontend with my backend. I also watched a tutorial on YouTube. Still the same problem... That's why I think that it is a Nuxt + Django specific problem because otherwise, the other repos would work, right? Or maybe I just do something wrong every time... This is what I get when I log in with standard DRF form: HTTP 200 OK Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "username": "admin", "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZW1haWwiOiJhbmRyZWFzLmdlcmFzaW1vdzEyQGdtYWlsLmNvbSIsImV4cCI6MTYyMjc5NjQ2N30.XQ58Fo0nOS2C44SRQG5A2vEDT0fOXJTIrHG8XNaxzBo" } Here is my Login API in Django: class LoginAPIView(GenericAPIView): serializer_class = LoginSerializer def post(self, request, … -
How to pull secrets from Kubernetes into GitHub action to run Django migrations for AKS deployment?
I have taken up the challenge of automating the deployment of my company's Django-based application that is done with AKS but I am very new to it. My initial idea is to accomplish it by upgrading the steps in a GitHub workflow that acts on the release of a new version. I have structured it with three jobs. build, migrate and deploy: build: Simply build the Docker image and push it to the container registry on DockerHub - this step is successfully done. migrate: Run the migrations in the production database from python manage.py migrate - here lies the problem. deploy: Deploy the image to the Kubernetes cluster - successfully done. Step 2 is the problem because we store the Postgres database credentials inside the Kubernetes cluster and to run the migrations I need those secrets to pass them as environment variables before I call the migrate command. So I am stuck on how I can pull those secrets from Kubernetes and use them to run a command in a step in GitHub action like this: migrate: needs: build runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v2 with: python-version: 3.8 - name: psycopg2 prerequisites … -
Stripe "webhook" error with "custom user model" (Django)
I'm trying to configure Django Stripe Subscriptions. And now trying to setup webhook to create a new customer data by below code. views.py import stripe from django.conf import settings from django.contrib.auth.models import User from subscriptions.models import StripeCustomer ... # Get the user and create a new StripeCustomer user = User.objects.get(id=client_reference_id) StripeCustomer.objects.create( user=user, stripeCustomerId=stripe_customer_id, stripeSubscriptionId=stripe_subscription_id, ) print(user.username + ' just subscribed.') I'm getting error at user = User.objects.get(id=client_reference_id) because I'm using "custom user model". therefore I changed the above code to user = settings.AUTH_USER_MODEL.objects.get(id=client_reference_id) But still, it does not work. Is there any other way to write to get "user data"? I'm following this manual to create this app https://testdriven.io/blog/django-stripe-subscriptions/ Below is other codes. My models.py from django.conf import settings from django.db import models class StripeCustomer(models.Model): user = models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripeCustomerId = models.CharField(max_length=255) stripeSubscriptionId = models.CharField(max_length=255) def __str__(self): return self.user.username accounts/models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): class Meta: verbose_name_plural = 'CustomUser' My settings.py #used for django-allauth AUTH_USER_MODEL = 'accounts.CustomUser' I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
How not to go into infinite recursion with a Django signal and a Celery task
I'm working on billing Django app and should generate Pdf from budget on background task each time any value changes. models.py: class Budget(ChangesMixin, models.Model): pdf = models.FileField(verbose_name="PDF", max_length=200, upload_to='pdf/budgets', null=True, blank=True) tasks.py: @shared_task(name='generate_budget_pdf_task') def generate_budget_pdf_task(budget_id): budget = get_object_or_404(app_models.Budget, id=id) concepts = budget.concept_budget.all() try: file = app_pdf.PDF(None, budget, concepts) pdf_file = file.generate_budget() file_name = 'Pto_' + str(budget.brand.client.name) + '_' + str(budget.name) + '_' + str(budget.code) + ".pdf" budget.pdf.save(file_name, ContentFile(pdf_file), save=True) except Exception as e: print("Error generate_budget_pdf_task") print(e) print(type(e)) signals.py: def generate_budget_pdf_signal(sender, instance, created, **kwargs): if 'pdf' not in instance.changes(): app_tasks.generate_budget_pdf_task.delay(instance.id) post_save.connect(generate_budget_pdf_signal, sender=app_models.Budget) But the task update Any could help me please ? Thanks in advance. -
why am I getting undefined error while django migrations?
when I am doing a makemigrations(python manage.py makemigrations), I am getting below errors: File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "base_parameter" does not exist LINE 1: ...e_parameter"."key", "base_parameter"."value" FROM "base_para... ^ I have no idea where to start the troubleshoot. I have created a new database in PostgreSQL. I did go through couple of posts in Stackoverflow, but they are no good for me. I have tried below. - remove previous migrations files - create new DB Please suggest how to fix this. Thank you -
Why is my Django CORS headers not working properly
So I've added corsheaders to both my INSTALLED_APPS and MIDDLEWARE and set CORS_ORIGIN_ALLOW_ALL to True NSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'student', 'rest_framework', 'corsheaders' ] 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 And I'm also using rest to build an api to use alongside my react app. I made my first API calls to http://localhost:8001/api/students/ to get all the students data and everything is working fine, until I tried to access them individually by changing the link to http://localhost:8001/api/students/1/, when I tried to make a call to that link it gave me this error why is this happening ? -
How to implement encryption decrypttion using cryptography in Django
I am trying generate the order and send to someone and i want to use encrypt and decrypt method using crypto library like bitcoin, Ethereum, but i don't know how can i implement this.