I want to send data to database. But the error said return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: dashboard_userusulan.ketua_id
[27/Dec/2021 23:46:14] "POST /dashboard/usulan-penelitian/ HTTP/1.1" 500 196035
Im use CreateView and form_valid() to send the data. I want when i click submit button field 'ketua' automatic create current user.
models.py
class UserUsulan(models.Model):
YEAR_CHOICES = [(r,r) for r in range(1984, datetime.date.today().year+1)]
JENIS_PENELITIAN_CHOICE = (
('DASAR', 'Penelitian Dasar'),
('MADYA', 'Penelitian Madya'),
('UTAMA', 'Penelitian Utama'),
)
BIDANG_PENELITIAN_CHOICE = (
('TEKNOLOGI', 'Teknologi'),
('SAINS', 'Sains'),
('PENDIDIKAN', 'Pendidikan'),
('EKONOMI', 'Ekonomi'),
('HUKUM', 'Hukum'),
('MANAJEMEN', 'Manajemen'),
)
TARGET_LUARAN_CHOICE = (
('JURNAL INTERNASIONAL', 'Jurnal Internasional Bereputasi'),
('JURNAL NASIONAL', 'Jurnal Nasional Terakreditasi'),
('PROSIDING INTERNASIONAL', 'Prosiding Internasional'),
('PROSIDING NASIONAL', 'Prosiding Nasional'),
('HKI', 'Hak Kekayaan Intelektual'),
('BUKU','Buku'),
('PRODUK','Produk'),
)
STATUS_USULAN_CHOICE = (
('DITERIMA', 'Diterima'),
('MENUNGGU', 'Menunggu'),
('DITOLAK', 'Ditolak'),
)
SUMBER_DANA_CHOICE = (
('LP3M', 'DIPA LP3M Universitas Mulia'),
)
SKEMA_PENELITIAN_CHOICE = (
('L', 'Lektor'),
('AA', 'Asisten Ahli'),
('TENDIK', 'Tenaga Pengajar'),
)
tahun = models.IntegerField(_('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
judul_penelitian = models.TextField(blank=True)
jenis_penelitian = models.CharField(max_length=16, blank=True, default="", choices=JENIS_PENELITIAN_CHOICE)
tmt_awal = models.DateField(null=True, blank=True)
tmt_akhir = models.DateField(null=True, blank=True)
bidang_penelitian = models.CharField(max_length=10, blank=True, default="", choices=BIDANG_PENELITIAN_CHOICE)
tujuan_sosial_ekonomi = models.TextField(blank=True)
sumber_dana = models.CharField(max_length=30, blank=True, default="", choices=SUMBER_DANA_CHOICE)
skema_penelitian = models.CharField(max_length=15, blank=True, default="", choices=SKEMA_PENELITIAN_CHOICE)
jumlah_dana_usulan = MoneyField(max_digits=14, decimal_places=2, default_currency='IDR')
target_luaran = models.CharField(max_length=23, blank=True, default="", choices=TARGET_LUARAN_CHOICE)
ketua = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='ketua_penelitian', on_delete=models.CASCADE, null=True, blank=True)
anggota = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='anggota_penelitian')
upload_file = models.FileField(upload_to='Penelitian/', null=True, blank=True)
status_usulan = models.CharField(max_length=8, blank=True, choices=STATUS_USULAN_CHOICE)
jumlah_dana_disetujui = MoneyField(max_digits=14, decimal_places=2, default_currency='IDR', null=True, blank=True)
keterangan_operator = models.TextField(null=True, blank=True)
com_reviewer_1 = models.TextField(null=True, blank=True)
com_reviewer_2 = models.TextField(null=True, blank=True)
views.py
class UserUsulanPenelitian(LoginRequiredMixin, CreateView):
template_name = 'dashboard/usulan-penelitian.html'
form_class = UserUsulanCreatePenelitianForm
success_url = 'dashboard/usulan-penelitian'
def form_valid(self, form):
#fetch user login data and input current user
form.instance.ketua = self.request.user
# form.save()
print(self.request.user)
# message.success(self.request, 'Berhasil Menambahkan Usulan Penelitian')
print('Success Menambahkan Data')
return super().form_valid(form)
Edit ketua field OneToOneField to ForeignKey
ketua = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='ketua_penelitian', on_delete=models.CASCADE, null=True, blank=True)
i have a django rest api with jwt auth , and i have my front end with react js , i have my login function set up like this :
class SessionApi {
static login(data) {
const endpoint = 'http://foody-dev-dev.eu-west-
3.elasticbeanstalk.com/api/auth/jwt/'
const csrfToken = cookie.load('csrftoken')
let lookupOptions = {
method: "POST",
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken,
},
body: JSON.stringify(data),
}
return fetch(endpoint, lookupOptions).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
}
and i have my load Meals function set up like this :
loadProducts(){
const endpoint = 'http://foody-dev-dev.eu-west-3.elasticbeanstalk.com/api/meals/'
const csrfToken = cookie.load('csrftoken')
let thisComp = this
let token = sessionStorage.token
let lookupOptions = {
method: "GET",
headers: {
'Content-Type': 'application/json',
'AUTHORIZATION': `Bearer ${sessionStorage.token}`,
'X-CSRFToken': csrfToken
},
}
fetch(endpoint, lookupOptions)
.then(function(response){
return response.json()
}).then(function(responseData){
console.log(responseData)
thisComp.setState({
products: responseData
})
console.log("Token Stored in meal", token)
}).catch(function(error){
console.log("error", error)
})
}
i succes to login and to get my token but when i try to go to my Products view in react js and run the load meals function i get this error :
Exception Type: TypeError at /api/meals/
Exception Value: int() argument must be a string, a bytes-like object or
a number, not 'AnonymousUser'
Request information:
USER: AnonymousUser
GET: No GET data
POST: No POST data
FILES: No FILES data
COOKIES: No cookie data
META:
CONTENT_TYPE = 'application/json'
CONTEXT_DOCUMENT_ROOT = '/var/www/html'
CONTEXT_PREFIX = ''
DOCUMENT_ROOT = '/var/www/html'
GATEWAY_INTERFACE = 'CGI/1.1'
HTTP_ACCEPT = '*/*'
HTTP_ACCEPT_ENCODING = 'gzip, deflate'
HTTP_ACCEPT_LANGUAGE = 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7'
HTTP_CONNECTION = 'keep-alive'
HTTP_HOST = 'foody-dev-dev.eu-west-3.elasticbeanstalk.com'
HTTP_ORIGIN = 'http://foody-react.s3-website.eu-west-3.amazonaws.com'
HTTP_REFERER = 'http://foody-react.s3-website.eu-west-3.amazonaws.com/'
HTTP_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'
HTTP_X_CSRFTOKEN = 'undefined'
HTTP_X_FORWARDED_FOR = '141.226.122.202'
HTTP_X_FORWARDED_PORT = '80'
HTTP_X_FORWARDED_PROTO = 'http'
PATH_INFO = '/api/meals/'
PATH_TRANSLATED = '/opt/python/current/app/api/wsgi.py/api/meals/'
QUERY_STRING = ''
REMOTE_ADDR = '172.31.16.55'
REMOTE_PORT = '25104'
REQUEST_METHOD = 'GET'
REQUEST_SCHEME = 'http'
REQUEST_URI = '/api/meals/'
SCRIPT_FILENAME = '/opt/python/current/app/api/wsgi.py'
SCRIPT_NAME = ''
SERVER_ADDR = '172.31.36.251'
SERVER_ADMIN = 'root#localhost'
SERVER_NAME = 'foody-dev-dev.eu-west-3.elasticbeanstalk.com'
SERVER_PORT = '80'
SERVER_PROTOCOL = 'HTTP/1.1'
SERVER_SIGNATURE = ''
SERVER_SOFTWARE = 'Apache/2.4.33 (Amazon) mod_wsgi/3.5 Python/3.6.5'
mod_wsgi.application_group = 'ip-172-31-36-251.eu-west-3.compute.internal|'
mod_wsgi.callable_object = 'application'
mod_wsgi.enable_sendfile = '0'
mod_wsgi.handler_script = ''
mod_wsgi.input_chunked = '0'
mod_wsgi.listener_host = ''
mod_wsgi.listener_port = '80'
mod_wsgi.process_group = 'wsgi'
mod_wsgi.queue_start = '1530048823861583'
mod_wsgi.request_handler = 'wsgi-script'
mod_wsgi.script_reloading = '1'
mod_wsgi.version = '(3, 5)'
wsgi.errors = <_io.TextIOWrapper encoding='utf-8'>
wsgi.file_wrapper = ''
wsgi.input = <mod_wsgi.Input object at 0x7fc68ffcc030>
wsgi.multiprocess = True
wsgi.multithread = True
wsgi.run_once = False
wsgi.url_scheme = 'http'
wsgi.version = '(1, 0)'
Settings:
Using settings module api.settings
ABSOLUTE_URL_OVERRIDES = {}
ADMINS = []
ADMIN_MEDIA_PREFIX = '//foody-dev.s3.amazonaws.com/static/admin/'
ALLOWED_HOSTS = ['127.0.0.1', 'foody-delivery.herokuapp.com', '.herokuapp.com', 'www.velty.fr', 'www.velty.fr.herokudns.com', 'foody-dev-dev.eu-west-3.elasticbeanstalk.com']
APPEND_SLASH = True
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']
AUTH_PASSWORD_VALIDATORS = '********************'
AUTH_USER_MODEL = 'auth.User'
AWS_ACCESS_KEY_ID = '********************'
AWS_FILE_EXPIRE = 200
AWS_HEADERS = {'Expires': 'Sunday, 26 August 2018 20:00:00 GMT', 'Cache-Control': 'max-age=5270400'}
AWS_PRELOAD_METADATA = True
AWS_QUERYSTRING_AUTH = False
AWS_SECRET_ACCESS_KEY = '********************'
AWS_STORAGE_BUCKET_NAME = 'foody-dev'
BASE_DIR = '/opt/python/current/app'
CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_KEY_PREFIX = '********************'
CACHE_MIDDLEWARE_SECONDS = 600
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_ALLOW_HEADERS = "('Content-Type', 'Access-Control-Allow-Headers', 'Authorization', 'AUTHORIZATION', 'X-Requested-With', 'credentials')"
CORS_ORIGIN_WHITELIST = "('*', 'your-domain.com', 'your-bucket-here.s3-us-west-2.amazonaws.com', 'foody-dev-dev.eu-west-3.elasticbeanstalk.com')"
CORS_URLS_REGEX = '^/api.*'
CSRF_COOKIE_AGE = 31449600
CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_SECURE = False
CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure'
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'
CSRF_TRUSTED_ORIGINS = []
CSRF_USE_SESSIONS = False
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/opt/python/current/app/db.sqlite3', 'CONN_MAX_AGE': 500, 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'OPTIONS': {}, 'TIME_ZONE': None, 'USER': '', 'PASSWORD': '********************', 'HOST': '', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None}}}
DATABASE_ROUTERS = []
DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440
DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000
DATETIME_FORMAT = 'N j, Y, P'
DATETIME_INPUT_FORMATS = ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M', '%m/%d/%y']
DATE_FORMAT = 'N j, Y'
DATE_INPUT_FORMATS = ['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', '%B %d, %Y', '%d %B %Y', '%d %B, %Y']
DEBUG = True
DEBUG_PROPAGATE_EXCEPTIONS = False
DECIMAL_SEPARATOR = '.'
DEFAULT_CHARSET = 'utf-8'
DEFAULT_CONTENT_TYPE = 'text/html'
DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter'
DEFAULT_FILE_STORAGE = 'api.aws.utils.MediaRootS3BotoStorage'
DEFAULT_FROM_EMAIL = 'webmaster#localhost'
DEFAULT_INDEX_TABLESPACE = ''
DEFAULT_TABLESPACE = ''
DISALLOWED_USER_AGENTS = []
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_HOST_PASSWORD = '********************'
EMAIL_HOST_USER = ''
EMAIL_PORT = 25
EMAIL_SSL_CERTFILE = None
EMAIL_SSL_KEYFILE = '********************'
EMAIL_SUBJECT_PREFIX = '[Django] '
EMAIL_TIMEOUT = None
EMAIL_USE_LOCALTIME = False
EMAIL_USE_SSL = False
EMAIL_USE_TLS = False
FILE_CHARSET = 'utf-8'
FILE_UPLOAD_DIRECTORY_PERMISSIONS = None
FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler']
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440
FILE_UPLOAD_PERMISSIONS = None
FILE_UPLOAD_TEMP_DIR = None
FIRST_DAY_OF_WEEK = 0
FIXTURE_DIRS = []
FORCE_SCRIPT_NAME = None
FORMAT_MODULE_PATH = None
FORM_RENDERER = 'django.forms.renderers.DjangoTemplates'
IGNORABLE_404_URLS = []
INSTALLED_APPS = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'corsheaders', 'rest_framework', 'rest_auth', 'foody']
INTERNAL_IPS = []
JWT_AUTH = {'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'api.utils.jwt_response_payload_handler', 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_AUTH_COOKIE': None}
LANGUAGES = [('af', 'Afrikaans'), ('ar', 'Arabic'), ('ast', 'Asturian'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('be', 'Belarusian'), ('bn', 'Bengali'), ('br', 'Breton'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('dsb', 'Lower Sorbian'), ('el', 'Greek'), ('en', 'English'), ('en-au', 'Australian English'), ('en-gb', 'British English'), ('eo', 'Esperanto'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-co', 'Colombian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('es-ve', 'Venezuelan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy', 'Frisian'), ('ga', 'Irish'), ('gd', 'Scottish Gaelic'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hsb', 'Upper Sorbian'), ('hu', 'Hungarian'), ('ia', 'Interlingua'), ('id', 'Indonesian'), ('io', 'Ido'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('kab', 'Kabyle'), ('kk', 'Kazakh'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lb', 'Luxembourgish'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('mr', 'Marathi'), ('my', 'Burmese'), ('nb', 'Norwegian Bokmål'), ('ne', 'Nepali'), ('nl', 'Dutch'), ('nn', 'Norwegian Nynorsk'), ('os', 'Ossetic'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('sw', 'Swahili'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('tt', 'Tatar'), ('udm', 'Udmurt'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-hans', 'Simplified Chinese'), ('zh-hant', 'Traditional Chinese')]
LANGUAGES_BIDI = ['he', 'ar', 'fa', 'ur']
LANGUAGE_CODE = 'en-us'
LANGUAGE_COOKIE_AGE = None
LANGUAGE_COOKIE_DOMAIN = None
LANGUAGE_COOKIE_NAME = 'django_language'
LANGUAGE_COOKIE_PATH = '/'
LOCALE_PATHS = []
LOGGING = {}
LOGGING_CONFIG = 'logging.config.dictConfig'
LOGIN_REDIRECT_URL = '/accounts/profile/'
LOGIN_URL = '/accounts/login/'
LOGOUT_REDIRECT_URL = None
MANAGERS = []
MEDIA_ROOT = '//foody-dev.s3.amazonaws.com/media/'
MEDIA_URL = '//foody-dev.s3.amazonaws.com/media/'
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
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']
MIGRATION_MODULES = {}
MONTH_DAY_FORMAT = 'F j'
NUMBER_GROUPING = 0
PASSWORD_HASHERS = '********************'
PASSWORD_RESET_TIMEOUT_DAYS = '********************'
PREPEND_WWW = False
REST_FRAMEWORK = {'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.SessionAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication'), 'DEFAULT_PERMISSION_CLASSES': ()}
ROOT_URLCONF = 'api.urls'
S3DIRECT_REGION = 'us-west-2'
S3_URL = '//foody-dev.s3.amazonaws.com/'
SECRET_KEY = '********************'
SECURE_BROWSER_XSS_FILTER = False
SECURE_CONTENT_TYPE_NOSNIFF = False
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
SECURE_HSTS_SECONDS = 0
SECURE_PROXY_SSL_HEADER = None
SECURE_REDIRECT_EXEMPT = []
SECURE_SSL_HOST = None
SECURE_SSL_REDIRECT = False
SERVER_EMAIL = 'root#localhost'
SESSION_CACHE_ALIAS = 'default'
SESSION_COOKIE_AGE = 1209600
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_NAME = 'sessionid'
SESSION_COOKIE_PATH = '/'
SESSION_COOKIE_SECURE = False
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_FILE_PATH = None
SESSION_SAVE_EVERY_REQUEST = False
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
SETTINGS_MODULE = 'api.settings'
SHORT_DATETIME_FORMAT = 'm/d/Y P'
SHORT_DATE_FORMAT = 'm/d/Y'
SIGNING_BACKEND = 'django.core.signing.TimestampSigner'
SILENCED_SYSTEM_CHECKS = []
STATICFILES_DIRS = ['/opt/python/current/app/staticfiles']
STATICFILES_FINDERS = ['django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder']
STATICFILES_STORAGE = 'api.aws.utils.StaticRootS3BotoStorage'
STATIC_ROOT = '/opt/python/current/staticfiles/static-cdn-local/../www'
STATIC_URL = '//foody-dev.s3.amazonaws.com/static/'
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']}}]
TEST_NON_SERIALIZED_APPS = []
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
THOUSAND_SEPARATOR = ','
TIME_FORMAT = 'P'
TIME_INPUT_FORMATS = ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
TIME_ZONE = 'UTC'
USE_ETAGS = False
USE_I18N = True
USE_L10N = True
USE_THOUSAND_SEPARATOR = False
USE_TZ = True
USE_X_FORWARDED_HOST = False
USE_X_FORWARDED_PORT = False
WSGI_APPLICATION = 'api.wsgi.application'
X_FRAME_OPTIONS = 'SAMEORIGIN'
YEAR_MONTH_FORMAT = 'F Y'
My backend looks like this :
urls.py :
from django.contrib import admin
from django.views.generic import TemplateView
from django.urls import path, include, re_path
from django.conf.urls.static import static
from django.conf import settings
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
urlpatterns = [
path('admin/', admin.site.urls),
path('api/auth/jwt/', obtain_jwt_token),
path('api/auth/jwt/refresh/', refresh_jwt_token),
path('api/meals/', include('foody.urls'))
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
"""
Django settings for api project.
Generated by 'django-admin startproject' using Django 1.11.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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.dirname(os.path.abspath(__file__))))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY','qj$in1cz)+2e#kc14q(6#0dx&jjq0wn$77u08!ncdq%-knz0y0')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1','foody-delivery.herokuapp.com','.herokuapp.com', 'www.velty.fr','www.velty.fr.herokudns.com','foody-dev-dev.eu-west-3.elasticbeanstalk.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'storages',
'corsheaders',
'rest_framework',
'rest_auth',
'foody',
]
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',
]
ROOT_URLCONF = 'api.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 = 'api.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
AWS_ACCESS_KEY_ID = "AKIAIL3JMMDWLIYBOYMA"
AWS_SECRET_ACCESS_KEY = "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"
if 'RDS_DB_NAME' in os.environ:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ['RDS_DB_NAME'],
'USER': os.environ['RDS_USERNAME'],
'PASSWORD': os.environ['RDS_PASSWORD'],
'HOST': os.environ['RDS_HOSTNAME'],
'PORT': os.environ['RDS_PORT'],
}
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# add this
import dj_database_url
db_from_env = dj_database_url.config()
DATABASES['default'].update(db_from_env)
DATABASES['default']['CONN_MAX_AGE'] = 500
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/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.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'staticfiles'),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles', 'static-cdn-local','..', 'www')
MEDIA_ROOT = os.path.join((BASE_DIR) ,'staticfiles', 'media-root')
MEDIA_URL = '/media/'
CORS_URLS_REGEX = r'^/api.*'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_ALLOW_HEADERS = (
"Content-Type",
"Access-Control-Allow-Headers",
"Authorization",
"AUTHORIZATION",
"X-Requested-With",
"credentials"
)
CORS_ORIGIN_WHITELIST = (
'*',
'your-domain.com',
'your-bucket-here.s3-us-west-2.amazonaws.com',
'foody-dev-dev.eu-west-3.elasticbeanstalk.com'
)
from api.restconf.main import *
from api.aws.conf import *
views.py :
from rest_framework import generics, permissions
from .serializers import MealSerializer
from .models import Meal
from .permissions import IsOwnerOrReadOnly
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication
class MealDetailAPIView(generics.RetrieveUpdateDestroyAPIView):
queryset = Meal.objects.all()
serializer_class = MealSerializer
lookup_field = 'id'
permission_classes = [IsOwnerOrReadOnly]
class MealListCreateAPIView(generics.ListCreateAPIView):
queryset = Meal.objects.all()
serializer_class = MealSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get_queryset(self):
request = self.request
qs = Meal.objects.filter(user = request.user).order_by("-id")
query = request.GET.get('q')
if query is not None:
qs = qs.filter(name__icontains=query, description__icontains=query)
return qs
def perform_create(self, serializer):
serializer.save(user = self.request.user)
Thanks in advance for your help
I'm developing an API with Django REST. The client is a SPA in AngularJS running in node.js. Register and Login work fine, but when the user does logout the error message is showed:
{"detail":"Authentication credentials were not provided."}
I tried many solutions, like post 1 and post 2. but the problem continues. If my Angular files are in the server, my page works fine, but when I changed for a SPA created by yeoman, I have the credentials problem.
My settings.py
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.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y6u0gy4ij&8uoo6#p*$qukwp$-07#-1gd)#)(l!-j&wmpot4h#'
# 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',
'authentication',
'corsheaders',
]
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.auth.middleware.SessionAuthenticationMiddleware', #
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ServerLearn.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',
],
},
},
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
}
WSGI_APPLICATION = 'ServerLearn.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/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.11/howto/static-files/
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'authentication.Account'
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api/v1/.*$'
My models.py
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
# Create your models here.
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
token = Token.objects.create(user=instance)
print(token)
class AccountManager(BaseUserManager):
def create_user(self, username, password=None, **kwargs):
if not username:
raise ValueError("Need username.")
if not kwargs.get("email"):
raise ValueError("Need email.")
account = self.model(
username = username,
email = self.normalize_email(kwargs.get("email")),
name = kwargs.get("name"),
age = kwargs.get("age"),
gender = kwargs.get("gender"),
#birth = kwargs.get("birth")
)
account.set_password(password)
account.save()
return account
#admin
#senhaadmin
def create_superuser(self, username, password, **kwargs):
account = self.model(
username = username,
email = self.normalize_email(kwargs.get("email")),
name = "Admin",
age = 31111,
gender = 555,
)
account.is_admin = True
account.set_password(password)
account.save()
return account
class Account(AbstractBaseUser):
username = models.CharField(max_length = 50, unique = True)
email = models.EmailField(unique = True)
name = models.CharField(max_length = 100)
age = models.PositiveSmallIntegerField()
gender = models.PositiveSmallIntegerField()
#birth = models.DateField(null = True, blank = True)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
is_admin = models.BooleanField(default = False)
objects = AccountManager()
USERNAME_FIELD = 'username'
REQUIRED_FILES = ['username', 'email', 'name', 'age', 'gender']
def __unicode__ (self):
return self.username
My views.py
class AccountViewSet(viewsets.ModelViewSet):
lookup_field = 'username'
queryset = Account.objects.all()
serializer_class = AccountSerializer
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
return (permissions.AllowAny(),)
if self.request.method == 'POST':
return (permissions.AllowAny(),)
return (permissions.IsAuthenticated(), IsAccountOwner(),)
def create(self, request):
serializer = self.serializer_class(data = request.data)
if serializer.is_valid():
Account.objects.create_user(**serializer.validated_data)
return Response(serializer.validated_data, status = status.HTTP_201_CREATED)
return Response({
'status': 'Bad request',
'message': 'Conta não pode ser criada'
}, status = status.HTTP_400_BAD_REQUEST)
class LoginView(views.APIView):
def post(self, request, format=None):
data = json.loads(request.body.decode('utf-8'))
username = data.get('username', None)
password = data.get('password', None)
account = authenticate(username=username, password=password)
if account is not None:
if account.is_active:
login(request, account)
serialized = AccountSerializer(account)
return Response(serialized.data)
else:
return Response({
'status': 'Unauthorized',
'message': 'This account has been disabled.'
}, status=status.HTTP_401_UNAUTHORIZED)
else:
return Response({
'status': 'Unauthorized',
'message': 'Username/password combination invalid.'
}, status=status.HTTP_401_UNAUTHORIZED)
class LogoutView(views.APIView):
#ERROR IN NEXT LINE
permission_classes = (permissions.IsAuthenticated,)
def post(self, request, format=None):
logout(request)
return Response({}, status=status.HTTP_204_NO_CONTENT)
In my Angular application, in app.js
app.run(run);
run.$inject = ['$http'];
function run($http) {
$http.defaults.xsrfHeaderName = 'X-CSRFToken';
$http.defaults.xsrfCookieName = 'csrftoken';
}
I get token after login with code:
$http.post('http://localhost:8000/api/v1/api-token-auth/', {
username: username,
password: password
}).then(tokenSuccessFn, tokenErrorFn);
function tokenSuccessFn(data, status, headers, config) {
console.log("token: ");
console.log(JSON.stringify(data));
$http.defaults.headers.common.Authorization = 'Token ' + $cookies.get("csrftoken");
}
function tokenErrorFn(data, status, headers, config) {
console.error('token error !!!');
}
The logout is
return $http.post('http://localhost:8000/api/v1/auth/logout/')
.then(logoutSuccessFn, logoutErrorFn);
function logoutSuccessFn(data, status, headers, config) {
Authentication.unauthenticate();
window.location = '/';
}
function logoutErrorFn(data, status, headers, config) {
console.error('Logout error !!!');
}
remove 'rest_framework.authentication.SessionAuthentication' from your DRF DEFAULT_AUTHENTICATION_CLASSES,only use TokenAuth,if you still need browsable api,you can use chrome plugin ModHeader.
I found the problem. I didn't add the token to header correctly.
I get the token and storage in a local storage.
$http.post('http://localhost:8000/api/v1/api-token-auth/', {
username: username,
password: password
}).then(tokenSuccessFn, tokenErrorFn);
function tokenSuccessFn(data, status, headers, config) {
localStorage.setItem('myApp.token',data['data'].token);
}
function tokenErrorFn(data, status, headers, config) {
console.error('token error !!!');
}
When the app (page) begins, I load the token from local storage in app.js:
app.run(['$http', function ($http) {
$http.defaults.headers.common['Authorization'] = 'Token ' + localStorage.getItem('myApp.token');
}]);
Thanks Ykh for the help.