Unable to get activation E-mail in django - django

I am trying to get an activation email from Django but have not received any email. Now less secure app access is now banned from google so I created an app password which was advised by the youtube channel but I still not get the output here are my tables:
Views.py
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.shortcuts import redirect, render
from django.utils import timezone
from django.core.mail import send_mail, EmailMessage
from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.utils.encoding import force_text
from django.utils.http import urlsafe_base64_encode , urlsafe_base64_decode
from .tokens import generate_token
def Register(request):
if request.method=='POST':
# username=request.POST.get('Username')
username=request.POST['Username']
password=request.POST['Password']
Fname=request.POST['Fname']
Lname=request.POST['Lname']
Email=request.POST['Email']
PhoneNo =request.POST['PhoneNo']
Age=request.POST['Age']
if User.objects.filter(username=username):
messages.error(request,"Username already exits! Please try some other username.")
if User.objects.filter(email=Email):
messages.error(request,"Email ID already exits! Please try some other Email ID.")
myuser =User.objects.create_user(username,Email,password)
myuser.first_name=Fname
myuser.last_name=Lname
myuser.save()
messages.success(request,"Your Account has been successfully created. We have sent you a confirmation email, please confirm your email to activate your account.")
#Welcome Email
subject ="Welcome to the largest Community of art"
message="Hello there!! "+ Fname+"\nWelcome to some place where you can share your art ,learn about different forms of art and teach your creative students about your art\n"+"We have also sent you a confirmation email, please confirm your email address. \n\nThanking You\nPranay Singhvi"
from_email = settings.EMAIL_HOST_USER
to_list = [myuser.email]
send_mail(subject, message, from_email, to_list, fail_silently=True)
# Email Address Confirmation Email
current_site = get_current_site(request)
email_subject = "Confirm your Email # NGMA Login!!"
message2 = render_to_string('email_confirmation.html',{
'name': myuser.first_name,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(myuser.pk)),
'token': generate_token.make_token(myuser)
})
emails = EmailMessage(
email_subject,
message2,
settings.EMAIL_HOST_USER,
[myuser.email],
)
emails.send(fail_silently = True)
return redirect('LoginUser/')
return render(request,'Register.html')
def activate(request,uidb64,token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
myuser = User.objects.get(pk=uid)
except (TypeError,ValueError,OverflowError,User.DoesNotExist):
myuser = None
if myuser is not None and generate_token.check_token(myuser,token):
myuser.is_active = True
myuser.profile.signup_confirmation = True
myuser.save()
login(request,myuser)
messages.success(request, "Your Account has been activated!!")
return redirect('VisitorForm/')
else:
return render(request,'activation_failed.html')
Settings.py
"""
Django settings for NGMA project.
Generated by 'django-admin startproject' using Django 4.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
import os
from pathlib import Path
from django.contrib.messages import constants as messages
import django
from django.utils.encoding import force_str
django.utils.encoding.force_text = force_str
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS=True
EMAIL_HOST='smtp#gmail.com'
EMAIL_HOST_USER='pranaysinghvi2003#gmail.com'
EMAIL_HOST_PASSWORD='mzwlfgnrzsiyimnz'
EMAIL_PORT=587
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'home.apps.HomeConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'NGMA.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / "templates"],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'NGMA.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
Tokens.py
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from six import text_type
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self,user,timestamp):
return (
text_type(user.pk) + text_type(timestamp)
# text_type(user.profile.signup_confirmation)
)
generate_token = TokenGenerator()
urls.py
from django.contrib import admin
from django.urls import path, include
from home import views
urlpatterns = [
path("",views.home,name="home"),
path("Home/",views.home,name="home"),
path('ContactUs/',views.Contact, name='Contact'),
path('Checkout/',views.VisiterForm, name='Checkout'),
path('AboutUs/',views.About, name='About'),
path('Employee/',views.Employee, name='Employee'),
path('Booking/',views.Booking, name='Booking'),
path('VisitorForm/',views.VisitorForm,name='VisitorForm'),
path('LoginUser/',views.LoginUser ,name='LoginUser'),
path('LogoutUser/',views.LogoutUser ,name='LogoutUser'),
path('Register/',views.Register ,name='Register'),
path('Artist/',views.Artist ,name='Artist'),
path('ArtistForm/',views.ArtistForm ,name='ArtistForm'),
path('activate/<slug:uidb64>/<slug:token>/', views.activate, name='activate'),
path('Checkout/',views.Checkout,name='Checkout')
]
To send a welcome email and an activation email on registering

Related

Django Rest Framework GET request returning desired Response only on first Request

I am using Django Rest Framework and OpenStack (DevStack deployed on a Virtual Machine on my local PC) to create APIs which will run methods provided by OpenStack SDK and return the response in JSON format.
However, while fetching(GET Request) a list of Servers created on OpenStack Cloud Platform, the Response for the first time after starting the Django Server is proper and desired, but after first GET Request, all GET requests sent are returning an empty List as the Response.
It must be noted that I have not changed anything in the code or in the Endpoint(URL), the same scenario keeps on repeating when I restart the Django Server, desired GET Response on first Request and Empty List for all the GET Requests onward.
I do not have any models of my own in models.py.
First GET Request Response:-
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"name": "test_shell",
"image": "openstack.image.v2.image.Image(id=b6019f25-6f6d-4fd2-9fb8-14d50a07d2c0, properties={'links': [{'rel': 'bookmark', 'href': 'http://192.168.56.101/compute/images/b6019f25-6f6d-4fd2-9fb8-14d50a07d2c0'}]})",
"flavor": "openstack.compute.v2.flavor.Flavor(vcpus=1, ram=128, disk=1, OS-FLV-EXT-DATA:ephemeral=0, swap=0, original_name=m1.nano, extra_specs={'hw_rng:allowed': 'True'})",
"networks": null,
"status": "ACTIVE",
"power_state": "1"
},
{
"name": "ins_code_4",
"image": "openstack.image.v2.image.Image(id=b6019f25-6f6d-4fd2-9fb8-14d50a07d2c0, properties={'links': [{'rel': 'bookmark', 'href': 'http://192.168.56.101/compute/images/b6019f25-6f6d-4fd2-9fb8-14d50a07d2c0'}]})",
"flavor": "openstack.compute.v2.flavor.Flavor(vcpus=1, ram=128, disk=1, OS-FLV-EXT-DATA:ephemeral=0, swap=0, original_name=m1.nano, extra_specs={'hw_rng:allowed': 'True'})",
"networks": null,
"status": "SHUTOFF",
"power_state": "4"
},
{
"name": "ins_code_3",
"image": "openstack.image.v2.image.Image(id=b6019f25-6f6d-4fd2-9fb8-14d50a07d2c0, properties={'links': [{'rel': 'bookmark', 'href': 'http://192.168.56.101/compute/images/b6019f25-6f6d-4fd2-9fb8-14d50a07d2c0'}]})",
"flavor": "openstack.compute.v2.flavor.Flavor(vcpus=1, ram=128, disk=1, OS-FLV-EXT-DATA:ephemeral=0, swap=0, original_name=m1.nano, extra_specs={'hw_rng:allowed': 'True'})",
"networks": null,
"status": "SHUTOFF",
"power_state": "4"
}
]
GET Response after first Request:-
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[]
Django Code:-
Root settings.py
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/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-#gd5-6=)lwq4&bo(gywzy7ftic+5r!hgs$(%1gyqbt=pbwk=*a'
# 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',
'api',
]
# Custom by me
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
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 = 'cloudhome.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ BASE_DIR / "templates" ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'cloudhome.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / "static"
]
STATIC_ROOT = "static_root"
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Root urls.py:-
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('api/', include('api.urls', namespace="api")),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
App "api" urls.py:-
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from api import views
app_name = "api"
urlpatterns = [
path('servers/', views.ServerList.as_view()),
path('servers/<slug:pk>/', views.ServerDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
App "api" views.py:-
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from requests import request
from rest_framework.parsers import JSONParser
from api.serializers import ServerSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import generics
import openstack
from openstack import connection
from rest_framework import authentication, permissions
from rest_framework.permissions import IsAuthenticated
openstack.enable_logging(debug=True)
conn=connection.Connection(auth_url='http://192.168.56.101/identity/v3',
project_name='admin',username='admin',
password='nomoresecret',
user_domain_id='default',
project_domain_id='default', verify=False)
class ServerList(generics.ListAPIView):
queryset = conn.compute.servers()
serializer_class = ServerSerializer
permission_classes = [permissions.IsAuthenticated]
class ServerDetail(generics.RetrieveAPIView):
queryset = conn.compute.servers()
serializer_class = ServerSerializer
permission_classes = [permissions.IsAuthenticated]
App "api" serializers.py:-
import openstack
from openstack import connection
from requests import Response
from rest_framework import serializers
from rest_framework import status
openstack.enable_logging(debug=True)
conn=connection.Connection(auth_url='http://192.168.56.101/identity/v3',
project_name='admin',username='admin',
password='nomoresecret',
user_domain_id='default',
project_domain_id='default', verify=False)
class ServerSerializer(serializers.Serializer):
instance_id = serializers.CharField(read_only=True)
name = serializers.CharField(max_length=100)
image = serializers.CharField(max_length=500)
fixed_ip = serializers.IPAddressField(read_only=True)
floating_ip = serializers.IPAddressField(required=False, allow_blank=True)
flavor = serializers.CharField(max_length=500)
networks = serializers.CharField(max_length=500)
key_pair = serializers.CharField(max_length=100, required=False, allow_blank=True)
status = serializers.CharField(max_length=20, read_only=True)
power_state = serializers.CharField(max_length=20, read_only=True)
console_url = serializers.URLField(max_length=100, read_only=True)
def create(self, validated_data):
serverCreated = conn.compute.create_server(name=validated_data["instance_name"], image_id=validated_data["image_id"],
flavor_id=validated_data["flavor_id"], networks=[{"uuid": validated_data["network_id"]}])
serverWait = conn.compute.wait_for_server(serverCreated)
print(serverWait.access_ipv4)
return serverWait
Kindly help me to resolve this issue and feel free to suggest changes to make this code more efficient. Thanks in advance.

It is required that you pass in a value for the "algorithms" argument when calling decode()

The following pages are the code of projects:
If i am using token = jwt.encode(payload,'secret', algorithm='HS256').decode('utf-8') statement
then
'str' object has no attribute 'decode'
error is occuring. Also, when I am removing and using it without .decode('utf-8') and proceeding with the further code. it is working fine. But when I am applying payload = jwt.decode(token, 'secret', algorithm=['HS256'])
then
It is required that you pass in a value for the "algorithms" argument when calling decode()"
This above-mentioned error is occurring. Please Help me to rectify this error. This is the mentioned error that saying algorithms argument when calling decode() error should be rectified.
View Page:
from django.http import request, response
from django.shortcuts import render
from rest_framework import serializers
from rest_framework.views import APIView
from myusers.serializers import UserSerializer
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.response import Response
from .models import User
import jwt, datetime
# Create your views here.
class RegisterView(APIView):
def post(self,request):
serializer = UserSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
class LoginView(APIView):
def post(self,request):
email=request.data['email']
password = request.data['password']
user = User.objects.filter(email=email).first()
if user is None:
raise AuthenticationFailed('User Not Found!!!')
if not user.check_password(password):
raise AuthenticationFailed('Incorrect Password!!!')
payload={
'id':user.id,
'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
'iat':datetime.datetime.utcnow()
}
token = jwt.encode(payload,'secret', algorithm='HS256').decode('utf-8')
response = Response()
response.data={
"jwt":token
}
response.set_cookie(key='jwt', value=token, httponly=True)
return response
class Userview(APIView):
def get(self,request):
token = request.COOKIES.get('jwt')
if not token:
raise AuthenticationFailed('User Authentication Failed!!!')
try:
payload = jwt.decode(token, 'secret', algorithm=['HS256'])
except jwt.ExpiredSignatureError:
raise AuthenticationFailed('Unauthenticated!')
user = User.objects.filter(id = payload['id']).first()
serializer = UserSerializer(user)
return Response(serializer.data)
class LogoutView(APIView):
def post(self, request):
response = Response()
response.delete_cookie('jwt')
response.data = {
'message': 'success'
}
return response
Serializer Page:
from django.db.models import fields
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'name','email','password']
extra_kwargs={
'password' : {'write_only':True}
}
def create(self, validated_data):
password = validated_data.pop('password',None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
Model Page:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
name = models.CharField(max_length=255)
email = models.CharField(max_length=250, unique=True)
password = models.CharField(max_length=255)
username = None
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
Urls page:
from django.urls import path
from .views import RegisterView, LoginView, Userview
urlpatterns = [
path('register',RegisterView.as_view()),
path('login',LoginView.as_view()),
path('user',Userview.as_view()),
path('logout',Userview.as_view()),
]
Setting Page:
"""
Django settings for login project.
Generated by 'django-admin startproject' using Django 4.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/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/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-k02ug7k7bm-q0cgy4uini(mol=__ye-cm)$c1q+utmhg86ds$7'
# 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',
'myusers',
'rest_framework',
'corsheaders'
]
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 = 'login.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'login.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
AUTH_USER_MODEL = 'myusers.User'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
You're missing an 's', the parameter is called "algorithms" in the decode function:
payload = jwt.decode(token, 'secret', algorithms=['HS256'])
and you're also passing an array of possible values.
When you call encode, the parameter is "algorithm" and only takes a single value.
The reason is that during encoding (i.e signing), you have to use explicitly one algorithm, because a token can only be signed using one algorithm. But during decoding (verifying), you tell the function which algorithms you accept.
Another solution is to downgrade the PyJWT version to 1.7.1, so you wouldn't need to pass the "algorithms" argument.
Like this:
jwt.decode(encoded, verify=False)
I had to pass
verify=False, options={'verify_signature': False} in order to get it working.

400 (Bad Request Vue Js, axios and Django rest framework for POST and PUT Method

My Get and Delete Request is working perfectly. But, getting 400 Bad request while POST or PUT method are calling. And for your kind information my Django rest framework is working fine in POST-MAN and in my local http://127.0.0.1:8000/doctor. And I am including my local machine picture too.
This is working fine. In my Axios code:
data(){
return{
doctors:[],
modalTitle:"",
DoctorName:"",
DoctorId:0,
DoctorNameFilter:"",
DoctorIdFilter:"",
doctorsWithoutFilter:[]
}
},
methods:{
refreshData(){
axios.get(variables.API_URL+"doctor/")
.then((response)=>{
this.doctors=response.data;
this.doctorsWithoutFilter=response.data;
});
},
addClick(){
this.modalTitle="Add Doctor";
this.DoctorId=0;
this.DoctorName="";
},
editClick(doc){
this.modalTitle="Edit Doctor";
this.DoctorId=doc.id;
this.DoctorName=doc.name;
},
createClick(){
axios.post(variables.API_URL+"doctor/",Qs.stringify({
data:this.DoctorName
}))
.then((response)=>{
this.refreshData();
alert(response.data);
});
},
updateClick(){
axios.put(variables.API_URL+"doctor/"+this.DoctorId, Qs.stringify({
data:this.DoctorName
}))
.then((response)=>{
this.refreshData();
alert(response.data);
});
},
deleteClick(id){
if(!confirm("Are you sure?")){
return;
}
axios.delete(variables.API_URL+"doctor/"+id)
.then((response)=>{
this.refreshData();
alert(response.data);
});
},
FilterFn(){
var DoctorIdFilter=this.DoctorIdFilter;
var DoctorNameFilter=this.DoctorNameFilter;
this.doctors=this.doctorsWithoutFilter.filter(
function(el){
return el.DoctorId.toString().toLowerCase().includes(
DoctorIdFilter.toString().trim().toLowerCase()
)&&
el.DoctorName.toString().toLowerCase().includes(
DoctorNameFilter.toString().trim().toLowerCase()
)
});
},
sortResult(prop,asc){
this.doctors=this.doctorsWithoutFilter.sort(function(a,b){
if(asc){
return (a[prop]>b[prop])?1:((a[prop]<b[prop])?-1:0);
}
else{
return (b[prop]>a[prop])?1:((b[prop]<a[prop])?-1:0);
}
})
}
},
mounted:function(){
this.refreshData();
}
}
My Django settings.py:
"""
Django settings for DrAppointment project.
Generated by 'django-admin startproject' using Django 3.2.8.
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/
"""
import os
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-s6!#d2y#rlptr&#e)+0e^=m=n(&!zrqa$byd#pwbgzpogvo8qe'
# 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',
'appointment',
'rest_framework',
'corsheaders',
]
CORS_ORIGIN_ALLOW_ALL = True
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.common.CommonMiddleware',
]
ROOT_URLCONF = 'DrAppointment.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'DrAppointment.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# REST_FRAMEWORK Settings
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
In my view.py :
from django.shortcuts import render, HttpResponse
from .models import Doctors, Appointment
from .serializers import DoctorsSerializer, AppointmentSerializer
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status, generics
from rest_framework import permissions
from rest_framework.decorators import APIView
# from django.views.decorators.csrf import csrf_exempt
#permission_classes((permissions.AllowAny,))
class DoctorList(generics.ListCreateAPIView):
queryset = Doctors.objects.all()
serializer_class = DoctorsSerializer
#permission_classes((permissions.AllowAny,))
class DoctorDetails(generics.RetrieveUpdateDestroyAPIView):
queryset = Doctors.objects.all()
serializer_class = DoctorsSerializer
In My urls.py:
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from appointment import views
# from .views import DoctorList, DoctorDetails
# from .views import doctor_list, doctor_details, appointment_list, appointment_details
urlpatterns = [
path('doctor/', views.DoctorList.as_view()),
path('doctor/<int:pk>', views.DoctorDetails.as_view()),
# path('appointment/', AppointmentList.as_view()),
# path('appointment/<int:pk>', AppointmentDetails.as_view()),
]

Django: TypeError: 'ModelSignal' object is not callable

I have a piece of code throwing an error:
TypeError: 'ModelSignal' object is not callable.
While I'm gonna add signals in my project, this error is occuring.
Why this type of error is occured? What you need to know to give my answer?
Please help me someone. I'm a newbie to Django. Thanks in advance.
Here is my views.py file:
def registerPage(request):
form = CreateUserForm()
if request.method == "POST":
form = CreateUserForm(request.POST)
if form.is_valid():
user =form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account successfully created for ' + username)
return redirect ('login')
context = {'form': form}
return render(request, 'accounts/register.html', context)
My models.py file:
from django.db import models
from django.contrib.auth.models import User
class Student(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
profile_pic = models.ImageField(default= 'default-picture.jpg', null= True, blank= True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return str(self.name)
My signals.py file:
from django.db.models.signals import post_save
from django.contrib.auth.models import Group, User
from .models import Student
def student_profile(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name = 'Student')
instance.groups.add(group)
Student.objects.create(
user = instance,
name = instance.username
)
post_save(student_profile, sender= User)
My apps.py file:
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'accounts'
def ready(self):
import accounts.signals
And my settings.py file:
from pathlib import Path
import os
# 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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1dcgsc#63l$2w_%+90xqra#z=&(q!8sdxf*dg7k6=ptxi&k8o*'
# 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',
'accounts.apps.AccountsConfig',
'django_filters',
]
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 = 'cmp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'cmp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Dhaka'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
You are calling the post_save object which is not callable. Try post_save.connect().
from django.db.models.signals import post_save
from django.contrib.auth.models import Group, User
from .models import Student
def student_profile(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name = 'Student')
instance.groups.add(group)
Student.objects.create(
user = instance,
name = instance.username
)
post_save.connect(student_profile, sender= User)
Or you can also try using receiver decorator:
from django.db.models.signals import post_save
from django.contrib.auth.models import Group, User
from django.dispatch import receiver
from .models import Student
#receiver(post_save, sender=User)
def student_profile(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name = 'Student')
instance.groups.add(group)
Student.objects.create(
user = instance,
name = instance.username
).save()

csrf cookie not set django rest

When working on REST browsable API the responses work fine but when I started working on postman to integrate with front end on the other side the respond become:
{
"detail": "CSRF Failed: CSRF cookie not set."
}
I tried everything to solve this error but nothing change, and checked every question here on CSRF token but still didn't work
These are my codes:
views.py:
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework import status
from User.serializers import UserDataSerializer, ImageSerializer
from rest_framework.views import APIView
from rest_framework import generics
from User.models import UserData,Image
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from rest_framework.renderers import TemplateHTMLRenderer
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
class Signup(APIView):
def post(self, request, format = None):
serializer = UserDataSerializer(data = request.data)
if(serializer.is_valid()):
user = User.objects.create_user(
username = serializer.data['username'],
first_name = serializer.data['first_name'],
last_name = serializer.data['last_name'],
email = serializer.data['email'],
password = serializer.data['password'],
)
#add the name because it is not with create_user method
# user.name = serializer.data['name']
# user.save()
login(request, user)
print ("logged")
text = {'valid' : True , 'errors' :"ur password"+serializer.data['password']}
return JsonResponse(serializer.data)
else:
return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class Login(APIView):
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
serializer = UserDataSerializer(user)
return JsonResponse(serializer.data, status=status.HTTP_302_FOUND)
else:
text = {'valid' : False , 'errors' : "Invalid Username or Password"}
return Response(text, status=status.HTTP_401_UNAUTHORIZED)
class Logout(APIView):
def get(self, request):
logout(request)
return Response({"valid": True}, status=status.HTTP_200_OK)
class ImageUpload(generics.CreateAPIView):
queryset = Image.objects.all()
serializer_class = ImageSerializer
settings.py:
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'baz^+ip1ik4_fla*zg$9q#37e(5jg6tmnwzj4btqw#nw=si)+('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
CSRF_COOKIE_SECURE = False
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'User.apps.UserConfig',
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
# 'django.core.context_processors.csrf',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'app.wsgi.application'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
}
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ImageSearchDB',
'USER': 'root',
'PASSWORD': '1234',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'init_command': 'SET default_storage_engine=INNODB',
}
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# AUTHENTICATION_BACKENDS = (
# 'app.User.backends.EmailOrUsernameModelBackend',
# 'django.contrib.auth.backends.ModelBackend'
# )
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = 'media/'
urls.py
from django.conf.urls import url
from User import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^login/?$', views.Login().as_view()),
url(r'^signup/?$', views.Signup().as_view()),
url(r'^logout/?$', views.Logout().as_view()),
url(r'^trail/?$', views.ImageUpload().as_view())
]
urlpatterns = format_suffix_patterns(urlpatterns) #no need
you have to use ensure_csrf_cookie decorator in the urls like this
from django.views.decorators.csrf import ensure_csrf_cookie
urlpatterns = [
url(r'^login/?$', ensure_csrf_cookie(views.Login().as_view())),
]
Also you need to add all of your CORS settings