Popular New Releases in Internationalization
formatjs
react-intl@5.25.0
globalize
Version 1.6.0
angular-translate
js-lingui
v3.13.2
website
snapshot-initial-v1.23: Release 1.23
Popular Libraries in Internationalization
by formatjs typescript
13086
The monorepo home to all of the FormatJS related libraries, most notably react-intl.
by i18next javascript
7228 MIT
Internationalization for react done right. Using the i18next i18n ecosystem.
by sebastianbergmann php
5872 BSD-3-Clause
Library that helps with managing the version number of Git-hosted PHP projects
by globalizejs javascript
4517 MIT
A JavaScript library for internationalization and localization that leverages the official Unicode CLDR JSON data
by angular-translate javascript
4420 MIT
Translating your AngularJS 1.x apps
by ngx-translate typescript
3964 MIT
The internationalization (i18n) library for Angular
by fnando ruby
3551 MIT
It's a small library to provide the I18n translations on the Javascript. It comes with Rails support.
by airbnb javascript
3515 BSD-2-Clause
Give your JavaScript the ability to speak many languages.
by lingui typescript
3270 MIT
🌍📖 A readable, automated, and optimized (5 kb) internationalization for JavaScript
Trending New libraries in Internationalization
by mohakapt swift
536
A lightweight and powerful editor for localizing iOS, macOS, tvOS, and watchOS applications.
by unicode-org rust
497 NOASSERTION
Solving i18n for client-side and resource-constrained environments.
by microsoft html
288 MIT
Generate .strings files directly from your code
by fkirc typescript
243 MIT
Translate JSON, YAML or other formats in a continuous workflow
by clovaai python
237 MIT
Evaluating Weakly Supervised Object Localization Methods Right (CVPR 2020)
by amannn typescript
211 MIT
A minimal, but complete solution for internationalization in Next.js apps. 🌐
by Arbify php
204 Apache-2.0
ARB files localization tool. Dedicated to Flutter and its intl package.
by tolgee kotlin
142 Apache-2.0
Server & Web App of Tolgee localization toolkit
by PRBonn python
134 MIT
chen2020iros: Learning an Overlap-based Observation Model for 3D LiDAR Localization.
Top Authors in Internationalization
1
10 Libraries
206
2
9 Libraries
14654
3
9 Libraries
389
4
8 Libraries
707
5
7 Libraries
8036
6
7 Libraries
19
7
7 Libraries
22
8
5 Libraries
1804
9
5 Libraries
249
10
5 Libraries
148
1
10 Libraries
206
2
9 Libraries
14654
3
9 Libraries
389
4
8 Libraries
707
5
7 Libraries
8036
6
7 Libraries
19
7
7 Libraries
22
8
5 Libraries
1804
9
5 Libraries
249
10
5 Libraries
148
Trending Kits in Internationalization
No Trending Kits are available at this moment for Internationalization
Trending Discussions on Internationalization
How to use TypeScript to make sure two objects have a same structure (without interface)?
django charfield not showing in admin panel
MQL4 WebRequest POST Json to Django API using Django rest framework, getting \x00 at the end of body
Why my translations in django i18n don't work
How to insert a <a> tag or icon inside Vuetify internationalization?
Show Two Languages at once
ERRORS: inside.UserProfile.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
is runtime language translation possible with angular (@angular/localize)?
How to generate dynamic paths for non-default locales in Next.js?
Is my django post method even being called?
QUESTION
How to use TypeScript to make sure two objects have a same structure (without interface)?
Asked 2022-Apr-15 at 15:19I'm currently working on a web project which heavily utilizes internationalization (i18n) and I have a hard time figuring out how to make sure all languages share exact same keys.
Here's a simple example of src/lang/en.ts
file:
1export default {
2 title: "My Website Project",
3 description: "This is an example of a file which contains phrases and their keys",
4 hello: "Hello!",
5};
6
and here's a simple example of src/lang/id.ts
file:
1export default {
2 title: "My Website Project",
3 description: "This is an example of a file which contains phrases and their keys",
4 hello: "Hello!",
5};
6export default {
7 title: "Proyek Website Saya",
8 description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
9 hello: "Halo!",
10};
11
Now, I want TypeScript to make sure those files have same keys (not more, not less). So if I put cat
property into src/lang/id.ts
, then:
1export default {
2 title: "My Website Project",
3 description: "This is an example of a file which contains phrases and their keys",
4 hello: "Hello!",
5};
6export default {
7 title: "Proyek Website Saya",
8 description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
9 hello: "Halo!",
10};
11export default {
12 title: "Proyek Website Saya",
13 description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
14 hello: "Halo!",
15 cat: "Kucing", // <-- this must be error because "cat" doesn't exist in en.ts file!
16};
17
But I can't build an interface like this
1export default {
2 title: "My Website Project",
3 description: "This is an example of a file which contains phrases and their keys",
4 hello: "Hello!",
5};
6export default {
7 title: "Proyek Website Saya",
8 description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
9 hello: "Halo!",
10};
11export default {
12 title: "Proyek Website Saya",
13 description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
14 hello: "Halo!",
15 cat: "Kucing", // <-- this must be error because "cat" doesn't exist in en.ts file!
16};
17export default interface LanguageStruct {
18 title: string,
19 description: string,
20 hello: string,
21};
22
Because there's hundreds of phrases for each language in the real project and writing those keys one-by-one would be both time consuming and exhausting. I wonder if there's a trick to do with TypeScript for that problem, or at least there's some kind of automation to do that job.
ANSWER
Answered 2022-Apr-15 at 15:19Use keyof typeof someObject
to construct a type from the keys of an object (e.g. the first language strings). Then restrict your other object (the other languages) to have that type as key, and string as value using Record
. So the type you're looking for is Record<keyof typeof someObject, string>
. Example:
1export default {
2 title: "My Website Project",
3 description: "This is an example of a file which contains phrases and their keys",
4 hello: "Hello!",
5};
6export default {
7 title: "Proyek Website Saya",
8 description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
9 hello: "Halo!",
10};
11export default {
12 title: "Proyek Website Saya",
13 description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
14 hello: "Halo!",
15 cat: "Kucing", // <-- this must be error because "cat" doesn't exist in en.ts file!
16};
17export default interface LanguageStruct {
18 title: string,
19 description: string,
20 hello: string,
21};
22const en = {
23 title: "My Website Project",
24 description: "This is an example of a file which contains phrases and their keys",
25 hello: "Hello!",
26};
27
28const de: Record<keyof typeof en, string> = {
29 title: "Proyek Website Saya",
30 description: "Ini adalah contoh dari sebuah file yang mengandung beberapa frasa beserta kata kuncinya",
31 hello: "Halo!",
32 cat: "Kucing", // this is highlighted as an error
33};
34
See working example here.
QUESTION
django charfield not showing in admin panel
Asked 2022-Feb-25 at 07:43i create a model in django and register it in admin.py when i go to admin panel it shows the model but when i want to create object it doesn't show the charfields and i can just create the oject without any details
this is my codes below
view.py
1from django.shortcuts import render
2from django.http import HttpResponse
3from .models import Feature
4
5# Create your views here.
6def index(request):
7 features = Feature.objects.all()
8 return render(request, 'index.html', {'features' : features})
9
model.py
1from django.shortcuts import render
2from django.http import HttpResponse
3from .models import Feature
4
5# Create your views here.
6def index(request):
7 features = Feature.objects.all()
8 return render(request, 'index.html', {'features' : features})
9from django.db import models
10
11# Create your models here.
12class Feature(models.Model):
13 name: models.CharField(max_length=100)
14 details: models.CharField(max_length=200)
15
stting.py
1from django.shortcuts import render
2from django.http import HttpResponse
3from .models import Feature
4
5# Create your views here.
6def index(request):
7 features = Feature.objects.all()
8 return render(request, 'index.html', {'features' : features})
9from django.db import models
10
11# Create your models here.
12class Feature(models.Model):
13 name: models.CharField(max_length=100)
14 details: models.CharField(max_length=200)
15"""
16Django settings for myproject project.
17
18Generated by 'django-admin startproject' using Django 3.2.12.
19
20For more information on this file, see
21
22For the full list of settings and their values, see
23 """
24
25from pathlib import Path
26import os
27
28# Build paths inside the project like this: BASE_DIR / 'subdir'.
29BASE_DIR = Path(__file__).resolve().parent.parent
30
31
32# Quick-start development settings - unsuitable for production
33
34# SECURITY WARNING: keep the secret key used in production secret!
35SECRET_KEY = 'django-insecure-dubzu2qq@tk9lk%d05a*@j1rd1hkr$v72eiga+*u7%v2d)19_5'
36
37# SECURITY WARNING: don't run with debug turned on in production!
38DEBUG = True
39
40ALLOWED_HOSTS = []
41
42
43# Application definition
44
45INSTALLED_APPS = [
46 'livesync',
47 'django.contrib.admin',
48 'django.contrib.auth',
49 'django.contrib.contenttypes',
50 'django.contrib.sessions',
51 'django.contrib.messages',
52 'django.contrib.staticfiles',
53 'myapp'
54]
55
56MIDDLEWARE = [
57 'livesync.core.middleware.DjangoLiveSyncMiddleware',
58 'django.middleware.security.SecurityMiddleware',
59 'django.contrib.sessions.middleware.SessionMiddleware',
60 'django.middleware.common.CommonMiddleware',
61 'django.middleware.csrf.CsrfViewMiddleware',
62 'django.contrib.auth.middleware.AuthenticationMiddleware',
63 'django.contrib.messages.middleware.MessageMiddleware',
64 'django.middleware.clickjacking.XFrameOptionsMiddleware',
65]
66
67ROOT_URLCONF = 'myproject.urls'
68
69TEMPLATES = [
70 {
71 'BACKEND': 'django.template.backends.django.DjangoTemplates',
72 'DIRS': [BASE_DIR, 'templates'],
73 'APP_DIRS': True,
74 'OPTIONS': {
75 'context_processors': [
76 'django.template.context_processors.debug',
77 'django.template.context_processors.request',
78 'django.contrib.auth.context_processors.auth',
79 'django.contrib.messages.context_processors.messages',
80 ],
81 },
82 },
83]
84
85WSGI_APPLICATION = 'myproject.wsgi.application'
86
87
88# Database
89
90DATABASES = {
91 'default': {
92 'ENGINE': 'django.db.backends.sqlite3',
93 'NAME': BASE_DIR / 'db.sqlite3',
94 }
95}
96
97
98# Password validation
99
100AUTH_PASSWORD_VALIDATORS = [
101 {
102 'NAME':
103'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
104 },
105 {
106 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
107 },
108 {
109 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
110 },
111 {
112 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
113 },
114]
115
116
117# Internationalization
118
119LANGUAGE_CODE = 'en-us'
120
121TIME_ZONE = 'UTC'
122
123USE_I18N = True
124
125USE_L10N = True
126
127USE_TZ = True
128
129
130# Static files (CSS, JavaScript, Images)
131
132STATIC_URL = '/static/'
133STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
134
135# Default primary key field type
136
137DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
138
admin.py
1from django.shortcuts import render
2from django.http import HttpResponse
3from .models import Feature
4
5# Create your views here.
6def index(request):
7 features = Feature.objects.all()
8 return render(request, 'index.html', {'features' : features})
9from django.db import models
10
11# Create your models here.
12class Feature(models.Model):
13 name: models.CharField(max_length=100)
14 details: models.CharField(max_length=200)
15"""
16Django settings for myproject project.
17
18Generated by 'django-admin startproject' using Django 3.2.12.
19
20For more information on this file, see
21
22For the full list of settings and their values, see
23 """
24
25from pathlib import Path
26import os
27
28# Build paths inside the project like this: BASE_DIR / 'subdir'.
29BASE_DIR = Path(__file__).resolve().parent.parent
30
31
32# Quick-start development settings - unsuitable for production
33
34# SECURITY WARNING: keep the secret key used in production secret!
35SECRET_KEY = 'django-insecure-dubzu2qq@tk9lk%d05a*@j1rd1hkr$v72eiga+*u7%v2d)19_5'
36
37# SECURITY WARNING: don't run with debug turned on in production!
38DEBUG = True
39
40ALLOWED_HOSTS = []
41
42
43# Application definition
44
45INSTALLED_APPS = [
46 'livesync',
47 'django.contrib.admin',
48 'django.contrib.auth',
49 'django.contrib.contenttypes',
50 'django.contrib.sessions',
51 'django.contrib.messages',
52 'django.contrib.staticfiles',
53 'myapp'
54]
55
56MIDDLEWARE = [
57 'livesync.core.middleware.DjangoLiveSyncMiddleware',
58 'django.middleware.security.SecurityMiddleware',
59 'django.contrib.sessions.middleware.SessionMiddleware',
60 'django.middleware.common.CommonMiddleware',
61 'django.middleware.csrf.CsrfViewMiddleware',
62 'django.contrib.auth.middleware.AuthenticationMiddleware',
63 'django.contrib.messages.middleware.MessageMiddleware',
64 'django.middleware.clickjacking.XFrameOptionsMiddleware',
65]
66
67ROOT_URLCONF = 'myproject.urls'
68
69TEMPLATES = [
70 {
71 'BACKEND': 'django.template.backends.django.DjangoTemplates',
72 'DIRS': [BASE_DIR, 'templates'],
73 'APP_DIRS': True,
74 'OPTIONS': {
75 'context_processors': [
76 'django.template.context_processors.debug',
77 'django.template.context_processors.request',
78 'django.contrib.auth.context_processors.auth',
79 'django.contrib.messages.context_processors.messages',
80 ],
81 },
82 },
83]
84
85WSGI_APPLICATION = 'myproject.wsgi.application'
86
87
88# Database
89
90DATABASES = {
91 'default': {
92 'ENGINE': 'django.db.backends.sqlite3',
93 'NAME': BASE_DIR / 'db.sqlite3',
94 }
95}
96
97
98# Password validation
99
100AUTH_PASSWORD_VALIDATORS = [
101 {
102 'NAME':
103'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
104 },
105 {
106 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
107 },
108 {
109 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
110 },
111 {
112 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
113 },
114]
115
116
117# Internationalization
118
119LANGUAGE_CODE = 'en-us'
120
121TIME_ZONE = 'UTC'
122
123USE_I18N = True
124
125USE_L10N = True
126
127USE_TZ = True
128
129
130# Static files (CSS, JavaScript, Images)
131
132STATIC_URL = '/static/'
133STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
134
135# Default primary key field type
136
137DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
138 from django.contrib import admin
139from .models import Feature
140
141
142# Register your models here.
143admin.site.register(Feature)
144
this screenshot is from my admin panel > add Feature (myModel) and it shows nothing.
ANSWER
Answered 2022-Feb-25 at 07:43You are using a @dataclass
way of defining your model. I'm not aware that will work ... It should be:
1from django.shortcuts import render
2from django.http import HttpResponse
3from .models import Feature
4
5# Create your views here.
6def index(request):
7 features = Feature.objects.all()
8 return render(request, 'index.html', {'features' : features})
9from django.db import models
10
11# Create your models here.
12class Feature(models.Model):
13 name: models.CharField(max_length=100)
14 details: models.CharField(max_length=200)
15"""
16Django settings for myproject project.
17
18Generated by 'django-admin startproject' using Django 3.2.12.
19
20For more information on this file, see
21
22For the full list of settings and their values, see
23 """
24
25from pathlib import Path
26import os
27
28# Build paths inside the project like this: BASE_DIR / 'subdir'.
29BASE_DIR = Path(__file__).resolve().parent.parent
30
31
32# Quick-start development settings - unsuitable for production
33
34# SECURITY WARNING: keep the secret key used in production secret!
35SECRET_KEY = 'django-insecure-dubzu2qq@tk9lk%d05a*@j1rd1hkr$v72eiga+*u7%v2d)19_5'
36
37# SECURITY WARNING: don't run with debug turned on in production!
38DEBUG = True
39
40ALLOWED_HOSTS = []
41
42
43# Application definition
44
45INSTALLED_APPS = [
46 'livesync',
47 'django.contrib.admin',
48 'django.contrib.auth',
49 'django.contrib.contenttypes',
50 'django.contrib.sessions',
51 'django.contrib.messages',
52 'django.contrib.staticfiles',
53 'myapp'
54]
55
56MIDDLEWARE = [
57 'livesync.core.middleware.DjangoLiveSyncMiddleware',
58 'django.middleware.security.SecurityMiddleware',
59 'django.contrib.sessions.middleware.SessionMiddleware',
60 'django.middleware.common.CommonMiddleware',
61 'django.middleware.csrf.CsrfViewMiddleware',
62 'django.contrib.auth.middleware.AuthenticationMiddleware',
63 'django.contrib.messages.middleware.MessageMiddleware',
64 'django.middleware.clickjacking.XFrameOptionsMiddleware',
65]
66
67ROOT_URLCONF = 'myproject.urls'
68
69TEMPLATES = [
70 {
71 'BACKEND': 'django.template.backends.django.DjangoTemplates',
72 'DIRS': [BASE_DIR, 'templates'],
73 'APP_DIRS': True,
74 'OPTIONS': {
75 'context_processors': [
76 'django.template.context_processors.debug',
77 'django.template.context_processors.request',
78 'django.contrib.auth.context_processors.auth',
79 'django.contrib.messages.context_processors.messages',
80 ],
81 },
82 },
83]
84
85WSGI_APPLICATION = 'myproject.wsgi.application'
86
87
88# Database
89
90DATABASES = {
91 'default': {
92 'ENGINE': 'django.db.backends.sqlite3',
93 'NAME': BASE_DIR / 'db.sqlite3',
94 }
95}
96
97
98# Password validation
99
100AUTH_PASSWORD_VALIDATORS = [
101 {
102 'NAME':
103'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
104 },
105 {
106 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
107 },
108 {
109 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
110 },
111 {
112 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
113 },
114]
115
116
117# Internationalization
118
119LANGUAGE_CODE = 'en-us'
120
121TIME_ZONE = 'UTC'
122
123USE_I18N = True
124
125USE_L10N = True
126
127USE_TZ = True
128
129
130# Static files (CSS, JavaScript, Images)
131
132STATIC_URL = '/static/'
133STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
134
135# Default primary key field type
136
137DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
138 from django.contrib import admin
139from .models import Feature
140
141
142# Register your models here.
143admin.site.register(Feature)
144class Feature(models.Model):
145 name = models.CharField(max_length=100)
146 details = models.CharField(max_length=200)
147
Also, have you run migrations? (I suspect not or I think you'd have seen an error here). You should run python manage.py makemigrations
followed by python manage.py migrate
when you create or amend a model definition - this is what creates/changes it in the DB, and without that there's not a lot to display in admin anyway ...
It's possible if you ran migrate it created an "empty" model maybe, since you were missing the =
- I really don't know exactly what this code would do without testing it.
QUESTION
MQL4 WebRequest POST Json to Django API using Django rest framework, getting \x00 at the end of body
Asked 2022-Feb-17 at 08:16I am using Django only for few weeks so there might be some mistakes.
I have an API using Django rest framework, which seems to work well. Using postman every thing is ok
I send data using WebRequest in Mql4 to the api
1string data = "{ ... }“;
2char post_data[];
3post_data = StringToCharArray(data, post_data, WHOLE_ARRAY);
4int r = WebRequest("POST", "http://127.0.0.1/api/symbol/","Content-Type: application/json",5000, data,res_data, res_headers);
5
The data given to WebRequest is fine but the function add \x00 at the end of body.
Here is my post data when it arrive to Django rest framework
1string data = "{ ... }“;
2char post_data[];
3post_data = StringToCharArray(data, post_data, WHOLE_ARRAY);
4int r = WebRequest("POST", "http://127.0.0.1/api/symbol/","Content-Type: application/json",5000, data,res_data, res_headers);
5{'Content-Length': '982', 'Content-Type': 'application/json', 'Accept': 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*', 'Host': '127.0.0.1', 'Accept-Language': 'fr,en', 'Accept-Charset': '*,utf-8', 'Connection': 'Keep-Alive', 'Proxy-Connection': 'Keep-Alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'User-Agent': 'MetaTrader 4 Terminal/4.1353 (Windows NT 6.1; x86)'}
6b'{"name": "GOLDs","date_market": "2022-02-01T00:00:00.000000Z","period": "M1","open_price": 1797.64,"close_price": 1870.91,"low_price": 1788.33,"high_price": 1879.12,"bollinger_band":[{"period":"M1","moving_average_period":20,"standard_deviation":1.5,"high":1936.06829,"low":1717.61271,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2,"high":1972.47755,"low":1681.20345,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2.5,"high":2008.88681,"low":1644.79419,"moving_average":1826.8405}],"moving_average":[{"period":"M1","moving_average_period":50,"type": "0","value":1569.6854},{"period":"M1","moving_average_period":100,"type": "0","value":1399.8002},{"period":"M1","moving_average_period":200,"type": "0","value":1245.38985}],"MACD_zerolag":[{"period":"M1","fast_EMA_period":12,"slow_EMA_period":26,"signal_EMA_period":9,"histogram_value":-0.01794,"signal_value":0.09465,"MACD_value":0.07671}]}\x00'
7
so I get the following error :
1string data = "{ ... }“;
2char post_data[];
3post_data = StringToCharArray(data, post_data, WHOLE_ARRAY);
4int r = WebRequest("POST", "http://127.0.0.1/api/symbol/","Content-Type: application/json",5000, data,res_data, res_headers);
5{'Content-Length': '982', 'Content-Type': 'application/json', 'Accept': 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*', 'Host': '127.0.0.1', 'Accept-Language': 'fr,en', 'Accept-Charset': '*,utf-8', 'Connection': 'Keep-Alive', 'Proxy-Connection': 'Keep-Alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'User-Agent': 'MetaTrader 4 Terminal/4.1353 (Windows NT 6.1; x86)'}
6b'{"name": "GOLDs","date_market": "2022-02-01T00:00:00.000000Z","period": "M1","open_price": 1797.64,"close_price": 1870.91,"low_price": 1788.33,"high_price": 1879.12,"bollinger_band":[{"period":"M1","moving_average_period":20,"standard_deviation":1.5,"high":1936.06829,"low":1717.61271,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2,"high":1972.47755,"low":1681.20345,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2.5,"high":2008.88681,"low":1644.79419,"moving_average":1826.8405}],"moving_average":[{"period":"M1","moving_average_period":50,"type": "0","value":1569.6854},{"period":"M1","moving_average_period":100,"type": "0","value":1399.8002},{"period":"M1","moving_average_period":200,"type": "0","value":1245.38985}],"MACD_zerolag":[{"period":"M1","fast_EMA_period":12,"slow_EMA_period":26,"signal_EMA_period":9,"histogram_value":-0.01794,"signal_value":0.09465,"MACD_value":0.07671}]}\x00'
7POST /api/symbol/ - 400
8{'Content-Type': 'application/json', 'Vary': 'Accept', 'Allow': 'GET, POST, HEAD, OPTIONS'}
9b'{"detail":"JSON parse error - Extra data: line 1 column 982 (char 981)"}'
10
if a send the same data removing the \x00 with Postman every thing goes well.
Is there a misconfiguration client side with mql4 ?
Or can I remove the received data to remove this \x00 ?
Here is my models.py
1string data = "{ ... }“;
2char post_data[];
3post_data = StringToCharArray(data, post_data, WHOLE_ARRAY);
4int r = WebRequest("POST", "http://127.0.0.1/api/symbol/","Content-Type: application/json",5000, data,res_data, res_headers);
5{'Content-Length': '982', 'Content-Type': 'application/json', 'Accept': 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*', 'Host': '127.0.0.1', 'Accept-Language': 'fr,en', 'Accept-Charset': '*,utf-8', 'Connection': 'Keep-Alive', 'Proxy-Connection': 'Keep-Alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'User-Agent': 'MetaTrader 4 Terminal/4.1353 (Windows NT 6.1; x86)'}
6b'{"name": "GOLDs","date_market": "2022-02-01T00:00:00.000000Z","period": "M1","open_price": 1797.64,"close_price": 1870.91,"low_price": 1788.33,"high_price": 1879.12,"bollinger_band":[{"period":"M1","moving_average_period":20,"standard_deviation":1.5,"high":1936.06829,"low":1717.61271,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2,"high":1972.47755,"low":1681.20345,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2.5,"high":2008.88681,"low":1644.79419,"moving_average":1826.8405}],"moving_average":[{"period":"M1","moving_average_period":50,"type": "0","value":1569.6854},{"period":"M1","moving_average_period":100,"type": "0","value":1399.8002},{"period":"M1","moving_average_period":200,"type": "0","value":1245.38985}],"MACD_zerolag":[{"period":"M1","fast_EMA_period":12,"slow_EMA_period":26,"signal_EMA_period":9,"histogram_value":-0.01794,"signal_value":0.09465,"MACD_value":0.07671}]}\x00'
7POST /api/symbol/ - 400
8{'Content-Type': 'application/json', 'Vary': 'Accept', 'Allow': 'GET, POST, HEAD, OPTIONS'}
9b'{"detail":"JSON parse error - Extra data: line 1 column 982 (char 981)"}'
10 from django.db import models, transaction
11
12M1 = 'M1'
13M5 = 'M5'
14M15 = 'M15'
15M30 = 'M30'
16H1 = 'H1'
17H4 = 'H4'
18DAILY = 'DAILY'
19WEEKLY = 'WEEKLY'
20MONTHLY = 'MONTHLY'
21
22PERIOD_CHOICES = (
23 (M1, 'Une minute'),
24 (M5, 'Cinq minutes'),
25 (M15, 'Quinze minutes'),
26 (M30, 'Trente minutes'),
27 (H1, 'Une heure'),
28 (H4, 'Quatre heures'),
29 (DAILY, 'Journalier'),
30 (WEEKLY, 'Hebdomadaire'),
31 (MONTHLY, 'Mensuel'),
32)
33
34
35class BollingerBand(models.Model):
36
37 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
38 moving_average_period = models.CharField(max_length=8)
39 standard_deviation = models.DecimalField(max_digits=6, decimal_places=2)
40
41 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='bollinger_band', default=1)
42
43 high = models.DecimalField(max_digits=12, decimal_places=6)
44 low = models.DecimalField(max_digits=12, decimal_places=6)
45 moving_average = models.DecimalField(max_digits=12, decimal_places=6)
46
47
48
49class MovingAverage(models.Model):
50
51 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
52 moving_average_period = models.CharField(max_length=8)
53 type = models.TextField(max_length=30)
54
55 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='moving_average', default=1)
56
57 value = models.DecimalField(max_digits=12, decimal_places=6)
58
59
60
61
62class MACDZR(models.Model):
63
64 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
65 fast_EMA_period = models.CharField(max_length=4)
66 slow_EMA_period = models.CharField(max_length=4)
67 signal_EMA_period = models.CharField(max_length=4)
68
69 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='MACD_zerolag', default=1)
70
71 histogram_value = models.DecimalField(max_digits=12, decimal_places=6)
72 signal_value = models.DecimalField(max_digits=12, decimal_places=6)
73 MACD_value = models.DecimalField(max_digits=12, decimal_places=6)
74
75
76
77
78
79class Symbol(models.Model):
80
81
82 name = models.CharField(max_length=30, default='undefined')
83 date_created = models.DateTimeField(auto_now_add=True)
84 date_updated = models.DateTimeField(auto_now=True)
85
86 date_market = models.DateTimeField()
87
88 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
89
90 open_price = models.DecimalField(max_digits=12, decimal_places=6)
91 close_price = models.DecimalField(max_digits=12, decimal_places=6)
92 high_price = models.DecimalField(max_digits=12, decimal_places=6)
93 low_price = models.DecimalField(max_digits=12, decimal_places=6)
94
95 class Meta:
96 constraints = [
97 models.UniqueConstraint(
98 fields=['name', 'date_market', 'period'],
99 name='unique_symbol'
100 )
101 ]
102
103 def __str__(self):
104 return self.name
105
Serializers.py
1string data = "{ ... }“;
2char post_data[];
3post_data = StringToCharArray(data, post_data, WHOLE_ARRAY);
4int r = WebRequest("POST", "http://127.0.0.1/api/symbol/","Content-Type: application/json",5000, data,res_data, res_headers);
5{'Content-Length': '982', 'Content-Type': 'application/json', 'Accept': 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*', 'Host': '127.0.0.1', 'Accept-Language': 'fr,en', 'Accept-Charset': '*,utf-8', 'Connection': 'Keep-Alive', 'Proxy-Connection': 'Keep-Alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'User-Agent': 'MetaTrader 4 Terminal/4.1353 (Windows NT 6.1; x86)'}
6b'{"name": "GOLDs","date_market": "2022-02-01T00:00:00.000000Z","period": "M1","open_price": 1797.64,"close_price": 1870.91,"low_price": 1788.33,"high_price": 1879.12,"bollinger_band":[{"period":"M1","moving_average_period":20,"standard_deviation":1.5,"high":1936.06829,"low":1717.61271,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2,"high":1972.47755,"low":1681.20345,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2.5,"high":2008.88681,"low":1644.79419,"moving_average":1826.8405}],"moving_average":[{"period":"M1","moving_average_period":50,"type": "0","value":1569.6854},{"period":"M1","moving_average_period":100,"type": "0","value":1399.8002},{"period":"M1","moving_average_period":200,"type": "0","value":1245.38985}],"MACD_zerolag":[{"period":"M1","fast_EMA_period":12,"slow_EMA_period":26,"signal_EMA_period":9,"histogram_value":-0.01794,"signal_value":0.09465,"MACD_value":0.07671}]}\x00'
7POST /api/symbol/ - 400
8{'Content-Type': 'application/json', 'Vary': 'Accept', 'Allow': 'GET, POST, HEAD, OPTIONS'}
9b'{"detail":"JSON parse error - Extra data: line 1 column 982 (char 981)"}'
10 from django.db import models, transaction
11
12M1 = 'M1'
13M5 = 'M5'
14M15 = 'M15'
15M30 = 'M30'
16H1 = 'H1'
17H4 = 'H4'
18DAILY = 'DAILY'
19WEEKLY = 'WEEKLY'
20MONTHLY = 'MONTHLY'
21
22PERIOD_CHOICES = (
23 (M1, 'Une minute'),
24 (M5, 'Cinq minutes'),
25 (M15, 'Quinze minutes'),
26 (M30, 'Trente minutes'),
27 (H1, 'Une heure'),
28 (H4, 'Quatre heures'),
29 (DAILY, 'Journalier'),
30 (WEEKLY, 'Hebdomadaire'),
31 (MONTHLY, 'Mensuel'),
32)
33
34
35class BollingerBand(models.Model):
36
37 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
38 moving_average_period = models.CharField(max_length=8)
39 standard_deviation = models.DecimalField(max_digits=6, decimal_places=2)
40
41 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='bollinger_band', default=1)
42
43 high = models.DecimalField(max_digits=12, decimal_places=6)
44 low = models.DecimalField(max_digits=12, decimal_places=6)
45 moving_average = models.DecimalField(max_digits=12, decimal_places=6)
46
47
48
49class MovingAverage(models.Model):
50
51 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
52 moving_average_period = models.CharField(max_length=8)
53 type = models.TextField(max_length=30)
54
55 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='moving_average', default=1)
56
57 value = models.DecimalField(max_digits=12, decimal_places=6)
58
59
60
61
62class MACDZR(models.Model):
63
64 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
65 fast_EMA_period = models.CharField(max_length=4)
66 slow_EMA_period = models.CharField(max_length=4)
67 signal_EMA_period = models.CharField(max_length=4)
68
69 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='MACD_zerolag', default=1)
70
71 histogram_value = models.DecimalField(max_digits=12, decimal_places=6)
72 signal_value = models.DecimalField(max_digits=12, decimal_places=6)
73 MACD_value = models.DecimalField(max_digits=12, decimal_places=6)
74
75
76
77
78
79class Symbol(models.Model):
80
81
82 name = models.CharField(max_length=30, default='undefined')
83 date_created = models.DateTimeField(auto_now_add=True)
84 date_updated = models.DateTimeField(auto_now=True)
85
86 date_market = models.DateTimeField()
87
88 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
89
90 open_price = models.DecimalField(max_digits=12, decimal_places=6)
91 close_price = models.DecimalField(max_digits=12, decimal_places=6)
92 high_price = models.DecimalField(max_digits=12, decimal_places=6)
93 low_price = models.DecimalField(max_digits=12, decimal_places=6)
94
95 class Meta:
96 constraints = [
97 models.UniqueConstraint(
98 fields=['name', 'date_market', 'period'],
99 name='unique_symbol'
100 )
101 ]
102
103 def __str__(self):
104 return self.name
105from rest_framework import serializers
106
107from API.models import Symbol, BollingerBand, MACDZR, MovingAverage
108
109
110class BollingerBandSerializer(serializers.ModelSerializer):
111
112 class Meta:
113 model = BollingerBand
114 fields = ['period',
115 'moving_average_period',
116 'standard_deviation',
117 'symbol',
118 'high',
119 'low',
120 'moving_average']
121
122
123
124class MovingAverageSerializer(serializers.ModelSerializer):
125
126 class Meta:
127 model = MovingAverage
128 fields = ['period',
129 'moving_average_period',
130 'type',
131 'symbol',
132 'value']
133
134
135
136class MACDZRSerializer(serializers.ModelSerializer):
137
138 class Meta:
139 model = MACDZR
140 fields = ['period',
141 'fast_EMA_period',
142 'slow_EMA_period',
143 'signal_EMA_period',
144 'symbol',
145 'histogram_value',
146 'signal_value',
147 'MACD_value']
148
149
150
151class SymbolSerializer(serializers.ModelSerializer):
152
153 bollinger_band = BollingerBandSerializer(many=True)
154 moving_average = MovingAverageSerializer(many=True)
155 MACD_zerolag = MACDZRSerializer(many=True)
156
157 class Meta:
158 model = Symbol
159 fields = ['id',
160 'name',
161 'date_created',
162 'date_updated',
163 'date_market',
164 'period',
165 'open_price',
166 'close_price',
167 'high_price',
168 'low_price',
169 'bollinger_band',
170 'moving_average',
171 'MACD_zerolag'
172 ]
173
174
175 def create(self, validated_data):
176
177 bollinger_bands_data = validated_data.pop('bollinger_band')
178 moving_averages_data = validated_data.pop('moving_average')
179 MACDs_zerolag_data = validated_data.pop('MACD_zerolag')
180
181 symbol = Symbol.objects.create(**validated_data)
182
183 for bollinger_band_data in bollinger_bands_data:
184 BollingerBand.objects.create(symbol=symbol, **bollinger_band_data)
185
186 for MACD_zerolag_data in MACDs_zerolag_data:
187 MACDZR.objects.create(symbol=symbol, **MACD_zerolag_data)
188
189 for moving_average_data in moving_averages_data:
190 MovingAverage.objects.create(symbol=symbol, **moving_average_data)
191
192 return symbol
193
and settings.py
1string data = "{ ... }“;
2char post_data[];
3post_data = StringToCharArray(data, post_data, WHOLE_ARRAY);
4int r = WebRequest("POST", "http://127.0.0.1/api/symbol/","Content-Type: application/json",5000, data,res_data, res_headers);
5{'Content-Length': '982', 'Content-Type': 'application/json', 'Accept': 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*', 'Host': '127.0.0.1', 'Accept-Language': 'fr,en', 'Accept-Charset': '*,utf-8', 'Connection': 'Keep-Alive', 'Proxy-Connection': 'Keep-Alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'User-Agent': 'MetaTrader 4 Terminal/4.1353 (Windows NT 6.1; x86)'}
6b'{"name": "GOLDs","date_market": "2022-02-01T00:00:00.000000Z","period": "M1","open_price": 1797.64,"close_price": 1870.91,"low_price": 1788.33,"high_price": 1879.12,"bollinger_band":[{"period":"M1","moving_average_period":20,"standard_deviation":1.5,"high":1936.06829,"low":1717.61271,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2,"high":1972.47755,"low":1681.20345,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2.5,"high":2008.88681,"low":1644.79419,"moving_average":1826.8405}],"moving_average":[{"period":"M1","moving_average_period":50,"type": "0","value":1569.6854},{"period":"M1","moving_average_period":100,"type": "0","value":1399.8002},{"period":"M1","moving_average_period":200,"type": "0","value":1245.38985}],"MACD_zerolag":[{"period":"M1","fast_EMA_period":12,"slow_EMA_period":26,"signal_EMA_period":9,"histogram_value":-0.01794,"signal_value":0.09465,"MACD_value":0.07671}]}\x00'
7POST /api/symbol/ - 400
8{'Content-Type': 'application/json', 'Vary': 'Accept', 'Allow': 'GET, POST, HEAD, OPTIONS'}
9b'{"detail":"JSON parse error - Extra data: line 1 column 982 (char 981)"}'
10 from django.db import models, transaction
11
12M1 = 'M1'
13M5 = 'M5'
14M15 = 'M15'
15M30 = 'M30'
16H1 = 'H1'
17H4 = 'H4'
18DAILY = 'DAILY'
19WEEKLY = 'WEEKLY'
20MONTHLY = 'MONTHLY'
21
22PERIOD_CHOICES = (
23 (M1, 'Une minute'),
24 (M5, 'Cinq minutes'),
25 (M15, 'Quinze minutes'),
26 (M30, 'Trente minutes'),
27 (H1, 'Une heure'),
28 (H4, 'Quatre heures'),
29 (DAILY, 'Journalier'),
30 (WEEKLY, 'Hebdomadaire'),
31 (MONTHLY, 'Mensuel'),
32)
33
34
35class BollingerBand(models.Model):
36
37 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
38 moving_average_period = models.CharField(max_length=8)
39 standard_deviation = models.DecimalField(max_digits=6, decimal_places=2)
40
41 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='bollinger_band', default=1)
42
43 high = models.DecimalField(max_digits=12, decimal_places=6)
44 low = models.DecimalField(max_digits=12, decimal_places=6)
45 moving_average = models.DecimalField(max_digits=12, decimal_places=6)
46
47
48
49class MovingAverage(models.Model):
50
51 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
52 moving_average_period = models.CharField(max_length=8)
53 type = models.TextField(max_length=30)
54
55 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='moving_average', default=1)
56
57 value = models.DecimalField(max_digits=12, decimal_places=6)
58
59
60
61
62class MACDZR(models.Model):
63
64 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
65 fast_EMA_period = models.CharField(max_length=4)
66 slow_EMA_period = models.CharField(max_length=4)
67 signal_EMA_period = models.CharField(max_length=4)
68
69 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='MACD_zerolag', default=1)
70
71 histogram_value = models.DecimalField(max_digits=12, decimal_places=6)
72 signal_value = models.DecimalField(max_digits=12, decimal_places=6)
73 MACD_value = models.DecimalField(max_digits=12, decimal_places=6)
74
75
76
77
78
79class Symbol(models.Model):
80
81
82 name = models.CharField(max_length=30, default='undefined')
83 date_created = models.DateTimeField(auto_now_add=True)
84 date_updated = models.DateTimeField(auto_now=True)
85
86 date_market = models.DateTimeField()
87
88 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
89
90 open_price = models.DecimalField(max_digits=12, decimal_places=6)
91 close_price = models.DecimalField(max_digits=12, decimal_places=6)
92 high_price = models.DecimalField(max_digits=12, decimal_places=6)
93 low_price = models.DecimalField(max_digits=12, decimal_places=6)
94
95 class Meta:
96 constraints = [
97 models.UniqueConstraint(
98 fields=['name', 'date_market', 'period'],
99 name='unique_symbol'
100 )
101 ]
102
103 def __str__(self):
104 return self.name
105from rest_framework import serializers
106
107from API.models import Symbol, BollingerBand, MACDZR, MovingAverage
108
109
110class BollingerBandSerializer(serializers.ModelSerializer):
111
112 class Meta:
113 model = BollingerBand
114 fields = ['period',
115 'moving_average_period',
116 'standard_deviation',
117 'symbol',
118 'high',
119 'low',
120 'moving_average']
121
122
123
124class MovingAverageSerializer(serializers.ModelSerializer):
125
126 class Meta:
127 model = MovingAverage
128 fields = ['period',
129 'moving_average_period',
130 'type',
131 'symbol',
132 'value']
133
134
135
136class MACDZRSerializer(serializers.ModelSerializer):
137
138 class Meta:
139 model = MACDZR
140 fields = ['period',
141 'fast_EMA_period',
142 'slow_EMA_period',
143 'signal_EMA_period',
144 'symbol',
145 'histogram_value',
146 'signal_value',
147 'MACD_value']
148
149
150
151class SymbolSerializer(serializers.ModelSerializer):
152
153 bollinger_band = BollingerBandSerializer(many=True)
154 moving_average = MovingAverageSerializer(many=True)
155 MACD_zerolag = MACDZRSerializer(many=True)
156
157 class Meta:
158 model = Symbol
159 fields = ['id',
160 'name',
161 'date_created',
162 'date_updated',
163 'date_market',
164 'period',
165 'open_price',
166 'close_price',
167 'high_price',
168 'low_price',
169 'bollinger_band',
170 'moving_average',
171 'MACD_zerolag'
172 ]
173
174
175 def create(self, validated_data):
176
177 bollinger_bands_data = validated_data.pop('bollinger_band')
178 moving_averages_data = validated_data.pop('moving_average')
179 MACDs_zerolag_data = validated_data.pop('MACD_zerolag')
180
181 symbol = Symbol.objects.create(**validated_data)
182
183 for bollinger_band_data in bollinger_bands_data:
184 BollingerBand.objects.create(symbol=symbol, **bollinger_band_data)
185
186 for MACD_zerolag_data in MACDs_zerolag_data:
187 MACDZR.objects.create(symbol=symbol, **MACD_zerolag_data)
188
189 for moving_average_data in moving_averages_data:
190 MovingAverage.objects.create(symbol=symbol, **moving_average_data)
191
192 return symbol
193"""
194Django settings for trading_project project.
195
196Generated by 'django-admin startproject' using Django 4.0.2.
197
198For more information on this file, see
199https://docs.djangoproject.com/en/4.0/topics/settings/
200
201For the full list of settings and their values, see
202https://docs.djangoproject.com/en/4.0/ref/settings/
203"""
204
205from pathlib import Path
206import os
207# Build paths inside the project like this: BASE_DIR / 'subdir'.
208BASE_DIR = Path(__file__).resolve().parent.parent
209
210
211# Quick-start development settings - unsuitable for production
212# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
213
214# SECURITY WARNING: keep the secret key used in production secret!
215SECRET_KEY = 'django-insecure-)6f&ci7@)t96(k^7am%66@%e%(88a%u00+3h5a13s461#q7dqm'
216
217# SECURITY WARNING: don't run with debug turned on in production!
218DEBUG = True
219
220ALLOWED_HOSTS = [
221 '0.0.0.0',
222 '127.0.0.1',
223]
224
225
226# Application definition
227
228INSTALLED_APPS = [
229 'django.contrib.admin',
230 'django.contrib.auth',
231 'django.contrib.contenttypes',
232 'django.contrib.sessions',
233 'django.contrib.messages',
234 'django.contrib.staticfiles',
235 #'django.contrib.sites',
236 'rest_framework',
237 'authentication',
238 'API',
239]
240
241MIDDLEWARE = [
242 'django.middleware.security.SecurityMiddleware',
243 'django.contrib.sessions.middleware.SessionMiddleware',
244 'django.middleware.common.CommonMiddleware',
245 'django.middleware.csrf.CsrfViewMiddleware',
246 'django.contrib.auth.middleware.AuthenticationMiddleware',
247 'django.contrib.messages.middleware.MessageMiddleware',
248 'django.middleware.clickjacking.XFrameOptionsMiddleware',
249 'request_logging.middleware.LoggingMiddleware',
250]
251
252ROOT_URLCONF = 'trading_project.urls'
253
254TEMPLATES = [
255 {
256 'BACKEND': 'django.template.backends.django.DjangoTemplates',
257 'DIRS': [
258 os.path.join(BASE_DIR, 'templates/'),
259 ],
260 'APP_DIRS': True,
261 'OPTIONS': {
262 'context_processors': [
263 'django.template.context_processors.debug',
264 'django.template.context_processors.request',
265 'django.contrib.auth.context_processors.auth',
266 'django.contrib.messages.context_processors.messages',
267 ],
268 },
269 },
270]
271
272WSGI_APPLICATION = 'trading_project.wsgi.application'
273
274
275# Database
276# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
277
278DATABASES = {
279 'default': {
280 'ENGINE': 'django.db.backends.postgresql_psycopg2',
281 'NAME': 'trading_project',
282 'USER': 'admin',
283 'PASSWORD': 'testpassword',
284 'HOST': 'localhost',
285 'PORT': '5432',
286 }
287}
288
289
290# Password validation
291# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
292
293AUTH_PASSWORD_VALIDATORS = [
294 {
295 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
296 },
297 {
298 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
299 },
300 {
301 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
302 },
303 {
304 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
305 },
306]
307
308
309# Internationalization
310# https://docs.djangoproject.com/en/4.0/topics/i18n/
311
312LANGUAGE_CODE = 'fr-fr'
313
314TIME_ZONE = 'UTC'
315
316USE_I18N = True
317
318USE_TZ = True
319
320
321# Static files (CSS, JavaScript, Images)
322# https://docs.djangoproject.com/en/4.0/howto/static-files/
323
324STATIC_URL = 'static/'
325STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
326
327# Default primary key field type
328# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
329
330DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
331
332AUTH_USER_MODEL = 'authentication.User'
333LOGIN_URL = 'login'
334LOGIN_REDIRECT_URL = 'home'
335LOGOUT_URL = 'logout'
336LOGOUT_REDIRECT_URL = 'login'
337
338
339LOGGING = {
340 'version': 1,
341 'disable_existing_loggers': False,
342 'handlers': {
343 'console': {
344 'class': 'logging.StreamHandler',
345 },
346 },
347 'loggers': {
348 'django.request': {
349 'handlers': ['console'],
350 'level': 'DEBUG', # change debug level as appropiate
351 'propagate': False,
352 },
353 },
354}
355
if anyone have a simple solution for that Thanks
ANSWER
Answered 2022-Feb-17 at 08:16I find my solution, when I converted my data string to post_Data object the length was not WHOLE_ARRAY, but StringLen.
1string data = "{ ... }“;
2char post_data[];
3post_data = StringToCharArray(data, post_data, WHOLE_ARRAY);
4int r = WebRequest("POST", "http://127.0.0.1/api/symbol/","Content-Type: application/json",5000, data,res_data, res_headers);
5{'Content-Length': '982', 'Content-Type': 'application/json', 'Accept': 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*', 'Host': '127.0.0.1', 'Accept-Language': 'fr,en', 'Accept-Charset': '*,utf-8', 'Connection': 'Keep-Alive', 'Proxy-Connection': 'Keep-Alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'User-Agent': 'MetaTrader 4 Terminal/4.1353 (Windows NT 6.1; x86)'}
6b'{"name": "GOLDs","date_market": "2022-02-01T00:00:00.000000Z","period": "M1","open_price": 1797.64,"close_price": 1870.91,"low_price": 1788.33,"high_price": 1879.12,"bollinger_band":[{"period":"M1","moving_average_period":20,"standard_deviation":1.5,"high":1936.06829,"low":1717.61271,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2,"high":1972.47755,"low":1681.20345,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2.5,"high":2008.88681,"low":1644.79419,"moving_average":1826.8405}],"moving_average":[{"period":"M1","moving_average_period":50,"type": "0","value":1569.6854},{"period":"M1","moving_average_period":100,"type": "0","value":1399.8002},{"period":"M1","moving_average_period":200,"type": "0","value":1245.38985}],"MACD_zerolag":[{"period":"M1","fast_EMA_period":12,"slow_EMA_period":26,"signal_EMA_period":9,"histogram_value":-0.01794,"signal_value":0.09465,"MACD_value":0.07671}]}\x00'
7POST /api/symbol/ - 400
8{'Content-Type': 'application/json', 'Vary': 'Accept', 'Allow': 'GET, POST, HEAD, OPTIONS'}
9b'{"detail":"JSON parse error - Extra data: line 1 column 982 (char 981)"}'
10 from django.db import models, transaction
11
12M1 = 'M1'
13M5 = 'M5'
14M15 = 'M15'
15M30 = 'M30'
16H1 = 'H1'
17H4 = 'H4'
18DAILY = 'DAILY'
19WEEKLY = 'WEEKLY'
20MONTHLY = 'MONTHLY'
21
22PERIOD_CHOICES = (
23 (M1, 'Une minute'),
24 (M5, 'Cinq minutes'),
25 (M15, 'Quinze minutes'),
26 (M30, 'Trente minutes'),
27 (H1, 'Une heure'),
28 (H4, 'Quatre heures'),
29 (DAILY, 'Journalier'),
30 (WEEKLY, 'Hebdomadaire'),
31 (MONTHLY, 'Mensuel'),
32)
33
34
35class BollingerBand(models.Model):
36
37 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
38 moving_average_period = models.CharField(max_length=8)
39 standard_deviation = models.DecimalField(max_digits=6, decimal_places=2)
40
41 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='bollinger_band', default=1)
42
43 high = models.DecimalField(max_digits=12, decimal_places=6)
44 low = models.DecimalField(max_digits=12, decimal_places=6)
45 moving_average = models.DecimalField(max_digits=12, decimal_places=6)
46
47
48
49class MovingAverage(models.Model):
50
51 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
52 moving_average_period = models.CharField(max_length=8)
53 type = models.TextField(max_length=30)
54
55 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='moving_average', default=1)
56
57 value = models.DecimalField(max_digits=12, decimal_places=6)
58
59
60
61
62class MACDZR(models.Model):
63
64 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
65 fast_EMA_period = models.CharField(max_length=4)
66 slow_EMA_period = models.CharField(max_length=4)
67 signal_EMA_period = models.CharField(max_length=4)
68
69 symbol = models.ForeignKey('API.Symbol', on_delete=models.CASCADE, related_name='MACD_zerolag', default=1)
70
71 histogram_value = models.DecimalField(max_digits=12, decimal_places=6)
72 signal_value = models.DecimalField(max_digits=12, decimal_places=6)
73 MACD_value = models.DecimalField(max_digits=12, decimal_places=6)
74
75
76
77
78
79class Symbol(models.Model):
80
81
82 name = models.CharField(max_length=30, default='undefined')
83 date_created = models.DateTimeField(auto_now_add=True)
84 date_updated = models.DateTimeField(auto_now=True)
85
86 date_market = models.DateTimeField()
87
88 period = models.CharField(max_length=30, choices=PERIOD_CHOICES, verbose_name='Période')
89
90 open_price = models.DecimalField(max_digits=12, decimal_places=6)
91 close_price = models.DecimalField(max_digits=12, decimal_places=6)
92 high_price = models.DecimalField(max_digits=12, decimal_places=6)
93 low_price = models.DecimalField(max_digits=12, decimal_places=6)
94
95 class Meta:
96 constraints = [
97 models.UniqueConstraint(
98 fields=['name', 'date_market', 'period'],
99 name='unique_symbol'
100 )
101 ]
102
103 def __str__(self):
104 return self.name
105from rest_framework import serializers
106
107from API.models import Symbol, BollingerBand, MACDZR, MovingAverage
108
109
110class BollingerBandSerializer(serializers.ModelSerializer):
111
112 class Meta:
113 model = BollingerBand
114 fields = ['period',
115 'moving_average_period',
116 'standard_deviation',
117 'symbol',
118 'high',
119 'low',
120 'moving_average']
121
122
123
124class MovingAverageSerializer(serializers.ModelSerializer):
125
126 class Meta:
127 model = MovingAverage
128 fields = ['period',
129 'moving_average_period',
130 'type',
131 'symbol',
132 'value']
133
134
135
136class MACDZRSerializer(serializers.ModelSerializer):
137
138 class Meta:
139 model = MACDZR
140 fields = ['period',
141 'fast_EMA_period',
142 'slow_EMA_period',
143 'signal_EMA_period',
144 'symbol',
145 'histogram_value',
146 'signal_value',
147 'MACD_value']
148
149
150
151class SymbolSerializer(serializers.ModelSerializer):
152
153 bollinger_band = BollingerBandSerializer(many=True)
154 moving_average = MovingAverageSerializer(many=True)
155 MACD_zerolag = MACDZRSerializer(many=True)
156
157 class Meta:
158 model = Symbol
159 fields = ['id',
160 'name',
161 'date_created',
162 'date_updated',
163 'date_market',
164 'period',
165 'open_price',
166 'close_price',
167 'high_price',
168 'low_price',
169 'bollinger_band',
170 'moving_average',
171 'MACD_zerolag'
172 ]
173
174
175 def create(self, validated_data):
176
177 bollinger_bands_data = validated_data.pop('bollinger_band')
178 moving_averages_data = validated_data.pop('moving_average')
179 MACDs_zerolag_data = validated_data.pop('MACD_zerolag')
180
181 symbol = Symbol.objects.create(**validated_data)
182
183 for bollinger_band_data in bollinger_bands_data:
184 BollingerBand.objects.create(symbol=symbol, **bollinger_band_data)
185
186 for MACD_zerolag_data in MACDs_zerolag_data:
187 MACDZR.objects.create(symbol=symbol, **MACD_zerolag_data)
188
189 for moving_average_data in moving_averages_data:
190 MovingAverage.objects.create(symbol=symbol, **moving_average_data)
191
192 return symbol
193"""
194Django settings for trading_project project.
195
196Generated by 'django-admin startproject' using Django 4.0.2.
197
198For more information on this file, see
199https://docs.djangoproject.com/en/4.0/topics/settings/
200
201For the full list of settings and their values, see
202https://docs.djangoproject.com/en/4.0/ref/settings/
203"""
204
205from pathlib import Path
206import os
207# Build paths inside the project like this: BASE_DIR / 'subdir'.
208BASE_DIR = Path(__file__).resolve().parent.parent
209
210
211# Quick-start development settings - unsuitable for production
212# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
213
214# SECURITY WARNING: keep the secret key used in production secret!
215SECRET_KEY = 'django-insecure-)6f&ci7@)t96(k^7am%66@%e%(88a%u00+3h5a13s461#q7dqm'
216
217# SECURITY WARNING: don't run with debug turned on in production!
218DEBUG = True
219
220ALLOWED_HOSTS = [
221 '0.0.0.0',
222 '127.0.0.1',
223]
224
225
226# Application definition
227
228INSTALLED_APPS = [
229 'django.contrib.admin',
230 'django.contrib.auth',
231 'django.contrib.contenttypes',
232 'django.contrib.sessions',
233 'django.contrib.messages',
234 'django.contrib.staticfiles',
235 #'django.contrib.sites',
236 'rest_framework',
237 'authentication',
238 'API',
239]
240
241MIDDLEWARE = [
242 'django.middleware.security.SecurityMiddleware',
243 'django.contrib.sessions.middleware.SessionMiddleware',
244 'django.middleware.common.CommonMiddleware',
245 'django.middleware.csrf.CsrfViewMiddleware',
246 'django.contrib.auth.middleware.AuthenticationMiddleware',
247 'django.contrib.messages.middleware.MessageMiddleware',
248 'django.middleware.clickjacking.XFrameOptionsMiddleware',
249 'request_logging.middleware.LoggingMiddleware',
250]
251
252ROOT_URLCONF = 'trading_project.urls'
253
254TEMPLATES = [
255 {
256 'BACKEND': 'django.template.backends.django.DjangoTemplates',
257 'DIRS': [
258 os.path.join(BASE_DIR, 'templates/'),
259 ],
260 'APP_DIRS': True,
261 'OPTIONS': {
262 'context_processors': [
263 'django.template.context_processors.debug',
264 'django.template.context_processors.request',
265 'django.contrib.auth.context_processors.auth',
266 'django.contrib.messages.context_processors.messages',
267 ],
268 },
269 },
270]
271
272WSGI_APPLICATION = 'trading_project.wsgi.application'
273
274
275# Database
276# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
277
278DATABASES = {
279 'default': {
280 'ENGINE': 'django.db.backends.postgresql_psycopg2',
281 'NAME': 'trading_project',
282 'USER': 'admin',
283 'PASSWORD': 'testpassword',
284 'HOST': 'localhost',
285 'PORT': '5432',
286 }
287}
288
289
290# Password validation
291# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
292
293AUTH_PASSWORD_VALIDATORS = [
294 {
295 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
296 },
297 {
298 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
299 },
300 {
301 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
302 },
303 {
304 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
305 },
306]
307
308
309# Internationalization
310# https://docs.djangoproject.com/en/4.0/topics/i18n/
311
312LANGUAGE_CODE = 'fr-fr'
313
314TIME_ZONE = 'UTC'
315
316USE_I18N = True
317
318USE_TZ = True
319
320
321# Static files (CSS, JavaScript, Images)
322# https://docs.djangoproject.com/en/4.0/howto/static-files/
323
324STATIC_URL = 'static/'
325STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
326
327# Default primary key field type
328# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
329
330DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
331
332AUTH_USER_MODEL = 'authentication.User'
333LOGIN_URL = 'login'
334LOGIN_REDIRECT_URL = 'home'
335LOGOUT_URL = 'logout'
336LOGOUT_REDIRECT_URL = 'login'
337
338
339LOGGING = {
340 'version': 1,
341 'disable_existing_loggers': False,
342 'handlers': {
343 'console': {
344 'class': 'logging.StreamHandler',
345 },
346 },
347 'loggers': {
348 'django.request': {
349 'handlers': ['console'],
350 'level': 'DEBUG', # change debug level as appropiate
351 'propagate': False,
352 },
353 },
354}
355StringToCharArray(data, post_data,0, StringLen(data));
356
QUESTION
Why my translations in django i18n don't work
Asked 2022-Feb-16 at 01:15I've been following 3 different tutorials for text translation in django, and with none of them my translation has worked, however I was doing exactly the same steps as in the tutorials. Django just doesn't translate my text, it goes without any kind of error. My last try was with this course: https://www.youtube.com/watch?v=AlJ8cGbk8ps. But just to be sure I'm adding my code below
settings.py
1# Internationalization
2# https://docs.djangoproject.com/en/4.0/topics/i18n/
3
4LANGUAGE_CODE = 'es'
5
6TIME_ZONE = 'UTC'
7
8USE_I18N = True
9
10USE_TZ = True
11
views.py
1# Internationalization
2# https://docs.djangoproject.com/en/4.0/topics/i18n/
3
4LANGUAGE_CODE = 'es'
5
6TIME_ZONE = 'UTC'
7
8USE_I18N = True
9
10USE_TZ = True
11from django.utils.translation import gettext as _
12
13# Create your views here.
14def index(request):
15 context = {
16 'hello':_('Hello'),
17 }
18
19 return render(request, 'index.html', context)
20
index.html
1# Internationalization
2# https://docs.djangoproject.com/en/4.0/topics/i18n/
3
4LANGUAGE_CODE = 'es'
5
6TIME_ZONE = 'UTC'
7
8USE_I18N = True
9
10USE_TZ = True
11from django.utils.translation import gettext as _
12
13# Create your views here.
14def index(request):
15 context = {
16 'hello':_('Hello'),
17 }
18
19 return render(request, 'index.html', context)
20{% load i18n %}
21
22<html lang="en">
23<head>
24 <meta charset="UTF-8">
25 <meta http-equiv="X-UA-Compatible" content="IE=edge">
26 <meta name="viewport" content="width=device-width, initial-scale=1.0">
27 <title>Document</title>
28</head>
29<body>
30
31 <h1>{{ hello }}</h1>
32 <h2>{% trans "My name is Dawid" %}</h2>
33
34</body>
35</html>
36
My locale folder looks like this:
I think I should also mention that I use virtual environment, but when I switched it off it doesn't work either. Whether I switch LANGUAGE_CODE to es or pl it takes no effect. I've compiled them too.
ANSWER
Answered 2022-Feb-16 at 01:15Try add this in your settings.py:
1# Internationalization
2# https://docs.djangoproject.com/en/4.0/topics/i18n/
3
4LANGUAGE_CODE = 'es'
5
6TIME_ZONE = 'UTC'
7
8USE_I18N = True
9
10USE_TZ = True
11from django.utils.translation import gettext as _
12
13# Create your views here.
14def index(request):
15 context = {
16 'hello':_('Hello'),
17 }
18
19 return render(request, 'index.html', context)
20{% load i18n %}
21
22<html lang="en">
23<head>
24 <meta charset="UTF-8">
25 <meta http-equiv="X-UA-Compatible" content="IE=edge">
26 <meta name="viewport" content="width=device-width, initial-scale=1.0">
27 <title>Document</title>
28</head>
29<body>
30
31 <h1>{{ hello }}</h1>
32 <h2>{% trans "My name is Dawid" %}</h2>
33
34</body>
35</html>
36LOCALE_PATHS = (
37 os.path.join(BASE_DIR, 'locale')
38)
39
Will fix it!
QUESTION
How to insert a <a> tag or icon inside Vuetify internationalization?
Asked 2022-Feb-14 at 19:20I'm currently working on a project based on Vuetify
. I need to insert a <a>
tag and icon inside an internationalization text. Generally, it is easy to insert a variable as below shows,
this.$vuetify.lang.$t('I'm {0}', varirable_name)
but in this way, I cannot insert <a>
tag or an icon <v-icon>
, how could I achieve it?
Just like this,
1`this.$vuetify.lang.$t('Here is an icon {0} and a {1}', <v-icon />, <a>link</a>)`
2
ANSWER
Answered 2022-Feb-14 at 19:20You can use v-html
directive to output raw HTML. It will work for basic tags but won't work for Vuetify's v-tags (for example, v-icon
).
1`this.$vuetify.lang.$t('Here is an icon {0} and a {1}', <v-icon />, <a>link</a>)`
2new Vue({
3 vuetify: new Vuetify(),
4 data() {
5 return {
6 message: this.$vuetify.lang.t('Here is an bold {0} and a {1}', "<strong>text</strong>", "<a>link</a>")
7 }
8 }
9
10}).$mount('#app')
1`this.$vuetify.lang.$t('Here is an icon {0} and a {1}', <v-icon />, <a>link</a>)`
2new Vue({
3 vuetify: new Vuetify(),
4 data() {
5 return {
6 message: this.$vuetify.lang.t('Here is an bold {0} and a {1}', "<strong>text</strong>", "<a>link</a>")
7 }
8 }
9
10}).$mount('#app')<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
11<link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.x/css/materialdesignicons.min.css" rel="stylesheet">
12<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
13
14
15<div id="app">
16 <v-app>
17 <v-main>
18 <v-container><span v-html="message"></span ></v-container>
19 </v-main>
20 </v-app>
21 </div>
22
23 <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
24 <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
I wouldn't recommend using Vuetify tags in composite format strings. Instead, translate the text inside of the tag.
1`this.$vuetify.lang.$t('Here is an icon {0} and a {1}', <v-icon />, <a>link</a>)`
2new Vue({
3 vuetify: new Vuetify(),
4 data() {
5 return {
6 message: this.$vuetify.lang.t('Here is an bold {0} and a {1}', "<strong>text</strong>", "<a>link</a>")
7 }
8 }
9
10}).$mount('#app')<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
11<link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.x/css/materialdesignicons.min.css" rel="stylesheet">
12<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
13
14
15<div id="app">
16 <v-app>
17 <v-main>
18 <v-container><span v-html="message"></span ></v-container>
19 </v-main>
20 </v-app>
21 </div>
22
23 <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
24 <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script><v-btn class="ma-2" color="primary" dark>
25 Accept // <- translate only this
26 <v-icon dark right>
27 mdi-checkbox-marked-circle
28 </v-icon>
29</v-btn>
30
QUESTION
Show Two Languages at once
Asked 2022-Feb-07 at 10:23Fisrt of all i am following this guide for localization which is the official guideline of flutter but at
1AppLocalizations.of(context)!.helloWorld
2
It gives error as null
I think this is maybe because I recently updated flutter to 2.10
please confirm if that is the case
I want to achieve this kind of results like English on right and Urdu Language of Left which i don't know how to do that because in samples and guides they just show how to change overall app language not just for some strings
Also for time being, I have used easy_localization: 3.0.0
but still the problem is how i support multiple language at once with this package
ANSWER
Answered 2022-Feb-07 at 10:23- Don't use localization for this part - drawer widget - text items
- wrap drawer widget with Directionality widget to prevent it from mirroring and make text in the same place.
- pop the drawer after using switch widget.
Example:
1AppLocalizations.of(context)!.helloWorld
2import 'package:flutter/material.dart' as ltr;
3
4
5drawer: Directionality(
6 textDirection: ltr.TextDirection.ltr,
7 child: Container(
8 color: Colors.lightGreen,
9 child: Column(
10 children: [
11 Row(
12 mainAxisAlignment: MainAxisAlignment.spaceBetween,
13 children: [
14 Text('English'),
15 Text('عربي'),
16 ],
17 ),
18 Row(
19 mainAxisAlignment: MainAxisAlignment.spaceBetween,
20 children: [
21 Text('English'),
22 Text('عربي'),
23 ],
24 ),
25 ],
26 ),
27 ),
28 ),
29
QUESTION
ERRORS: inside.UserProfile.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
Asked 2022-Jan-28 at 18:37I am a beginner in Django. I am trying to build an app with user authentication. However I want extra fields like country and phone number, and I don't want any username field (I want the phone number to act as the username), so I built a custom user class. There are questions that have already been asked that have the same error, but they are not exactly relevant to my use case and the solutions don't work for me.
models.py:
1from django.db import models
2from django.contrib.auth.models import User
3from django.contrib.auth.models import AbstractBaseUser
4from django.conf import settings
5
6from django_countries.fields import CountryField
7
8# Create your models here.
9
10class UserProfile(AbstractBaseUser):
11
12 user = models.OneToOneField(User, on_delete = models.DO_NOTHING)
13
14 phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False)
15 country = CountryField()
16 uid = models.UUIDField(
17 default = None,
18 blank = True,
19 null = True,
20 unique = True,
21 )
22 USERNAME_FIELD = "uid"
23 REQUIRED_FIELDS = ['phone_number', 'country']
24
forms.py:
1from django.db import models
2from django.contrib.auth.models import User
3from django.contrib.auth.models import AbstractBaseUser
4from django.conf import settings
5
6from django_countries.fields import CountryField
7
8# Create your models here.
9
10class UserProfile(AbstractBaseUser):
11
12 user = models.OneToOneField(User, on_delete = models.DO_NOTHING)
13
14 phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False)
15 country = CountryField()
16 uid = models.UUIDField(
17 default = None,
18 blank = True,
19 null = True,
20 unique = True,
21 )
22 USERNAME_FIELD = "uid"
23 REQUIRED_FIELDS = ['phone_number', 'country']
24from django import forms
25from django.contrib.auth.forms import UserCreationForm
26from django.contrib.auth.models import User
27from .models import UserProfile
28
29from django_countries.fields import CountryField
30
31
32# Create your forms here..
33
34class NewUserForm(UserCreationForm):
35 phone_number = forms.RegexField(max_length = 16, regex = r'^\+?1?\d{9,15}$')
36 country = CountryField()
37
38 class Meta:
39 model = UserProfile
40 fields = ("phone_number", "country", "password1", "password2")
41
42 def save(self, commit = True):
43 user = super(NewUserForm, self).save(commit = False)
44 user.phone_number = self.cleaned_data['phone_number']
45 user.username = user.phone_number
46 user.country = self.cleaned_data['country']
47 if commit:
48 user.save()
49 return user
50
settings.py:
1from django.db import models
2from django.contrib.auth.models import User
3from django.contrib.auth.models import AbstractBaseUser
4from django.conf import settings
5
6from django_countries.fields import CountryField
7
8# Create your models here.
9
10class UserProfile(AbstractBaseUser):
11
12 user = models.OneToOneField(User, on_delete = models.DO_NOTHING)
13
14 phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False)
15 country = CountryField()
16 uid = models.UUIDField(
17 default = None,
18 blank = True,
19 null = True,
20 unique = True,
21 )
22 USERNAME_FIELD = "uid"
23 REQUIRED_FIELDS = ['phone_number', 'country']
24from django import forms
25from django.contrib.auth.forms import UserCreationForm
26from django.contrib.auth.models import User
27from .models import UserProfile
28
29from django_countries.fields import CountryField
30
31
32# Create your forms here..
33
34class NewUserForm(UserCreationForm):
35 phone_number = forms.RegexField(max_length = 16, regex = r'^\+?1?\d{9,15}$')
36 country = CountryField()
37
38 class Meta:
39 model = UserProfile
40 fields = ("phone_number", "country", "password1", "password2")
41
42 def save(self, commit = True):
43 user = super(NewUserForm, self).save(commit = False)
44 user.phone_number = self.cleaned_data['phone_number']
45 user.username = user.phone_number
46 user.country = self.cleaned_data['country']
47 if commit:
48 user.save()
49 return user
50"""
51Django settings for app project.
52
53Generated by 'django-admin startproject' using Django 4.0.1.
54
55For more information on this file, see
56https://docs.djangoproject.com/en/4.0/topics/settings/
57
58For the full list of settings and their values, see
59https://docs.djangoproject.com/en/4.0/ref/settings/
60"""
61
62from pathlib import Path
63
64# Build paths inside the project like this: BASE_DIR / 'subdir'.
65BASE_DIR = Path(__file__).resolve().parent.parent
66
67
68# Quick-start development settings - unsuitable for production
69# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
70
71# SECURITY WARNING: keep the secret key used in production secret!
72SECRET_KEY = 'django-insecure-pu46*rr%pr(^utidu^bob6o#f*s4w5ig#$fmc$f@ga45+p2wzc'
73
74# SECURITY WARNING: don't run with debug turned on in production!
75DEBUG = True
76
77ALLOWED_HOSTS = []
78
79
80# Application definition
81
82INSTALLED_APPS = [
83 'inside.apps.InsideConfig',
84 'django.contrib.admin',
85 'django.contrib.auth',
86 'django.contrib.contenttypes',
87 'django.contrib.sessions',
88 'django.contrib.messages',
89 'django.contrib.staticfiles',
90 'crispy_forms',
91 'phonenumber_field',
92]
93
94AUTH_USER_MODEL = 'inside.UserProfile'
95
96CRISPY_TEMPLATE_PACK = 'bootstrap4'
97
98MIDDLEWARE = [
99 'django.middleware.security.SecurityMiddleware',
100 'django.contrib.sessions.middleware.SessionMiddleware',
101 'django.middleware.common.CommonMiddleware',
102 'django.middleware.csrf.CsrfViewMiddleware',
103 'django.contrib.auth.middleware.AuthenticationMiddleware',
104 'django.contrib.messages.middleware.MessageMiddleware',
105 'django.middleware.clickjacking.XFrameOptionsMiddleware',
106]
107
108ROOT_URLCONF = 'app.urls'
109
110TEMPLATES = [
111 {
112 'BACKEND': 'django.template.backends.django.DjangoTemplates',
113 'DIRS': [],
114 'APP_DIRS': True,
115 'OPTIONS': {
116 'context_processors': [
117 'django.template.context_processors.debug',
118 'django.template.context_processors.request',
119 'django.contrib.auth.context_processors.auth',
120 'django.contrib.messages.context_processors.messages',
121 ],
122 },
123 },
124]
125
126WSGI_APPLICATION = 'app.wsgi.application'
127
128
129# Database
130# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
131
132DATABASES = {
133 'default': {
134 'ENGINE': 'django.db.backends.sqlite3',
135 'NAME': BASE_DIR / 'db.sqlite3',
136 }
137}
138
139
140# Password validation
141# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
142
143AUTH_PASSWORD_VALIDATORS = [
144 {
145 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
146 },
147 {
148 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
149 },
150 {
151 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
152 },
153 {
154 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
155 },
156]
157
158
159# Internationalization
160# https://docs.djangoproject.com/en/4.0/topics/i18n/
161
162LANGUAGE_CODE = 'en-us'
163
164TIME_ZONE = 'Asia/Kolkata'
165
166USE_I18N = True
167
168USE_TZ = True
169
170
171# Static files (CSS, JavaScript, Images)
172# https://docs.djangoproject.com/en/4.0/howto/static-files/
173
174STATIC_URL = 'static/'
175
176# Default primary key field type
177# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
178
179DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
180
181
Django throws this error:
1from django.db import models
2from django.contrib.auth.models import User
3from django.contrib.auth.models import AbstractBaseUser
4from django.conf import settings
5
6from django_countries.fields import CountryField
7
8# Create your models here.
9
10class UserProfile(AbstractBaseUser):
11
12 user = models.OneToOneField(User, on_delete = models.DO_NOTHING)
13
14 phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False)
15 country = CountryField()
16 uid = models.UUIDField(
17 default = None,
18 blank = True,
19 null = True,
20 unique = True,
21 )
22 USERNAME_FIELD = "uid"
23 REQUIRED_FIELDS = ['phone_number', 'country']
24from django import forms
25from django.contrib.auth.forms import UserCreationForm
26from django.contrib.auth.models import User
27from .models import UserProfile
28
29from django_countries.fields import CountryField
30
31
32# Create your forms here..
33
34class NewUserForm(UserCreationForm):
35 phone_number = forms.RegexField(max_length = 16, regex = r'^\+?1?\d{9,15}$')
36 country = CountryField()
37
38 class Meta:
39 model = UserProfile
40 fields = ("phone_number", "country", "password1", "password2")
41
42 def save(self, commit = True):
43 user = super(NewUserForm, self).save(commit = False)
44 user.phone_number = self.cleaned_data['phone_number']
45 user.username = user.phone_number
46 user.country = self.cleaned_data['country']
47 if commit:
48 user.save()
49 return user
50"""
51Django settings for app project.
52
53Generated by 'django-admin startproject' using Django 4.0.1.
54
55For more information on this file, see
56https://docs.djangoproject.com/en/4.0/topics/settings/
57
58For the full list of settings and their values, see
59https://docs.djangoproject.com/en/4.0/ref/settings/
60"""
61
62from pathlib import Path
63
64# Build paths inside the project like this: BASE_DIR / 'subdir'.
65BASE_DIR = Path(__file__).resolve().parent.parent
66
67
68# Quick-start development settings - unsuitable for production
69# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
70
71# SECURITY WARNING: keep the secret key used in production secret!
72SECRET_KEY = 'django-insecure-pu46*rr%pr(^utidu^bob6o#f*s4w5ig#$fmc$f@ga45+p2wzc'
73
74# SECURITY WARNING: don't run with debug turned on in production!
75DEBUG = True
76
77ALLOWED_HOSTS = []
78
79
80# Application definition
81
82INSTALLED_APPS = [
83 'inside.apps.InsideConfig',
84 'django.contrib.admin',
85 'django.contrib.auth',
86 'django.contrib.contenttypes',
87 'django.contrib.sessions',
88 'django.contrib.messages',
89 'django.contrib.staticfiles',
90 'crispy_forms',
91 'phonenumber_field',
92]
93
94AUTH_USER_MODEL = 'inside.UserProfile'
95
96CRISPY_TEMPLATE_PACK = 'bootstrap4'
97
98MIDDLEWARE = [
99 'django.middleware.security.SecurityMiddleware',
100 'django.contrib.sessions.middleware.SessionMiddleware',
101 'django.middleware.common.CommonMiddleware',
102 'django.middleware.csrf.CsrfViewMiddleware',
103 'django.contrib.auth.middleware.AuthenticationMiddleware',
104 'django.contrib.messages.middleware.MessageMiddleware',
105 'django.middleware.clickjacking.XFrameOptionsMiddleware',
106]
107
108ROOT_URLCONF = 'app.urls'
109
110TEMPLATES = [
111 {
112 'BACKEND': 'django.template.backends.django.DjangoTemplates',
113 'DIRS': [],
114 'APP_DIRS': True,
115 'OPTIONS': {
116 'context_processors': [
117 'django.template.context_processors.debug',
118 'django.template.context_processors.request',
119 'django.contrib.auth.context_processors.auth',
120 'django.contrib.messages.context_processors.messages',
121 ],
122 },
123 },
124]
125
126WSGI_APPLICATION = 'app.wsgi.application'
127
128
129# Database
130# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
131
132DATABASES = {
133 'default': {
134 'ENGINE': 'django.db.backends.sqlite3',
135 'NAME': BASE_DIR / 'db.sqlite3',
136 }
137}
138
139
140# Password validation
141# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
142
143AUTH_PASSWORD_VALIDATORS = [
144 {
145 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
146 },
147 {
148 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
149 },
150 {
151 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
152 },
153 {
154 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
155 },
156]
157
158
159# Internationalization
160# https://docs.djangoproject.com/en/4.0/topics/i18n/
161
162LANGUAGE_CODE = 'en-us'
163
164TIME_ZONE = 'Asia/Kolkata'
165
166USE_I18N = True
167
168USE_TZ = True
169
170
171# Static files (CSS, JavaScript, Images)
172# https://docs.djangoproject.com/en/4.0/howto/static-files/
173
174STATIC_URL = 'static/'
175
176# Default primary key field type
177# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
178
179DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
180
181Watching for file changes with StatReloader
182Performing system checks...
183
184Exception in thread django-main-thread:
185Traceback (most recent call last):
186 File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
187 self.run()
188 File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
189 self._target(*self._args, **self._kwargs)
190 File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
191 fn(*args, **kwargs)
192 File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run
193 self.check(display_num_errors=True)
194 File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 488, in check
195 raise SystemCheckError(msg)
196django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
197
198ERRORS:
199inside.UserProfile.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
200 HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
201
202System check identified 1 issue (0 silenced).
203
ANSWER
Answered 2022-Jan-28 at 18:37You are defining a relationship to the default User
Model, which you are not using anymore as you have created a custom user model. Remove the one_to_one_field
to avoid this error
And to further errors you have to create a custom manager
1from django.db import models
2from django.contrib.auth.models import User
3from django.contrib.auth.models import AbstractBaseUser
4from django.conf import settings
5
6from django_countries.fields import CountryField
7
8# Create your models here.
9
10class UserProfile(AbstractBaseUser):
11
12 user = models.OneToOneField(User, on_delete = models.DO_NOTHING)
13
14 phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False)
15 country = CountryField()
16 uid = models.UUIDField(
17 default = None,
18 blank = True,
19 null = True,
20 unique = True,
21 )
22 USERNAME_FIELD = "uid"
23 REQUIRED_FIELDS = ['phone_number', 'country']
24from django import forms
25from django.contrib.auth.forms import UserCreationForm
26from django.contrib.auth.models import User
27from .models import UserProfile
28
29from django_countries.fields import CountryField
30
31
32# Create your forms here..
33
34class NewUserForm(UserCreationForm):
35 phone_number = forms.RegexField(max_length = 16, regex = r'^\+?1?\d{9,15}$')
36 country = CountryField()
37
38 class Meta:
39 model = UserProfile
40 fields = ("phone_number", "country", "password1", "password2")
41
42 def save(self, commit = True):
43 user = super(NewUserForm, self).save(commit = False)
44 user.phone_number = self.cleaned_data['phone_number']
45 user.username = user.phone_number
46 user.country = self.cleaned_data['country']
47 if commit:
48 user.save()
49 return user
50"""
51Django settings for app project.
52
53Generated by 'django-admin startproject' using Django 4.0.1.
54
55For more information on this file, see
56https://docs.djangoproject.com/en/4.0/topics/settings/
57
58For the full list of settings and their values, see
59https://docs.djangoproject.com/en/4.0/ref/settings/
60"""
61
62from pathlib import Path
63
64# Build paths inside the project like this: BASE_DIR / 'subdir'.
65BASE_DIR = Path(__file__).resolve().parent.parent
66
67
68# Quick-start development settings - unsuitable for production
69# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
70
71# SECURITY WARNING: keep the secret key used in production secret!
72SECRET_KEY = 'django-insecure-pu46*rr%pr(^utidu^bob6o#f*s4w5ig#$fmc$f@ga45+p2wzc'
73
74# SECURITY WARNING: don't run with debug turned on in production!
75DEBUG = True
76
77ALLOWED_HOSTS = []
78
79
80# Application definition
81
82INSTALLED_APPS = [
83 'inside.apps.InsideConfig',
84 'django.contrib.admin',
85 'django.contrib.auth',
86 'django.contrib.contenttypes',
87 'django.contrib.sessions',
88 'django.contrib.messages',
89 'django.contrib.staticfiles',
90 'crispy_forms',
91 'phonenumber_field',
92]
93
94AUTH_USER_MODEL = 'inside.UserProfile'
95
96CRISPY_TEMPLATE_PACK = 'bootstrap4'
97
98MIDDLEWARE = [
99 'django.middleware.security.SecurityMiddleware',
100 'django.contrib.sessions.middleware.SessionMiddleware',
101 'django.middleware.common.CommonMiddleware',
102 'django.middleware.csrf.CsrfViewMiddleware',
103 'django.contrib.auth.middleware.AuthenticationMiddleware',
104 'django.contrib.messages.middleware.MessageMiddleware',
105 'django.middleware.clickjacking.XFrameOptionsMiddleware',
106]
107
108ROOT_URLCONF = 'app.urls'
109
110TEMPLATES = [
111 {
112 'BACKEND': 'django.template.backends.django.DjangoTemplates',
113 'DIRS': [],
114 'APP_DIRS': True,
115 'OPTIONS': {
116 'context_processors': [
117 'django.template.context_processors.debug',
118 'django.template.context_processors.request',
119 'django.contrib.auth.context_processors.auth',
120 'django.contrib.messages.context_processors.messages',
121 ],
122 },
123 },
124]
125
126WSGI_APPLICATION = 'app.wsgi.application'
127
128
129# Database
130# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
131
132DATABASES = {
133 'default': {
134 'ENGINE': 'django.db.backends.sqlite3',
135 'NAME': BASE_DIR / 'db.sqlite3',
136 }
137}
138
139
140# Password validation
141# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
142
143AUTH_PASSWORD_VALIDATORS = [
144 {
145 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
146 },
147 {
148 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
149 },
150 {
151 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
152 },
153 {
154 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
155 },
156]
157
158
159# Internationalization
160# https://docs.djangoproject.com/en/4.0/topics/i18n/
161
162LANGUAGE_CODE = 'en-us'
163
164TIME_ZONE = 'Asia/Kolkata'
165
166USE_I18N = True
167
168USE_TZ = True
169
170
171# Static files (CSS, JavaScript, Images)
172# https://docs.djangoproject.com/en/4.0/howto/static-files/
173
174STATIC_URL = 'static/'
175
176# Default primary key field type
177# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
178
179DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
180
181Watching for file changes with StatReloader
182Performing system checks...
183
184Exception in thread django-main-thread:
185Traceback (most recent call last):
186 File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
187 self.run()
188 File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
189 self._target(*self._args, **self._kwargs)
190 File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
191 fn(*args, **kwargs)
192 File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run
193 self.check(display_num_errors=True)
194 File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 488, in check
195 raise SystemCheckError(msg)
196django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
197
198ERRORS:
199inside.UserProfile.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
200 HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
201
202System check identified 1 issue (0 silenced).
203from django.db import models
204from django.contrib.auth.models import User
205from django.contrib.auth.models import AbstractBaseUser
206from django.conf import settings
207
208from django_countries.fields import CountryField
209
210# Create your models here.
211
212class UserProfile(AbstractBaseUser):
213 # Remove this as you no longer using the default User Model.
214 # user = models.OneToOneField(User, on_delete = models.DO_NOTHING)
215 phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False)
216 country = CountryField()
217 # As you are using UID as your username field
218 # it is not safe to make it blank and null true
219 uid = models.UUIDField(
220 default = None,
221 blank = True,
222 null = True,
223 unique = True,
224 )
225 USERNAME_FIELD = "uid"
226 REQUIRED_FIELDS = ['phone_number', 'country']
227 # Create your custom user manager
228 objects = YOUR_CUSTOM_USER_MANAGER()
229
Note: As you are using uid as your username field, you have to write a custom authentication backend so that you can use the phone number to authenticate the user, otherwise you have to use the phone number as a username field if you don't want to create a custom authentication backend.
QUESTION
is runtime language translation possible with angular (@angular/localize)?
Asked 2022-Jan-26 at 03:20I am trying to learn and add angular internationalization in a project. I can understand only compile time translation from angular documents (https://angular.io/guide/i18n-overview).
I need some thing like this https://stackblitz.com/github/ngx-translate/example which is third party library 'ngx-translate'.
Can't we achieve the same runtime translation just with angular library without any third party library ?
Please guide me if runtime translation is possible with angular library.
ANSWER
Answered 2022-Jan-26 at 03:20no solutions for runtime with i18n from angular box. Only use ngx-translate. Angular team still only talks about "we will do it in next version", but no success. I work under big project and we use ngx-translate from angular version 4 or 6. u can trust this fird party library. i18n can only build app for some baseHref like:
When u need to compile a lot of app for work with i18n. ngx-translate - only 1 app, and translations can be splitted by modules where this translations is need.
My advice - use ngx-translate and when angular team will make runtime language reload - rewrite project part for translation
QUESTION
How to generate dynamic paths for non-default locales in Next.js?
Asked 2022-Jan-22 at 16:29I am building a Next.js app with internationalization using next-i18next. Pages are generated for all the pages of my site for both English and French, except for pages with dynamic routes: (i.e., blog/[id]/[blog-title]
). For pages with dynamic routes, pages are generated for English, but not for French.
I should note that the blog entries are the same in both languages. So if the user click on a blog entry in the list, they will get the same blog entry.
When a French language user goes to a page with a dynamic route they get a 404. I am new to React and Next so I could be doing something dumb here.
1// next-i18next.config.js
2module.exports = {
3 i18n: {
4 locales: ['en', 'fr'],
5 defaultLocale: 'en',
6 localeDetection: true,
7 },
8}
9
1// next-i18next.config.js
2module.exports = {
3 i18n: {
4 locales: ['en', 'fr'],
5 defaultLocale: 'en',
6 localeDetection: true,
7 },
8}
9//
10// blog\[id]\[title]
11//
12export async function getStaticPaths() {
13 const response = await axios.get('https://api.myappi.com/blog')
14 const posts = response.data
15
16 const paths = posts.map((post: Props) => ({
17 params: { id: post.Id, title: post.Title },
18 }))
19
20 return { paths, fallback: false }
21}
22
23export async function getStaticProps(props: IStaticProps) {
24 const { id, locale } = props.params
25 const response = await axios.get(`https://api.myappi.com/blog/${id}`)
26 const post = await response.data
27
28 if (!post) {
29 return {
30 notFound: true,
31 }
32 }
33
34 return {
35 props: {
36 Id: post.Id,
37 Title: post.Title,
38 Blog: post.Blog,
39 DatePosted: post.DatePosted,
40 PostedBy: post.PostedBy,
41 ...(await serverSideTranslations(props.locale, ['common', 'blog']))
42 }
43 }
44}
45
ANSWER
Answered 2022-Jan-07 at 20:56For dynamic routes, you have to explicitly return the locales you want to be pre-generated from the getStaticPaths
function. If you don't, Next.js will only generate pages for the default locale.
From Internationalized Routing documentation:
For pages using
getStaticProps
with Dynamic Routes, all locale variants of the page desired to be prerendered need to be returned fromgetStaticPaths
. Along with theparams
object returned forpaths
, you can also return alocale
field specifying which locale you want to render.
This can be achieved by modifying your getStaticPaths
function to generate a path for each slug/locale combination.
1// next-i18next.config.js
2module.exports = {
3 i18n: {
4 locales: ['en', 'fr'],
5 defaultLocale: 'en',
6 localeDetection: true,
7 },
8}
9//
10// blog\[id]\[title]
11//
12export async function getStaticPaths() {
13 const response = await axios.get('https://api.myappi.com/blog')
14 const posts = response.data
15
16 const paths = posts.map((post: Props) => ({
17 params: { id: post.Id, title: post.Title },
18 }))
19
20 return { paths, fallback: false }
21}
22
23export async function getStaticProps(props: IStaticProps) {
24 const { id, locale } = props.params
25 const response = await axios.get(`https://api.myappi.com/blog/${id}`)
26 const post = await response.data
27
28 if (!post) {
29 return {
30 notFound: true,
31 }
32 }
33
34 return {
35 props: {
36 Id: post.Id,
37 Title: post.Title,
38 Blog: post.Blog,
39 DatePosted: post.DatePosted,
40 PostedBy: post.PostedBy,
41 ...(await serverSideTranslations(props.locale, ['common', 'blog']))
42 }
43 }
44}
45export async function getStaticPaths({ locales }) { // Get available locales from `context`
46 const response = await axios.get('https://api.myappi.com/blog')
47 const posts = response.data
48
49 const paths = posts
50 .map((post: Props) => locales.map((locale) => ({
51 params: { id: post.Id, title: post.Title },
52 locale // Pass locale here
53 })))
54 .flat() // Flatten array to avoid nested arrays
55
56 return { paths, fallback: false }
57}
58
QUESTION
Is my django post method even being called?
Asked 2022-Jan-22 at 04:07I am trying to make a trading log app in Django but I have run into a few snags. It feels like my post method might night be being called when the submit button is clicked. I have tried printing and logging and neither ever fire in the post() method. The logging works fine in the get() method. Additionally I keep being routed back to my base index page even though I am rendering trading_log/add-order.html. I have also tried using a HTTPResponseRedirect. Both to no avail. I am really not sure what I am doing wrong at this point.
Settings.py
1"""
2Django settings for caspers_trading_tools project.
3
4Generated by 'django-admin startproject' using Django 4.0.1.
5
6For more information on this file, see
7https://docs.djangoproject.com/en/4.0/topics/settings/
8
9For the full list of settings and their values, see
10https://docs.djangoproject.com/en/4.0/ref/settings/
11"""
12
13from pathlib import Path
14import os
15
16# Build paths inside the project like this: BASE_DIR / 'subdir'.
17BASE_DIR = Path(__file__).resolve().parent.parent
18
19
20# Quick-start development settings - unsuitable for production
21# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
22
23# SECURITY WARNING: keep the secret key used in production secret!
24SECRET_KEY = 'django-insecure-d^@mw27((%t$wzj+3eykdmfmweufzep44sgkhib)^n1thdh!y6'
25
26# SECURITY WARNING: don't run with debug turned on in production!
27DEBUG = True
28
29ALLOWED_HOSTS = []
30
31
32# Application definition
33
34INSTALLED_APPS = [
35 'landing_page',
36 'trading_log',
37 'django.contrib.admin',
38 'django.contrib.auth',
39 'django.contrib.contenttypes',
40 'django.contrib.sessions',
41 'django.contrib.messages',
42 'django.contrib.staticfiles',
43]
44
45MIDDLEWARE = [
46 'django.middleware.security.SecurityMiddleware',
47 'django.contrib.sessions.middleware.SessionMiddleware',
48 'django.middleware.common.CommonMiddleware',
49 'django.middleware.csrf.CsrfViewMiddleware',
50 'django.contrib.auth.middleware.AuthenticationMiddleware',
51 'django.contrib.messages.middleware.MessageMiddleware',
52 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53]
54
55ROOT_URLCONF = 'caspers_trading_tools.urls'
56
57TEMPLATES = [
58 {
59 'BACKEND': 'django.template.backends.django.DjangoTemplates',
60 'DIRS': [
61 BASE_DIR / "templates",
62 BASE_DIR / "templates" / "includes"
63 ],
64 'APP_DIRS': True,
65 'OPTIONS': {
66 'context_processors': [
67 'django.template.context_processors.debug',
68 'django.template.context_processors.request',
69 'django.contrib.auth.context_processors.auth',
70 'django.contrib.messages.context_processors.messages',
71 ],
72 },
73 },
74]
75
76WSGI_APPLICATION = 'caspers_trading_tools.wsgi.application'
77
78
79# Database
80# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
81
82DATABASES = {
83 'default': {
84 'ENGINE': 'django.db.backends.sqlite3',
85 'NAME': BASE_DIR / 'db.sqlite3',
86 }
87}
88
89
90# Password validation
91# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
92
93AUTH_PASSWORD_VALIDATORS = [
94 {
95 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96 },
97 {
98 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99 },
100 {
101 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102 },
103 {
104 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105 },
106]
107
108
109# Internationalization
110# https://docs.djangoproject.com/en/4.0/topics/i18n/
111
112LANGUAGE_CODE = 'en-us'
113
114TIME_ZONE = 'UTC'
115
116USE_I18N = True
117
118USE_TZ = True
119
120
121# Static files (CSS, JavaScript, Images)
122# https://docs.djangoproject.com/en/4.0/howto/static-files/
123
124STATIC_URL = 'static/'
125
126STATICFILES_DIRS = [
127 BASE_DIR / "static"
128]
129
130
131# Default primary key field type
132# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
133
134DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
135
136
137LOGGING = {
138 'version': 1,
139 'disable_existing_loggers': False,
140 'filters': {
141 'require_debug_true': {
142 '()': 'django.utils.log.RequireDebugTrue',
143 },
144 },
145 'handlers': {
146 'file': {
147 'level': 'DEBUG',
148 'class': 'logging.FileHandler',
149 'filename': '.\\logs\\tradinglog_log.log',
150 }
151 },
152 'loggers': {
153 '': {
154 'handlers': ['file'],
155 'level': 'DEBUG',
156 'propagate': True,
157 },
158 },
159}
160
urls.py(from root app)
1"""
2Django settings for caspers_trading_tools project.
3
4Generated by 'django-admin startproject' using Django 4.0.1.
5
6For more information on this file, see
7https://docs.djangoproject.com/en/4.0/topics/settings/
8
9For the full list of settings and their values, see
10https://docs.djangoproject.com/en/4.0/ref/settings/
11"""
12
13from pathlib import Path
14import os
15
16# Build paths inside the project like this: BASE_DIR / 'subdir'.
17BASE_DIR = Path(__file__).resolve().parent.parent
18
19
20# Quick-start development settings - unsuitable for production
21# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
22
23# SECURITY WARNING: keep the secret key used in production secret!
24SECRET_KEY = 'django-insecure-d^@mw27((%t$wzj+3eykdmfmweufzep44sgkhib)^n1thdh!y6'
25
26# SECURITY WARNING: don't run with debug turned on in production!
27DEBUG = True
28
29ALLOWED_HOSTS = []
30
31
32# Application definition
33
34INSTALLED_APPS = [
35 'landing_page',
36 'trading_log',
37 'django.contrib.admin',
38 'django.contrib.auth',
39 'django.contrib.contenttypes',
40 'django.contrib.sessions',
41 'django.contrib.messages',
42 'django.contrib.staticfiles',
43]
44
45MIDDLEWARE = [
46 'django.middleware.security.SecurityMiddleware',
47 'django.contrib.sessions.middleware.SessionMiddleware',
48 'django.middleware.common.CommonMiddleware',
49 'django.middleware.csrf.CsrfViewMiddleware',
50 'django.contrib.auth.middleware.AuthenticationMiddleware',
51 'django.contrib.messages.middleware.MessageMiddleware',
52 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53]
54
55ROOT_URLCONF = 'caspers_trading_tools.urls'
56
57TEMPLATES = [
58 {
59 'BACKEND': 'django.template.backends.django.DjangoTemplates',
60 'DIRS': [
61 BASE_DIR / "templates",
62 BASE_DIR / "templates" / "includes"
63 ],
64 'APP_DIRS': True,
65 'OPTIONS': {
66 'context_processors': [
67 'django.template.context_processors.debug',
68 'django.template.context_processors.request',
69 'django.contrib.auth.context_processors.auth',
70 'django.contrib.messages.context_processors.messages',
71 ],
72 },
73 },
74]
75
76WSGI_APPLICATION = 'caspers_trading_tools.wsgi.application'
77
78
79# Database
80# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
81
82DATABASES = {
83 'default': {
84 'ENGINE': 'django.db.backends.sqlite3',
85 'NAME': BASE_DIR / 'db.sqlite3',
86 }
87}
88
89
90# Password validation
91# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
92
93AUTH_PASSWORD_VALIDATORS = [
94 {
95 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96 },
97 {
98 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99 },
100 {
101 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102 },
103 {
104 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105 },
106]
107
108
109# Internationalization
110# https://docs.djangoproject.com/en/4.0/topics/i18n/
111
112LANGUAGE_CODE = 'en-us'
113
114TIME_ZONE = 'UTC'
115
116USE_I18N = True
117
118USE_TZ = True
119
120
121# Static files (CSS, JavaScript, Images)
122# https://docs.djangoproject.com/en/4.0/howto/static-files/
123
124STATIC_URL = 'static/'
125
126STATICFILES_DIRS = [
127 BASE_DIR / "static"
128]
129
130
131# Default primary key field type
132# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
133
134DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
135
136
137LOGGING = {
138 'version': 1,
139 'disable_existing_loggers': False,
140 'filters': {
141 'require_debug_true': {
142 '()': 'django.utils.log.RequireDebugTrue',
143 },
144 },
145 'handlers': {
146 'file': {
147 'level': 'DEBUG',
148 'class': 'logging.FileHandler',
149 'filename': '.\\logs\\tradinglog_log.log',
150 }
151 },
152 'loggers': {
153 '': {
154 'handlers': ['file'],
155 'level': 'DEBUG',
156 'propagate': True,
157 },
158 },
159}
160from django.contrib import admin
161from django.urls import path, include
162
163urlpatterns = [
164 path('admin/', admin.site.urls),
165 path("", include("landing_page.urls")),
166 path("tradinglog/", include("trading_log.urls"))
167]
168
urls.py(from landing_page app)
1"""
2Django settings for caspers_trading_tools project.
3
4Generated by 'django-admin startproject' using Django 4.0.1.
5
6For more information on this file, see
7https://docs.djangoproject.com/en/4.0/topics/settings/
8
9For the full list of settings and their values, see
10https://docs.djangoproject.com/en/4.0/ref/settings/
11"""
12
13from pathlib import Path
14import os
15
16# Build paths inside the project like this: BASE_DIR / 'subdir'.
17BASE_DIR = Path(__file__).resolve().parent.parent
18
19
20# Quick-start development settings - unsuitable for production
21# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
22
23# SECURITY WARNING: keep the secret key used in production secret!
24SECRET_KEY = 'django-insecure-d^@mw27((%t$wzj+3eykdmfmweufzep44sgkhib)^n1thdh!y6'
25
26# SECURITY WARNING: don't run with debug turned on in production!
27DEBUG = True
28
29ALLOWED_HOSTS = []
30
31
32# Application definition
33
34INSTALLED_APPS = [
35 'landing_page',
36 'trading_log',
37 'django.contrib.admin',
38 'django.contrib.auth',
39 'django.contrib.contenttypes',
40 'django.contrib.sessions',
41 'django.contrib.messages',
42 'django.contrib.staticfiles',
43]
44
45MIDDLEWARE = [
46 'django.middleware.security.SecurityMiddleware',
47 'django.contrib.sessions.middleware.SessionMiddleware',
48 'django.middleware.common.CommonMiddleware',
49 'django.middleware.csrf.CsrfViewMiddleware',
50 'django.contrib.auth.middleware.AuthenticationMiddleware',
51 'django.contrib.messages.middleware.MessageMiddleware',
52 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53]
54
55ROOT_URLCONF = 'caspers_trading_tools.urls'
56
57TEMPLATES = [
58 {
59 'BACKEND': 'django.template.backends.django.DjangoTemplates',
60 'DIRS': [
61 BASE_DIR / "templates",
62 BASE_DIR / "templates" / "includes"
63 ],
64 'APP_DIRS': True,
65 'OPTIONS': {
66 'context_processors': [
67 'django.template.context_processors.debug',
68 'django.template.context_processors.request',
69 'django.contrib.auth.context_processors.auth',
70 'django.contrib.messages.context_processors.messages',
71 ],
72 },
73 },
74]
75
76WSGI_APPLICATION = 'caspers_trading_tools.wsgi.application'
77
78
79# Database
80# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
81
82DATABASES = {
83 'default': {
84 'ENGINE': 'django.db.backends.sqlite3',
85 'NAME': BASE_DIR / 'db.sqlite3',
86 }
87}
88
89
90# Password validation
91# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
92
93AUTH_PASSWORD_VALIDATORS = [
94 {
95 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96 },
97 {
98 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99 },
100 {
101 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102 },
103 {
104 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105 },
106]
107
108
109# Internationalization
110# https://docs.djangoproject.com/en/4.0/topics/i18n/
111
112LANGUAGE_CODE = 'en-us'
113
114TIME_ZONE = 'UTC'
115
116USE_I18N = True
117
118USE_TZ = True
119
120
121# Static files (CSS, JavaScript, Images)
122# https://docs.djangoproject.com/en/4.0/howto/static-files/
123
124STATIC_URL = 'static/'
125
126STATICFILES_DIRS = [
127 BASE_DIR / "static"
128]
129
130
131# Default primary key field type
132# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
133
134DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
135
136
137LOGGING = {
138 'version': 1,
139 'disable_existing_loggers': False,
140 'filters': {
141 'require_debug_true': {
142 '()': 'django.utils.log.RequireDebugTrue',
143 },
144 },
145 'handlers': {
146 'file': {
147 'level': 'DEBUG',
148 'class': 'logging.FileHandler',
149 'filename': '.\\logs\\tradinglog_log.log',
150 }
151 },
152 'loggers': {
153 '': {
154 'handlers': ['file'],
155 'level': 'DEBUG',
156 'propagate': True,
157 },
158 },
159}
160from django.contrib import admin
161from django.urls import path, include
162
163urlpatterns = [
164 path('admin/', admin.site.urls),
165 path("", include("landing_page.urls")),
166 path("tradinglog/", include("trading_log.urls"))
167]
168from django.urls import path
169
170from . import views
171
172urlpatterns = [
173 path("", views.starting_page, name="starting-page"),
174]
175
urls.py(from trading_log app)
1"""
2Django settings for caspers_trading_tools project.
3
4Generated by 'django-admin startproject' using Django 4.0.1.
5
6For more information on this file, see
7https://docs.djangoproject.com/en/4.0/topics/settings/
8
9For the full list of settings and their values, see
10https://docs.djangoproject.com/en/4.0/ref/settings/
11"""
12
13from pathlib import Path
14import os
15
16# Build paths inside the project like this: BASE_DIR / 'subdir'.
17BASE_DIR = Path(__file__).resolve().parent.parent
18
19
20# Quick-start development settings - unsuitable for production
21# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
22
23# SECURITY WARNING: keep the secret key used in production secret!
24SECRET_KEY = 'django-insecure-d^@mw27((%t$wzj+3eykdmfmweufzep44sgkhib)^n1thdh!y6'
25
26# SECURITY WARNING: don't run with debug turned on in production!
27DEBUG = True
28
29ALLOWED_HOSTS = []
30
31
32# Application definition
33
34INSTALLED_APPS = [
35 'landing_page',
36 'trading_log',
37 'django.contrib.admin',
38 'django.contrib.auth',
39 'django.contrib.contenttypes',
40 'django.contrib.sessions',
41 'django.contrib.messages',
42 'django.contrib.staticfiles',
43]
44
45MIDDLEWARE = [
46 'django.middleware.security.SecurityMiddleware',
47 'django.contrib.sessions.middleware.SessionMiddleware',
48 'django.middleware.common.CommonMiddleware',
49 'django.middleware.csrf.CsrfViewMiddleware',
50 'django.contrib.auth.middleware.AuthenticationMiddleware',
51 'django.contrib.messages.middleware.MessageMiddleware',
52 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53]
54
55ROOT_URLCONF = 'caspers_trading_tools.urls'
56
57TEMPLATES = [
58 {
59 'BACKEND': 'django.template.backends.django.DjangoTemplates',
60 'DIRS': [
61 BASE_DIR / "templates",
62 BASE_DIR / "templates" / "includes"
63 ],
64 'APP_DIRS': True,
65 'OPTIONS': {
66 'context_processors': [
67 'django.template.context_processors.debug',
68 'django.template.context_processors.request',
69 'django.contrib.auth.context_processors.auth',
70 'django.contrib.messages.context_processors.messages',
71 ],
72 },
73 },
74]
75
76WSGI_APPLICATION = 'caspers_trading_tools.wsgi.application'
77
78
79# Database
80# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
81
82DATABASES = {
83 'default': {
84 'ENGINE': 'django.db.backends.sqlite3',
85 'NAME': BASE_DIR / 'db.sqlite3',
86 }
87}
88
89
90# Password validation
91# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
92
93AUTH_PASSWORD_VALIDATORS = [
94 {
95 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96 },
97 {
98 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99 },
100 {
101 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102 },
103 {
104 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105 },
106]
107
108
109# Internationalization
110# https://docs.djangoproject.com/en/4.0/topics/i18n/
111
112LANGUAGE_CODE = 'en-us'
113
114TIME_ZONE = 'UTC'
115
116USE_I18N = True
117
118USE_TZ = True
119
120
121# Static files (CSS, JavaScript, Images)
122# https://docs.djangoproject.com/en/4.0/howto/static-files/
123
124STATIC_URL = 'static/'
125
126STATICFILES_DIRS = [
127 BASE_DIR / "static"
128]
129
130
131# Default primary key field type
132# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
133
134DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
135
136
137LOGGING = {
138 'version': 1,
139 'disable_existing_loggers': False,
140 'filters': {
141 'require_debug_true': {
142 '()': 'django.utils.log.RequireDebugTrue',
143 },
144 },
145 'handlers': {
146 'file': {
147 'level': 'DEBUG',
148 'class': 'logging.FileHandler',
149 'filename': '.\\logs\\tradinglog_log.log',
150 }
151 },
152 'loggers': {
153 '': {
154 'handlers': ['file'],
155 'level': 'DEBUG',
156 'propagate': True,
157 },
158 },
159}
160from django.contrib import admin
161from django.urls import path, include
162
163urlpatterns = [
164 path('admin/', admin.site.urls),
165 path("", include("landing_page.urls")),
166 path("tradinglog/", include("trading_log.urls"))
167]
168from django.urls import path
169
170from . import views
171
172urlpatterns = [
173 path("", views.starting_page, name="starting-page"),
174]
175
176from django.urls import path
177
178from . import views
179
180urlpatterns = [
181 path("", views.trading_log_starting_page, name="trading-log-page"),
182 path("all-orders", views.OrdersListView.as_view()),
183 path("all-trades", views.TradesListView.as_view(), name="all-trades-page"),
184 path("add-order", views.CreateOrderView.as_view(), name="add-order-page"),
185 path("add-trade", views.CreateTradeView.as_view())
186]
187
views.py
1"""
2Django settings for caspers_trading_tools project.
3
4Generated by 'django-admin startproject' using Django 4.0.1.
5
6For more information on this file, see
7https://docs.djangoproject.com/en/4.0/topics/settings/
8
9For the full list of settings and their values, see
10https://docs.djangoproject.com/en/4.0/ref/settings/
11"""
12
13from pathlib import Path
14import os
15
16# Build paths inside the project like this: BASE_DIR / 'subdir'.
17BASE_DIR = Path(__file__).resolve().parent.parent
18
19
20# Quick-start development settings - unsuitable for production
21# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
22
23# SECURITY WARNING: keep the secret key used in production secret!
24SECRET_KEY = 'django-insecure-d^@mw27((%t$wzj+3eykdmfmweufzep44sgkhib)^n1thdh!y6'
25
26# SECURITY WARNING: don't run with debug turned on in production!
27DEBUG = True
28
29ALLOWED_HOSTS = []
30
31
32# Application definition
33
34INSTALLED_APPS = [
35 'landing_page',
36 'trading_log',
37 'django.contrib.admin',
38 'django.contrib.auth',
39 'django.contrib.contenttypes',
40 'django.contrib.sessions',
41 'django.contrib.messages',
42 'django.contrib.staticfiles',
43]
44
45MIDDLEWARE = [
46 'django.middleware.security.SecurityMiddleware',
47 'django.contrib.sessions.middleware.SessionMiddleware',
48 'django.middleware.common.CommonMiddleware',
49 'django.middleware.csrf.CsrfViewMiddleware',
50 'django.contrib.auth.middleware.AuthenticationMiddleware',
51 'django.contrib.messages.middleware.MessageMiddleware',
52 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53]
54
55ROOT_URLCONF = 'caspers_trading_tools.urls'
56
57TEMPLATES = [
58 {
59 'BACKEND': 'django.template.backends.django.DjangoTemplates',
60 'DIRS': [
61 BASE_DIR / "templates",
62 BASE_DIR / "templates" / "includes"
63 ],
64 'APP_DIRS': True,
65 'OPTIONS': {
66 'context_processors': [
67 'django.template.context_processors.debug',
68 'django.template.context_processors.request',
69 'django.contrib.auth.context_processors.auth',
70 'django.contrib.messages.context_processors.messages',
71 ],
72 },
73 },
74]
75
76WSGI_APPLICATION = 'caspers_trading_tools.wsgi.application'
77
78
79# Database
80# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
81
82DATABASES = {
83 'default': {
84 'ENGINE': 'django.db.backends.sqlite3',
85 'NAME': BASE_DIR / 'db.sqlite3',
86 }
87}
88
89
90# Password validation
91# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
92
93AUTH_PASSWORD_VALIDATORS = [
94 {
95 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96 },
97 {
98 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99 },
100 {
101 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102 },
103 {
104 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105 },
106]
107
108
109# Internationalization
110# https://docs.djangoproject.com/en/4.0/topics/i18n/
111
112LANGUAGE_CODE = 'en-us'
113
114TIME_ZONE = 'UTC'
115
116USE_I18N = True
117
118USE_TZ = True
119
120
121# Static files (CSS, JavaScript, Images)
122# https://docs.djangoproject.com/en/4.0/howto/static-files/
123
124STATIC_URL = 'static/'
125
126STATICFILES_DIRS = [
127 BASE_DIR / "static"
128]
129
130
131# Default primary key field type
132# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
133
134DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
135
136
137LOGGING = {
138 'version': 1,
139 'disable_existing_loggers': False,
140 'filters': {
141 'require_debug_true': {
142 '()': 'django.utils.log.RequireDebugTrue',
143 },
144 },
145 'handlers': {
146 'file': {
147 'level': 'DEBUG',
148 'class': 'logging.FileHandler',
149 'filename': '.\\logs\\tradinglog_log.log',
150 }
151 },
152 'loggers': {
153 '': {
154 'handlers': ['file'],
155 'level': 'DEBUG',
156 'propagate': True,
157 },
158 },
159}
160from django.contrib import admin
161from django.urls import path, include
162
163urlpatterns = [
164 path('admin/', admin.site.urls),
165 path("", include("landing_page.urls")),
166 path("tradinglog/", include("trading_log.urls"))
167]
168from django.urls import path
169
170from . import views
171
172urlpatterns = [
173 path("", views.starting_page, name="starting-page"),
174]
175
176from django.urls import path
177
178from . import views
179
180urlpatterns = [
181 path("", views.trading_log_starting_page, name="trading-log-page"),
182 path("all-orders", views.OrdersListView.as_view()),
183 path("all-trades", views.TradesListView.as_view(), name="all-trades-page"),
184 path("add-order", views.CreateOrderView.as_view(), name="add-order-page"),
185 path("add-trade", views.CreateTradeView.as_view())
186]
187from trading_log.forms import CreateOrderForm
188from django.shortcuts import render
189from django.views.generic import ListView, View
190from django.http.response import HttpResponseRedirect
191from django.urls import reverse
192from django.utils.text import slugify
193import logging
194import uuid
195
196from .forms import CreateTradeForm
197from .models import Trade, Order
198
199
200# Create your views here.
201class TradesListView(ListView):
202 template_name = "trading_log/all-trades.html"
203 model = Trade
204 context_object_name = "trades"
205
206 def get_queryset(self):
207 request = self.request
208 # this should be removed once user_ids are implemented through Django's built in user registration and login
209 request.session["user_id"] = 1
210 user_id = request.session.get("user_id")
211 filtered_data = super().get_queryset().filter(user_id=user_id)
212 return filtered_data
213
214
215class OrdersListView(ListView):
216 template_name = "trading_log/all-orders.html"
217 model = Order
218 context_object_name = "orders"
219
220 def get_queryset(self):
221 request = self.request
222 # this should be removed once user_ids are implemented through login system and session creation
223 request.session["user_id"] = 1
224 user_id = request.session.get("user_id")
225 filtered_data = super().get_queryset().filter(user_id=user_id)
226 return filtered_data
227
228
229# Creates order view
230class CreateTradeView(View):
231 def get(self, request,):
232 form = CreateTradeForm()
233 return render(request, "trading_log/add-trade.html", {"form": form})
234
235 def post(self, request):
236 pass
237
238
239# Creates order view
240class CreateOrderView(View):
241 def get(self, request,):
242
243 logging.debug("TEST")
244 # this should be removed once user_ids are implemented through login system and session creation
245 request.session["user_id"] = 1
246 # should be set to session.get("user_id") probably in the future
247 user_id = request.session.get("user_id")
248 trade_form = CreateTradeForm()
249 order_form = CreateOrderForm()
250
251 context = {}
252 context["user_id"] = user_id
253 context["order_form"] = order_form
254 context["trade_form"] = trade_form
255 return render(request, "trading_log/add-order.html", context)
256
257 def post(self, request):
258 logging.debug("DSFSDFSDFSFD")
259 logging.error("Error test TEST")
260 logging.critical("Error test TEST 2")
261 # section commented out to try and resolve the lack of logging in post()
262 # trade_form = CreateTradeView(request.POST)
263 # order_form = CreateOrderForm(request.POST)
264 # trade = trade_form.save(commit=False)
265 # order = order_form.save(commit=False)
266 # trade.user_id = request.session.get("user_id")
267 # trade.setup_id = request.POST.get("setup_id")
268 # trade.notes = request.POST.get("notes")
269 # slug = slugify(str(trade.user_id) + str(trade.setup_id.name) +
270 # str(order.asset_id.name) + uuid.uuid4())
271 # trade.trade_slug = slugify(slug)
272
273 # logging.info("TRADE", trade)
274 # logging.info("ORDER", order)
275
276 # return HttpResponseRedirect(reverse("add-order-page"))
277 return render(request, "trading_log/add-order.html")
278
279
280def trading_log_starting_page(request):
281 all_trades = Trade.objects.all()
282 return render(request, "trading_log/index.html", {
283 "all_trades": all_trades
284 })
285
forms.py
1"""
2Django settings for caspers_trading_tools project.
3
4Generated by 'django-admin startproject' using Django 4.0.1.
5
6For more information on this file, see
7https://docs.djangoproject.com/en/4.0/topics/settings/
8
9For the full list of settings and their values, see
10https://docs.djangoproject.com/en/4.0/ref/settings/
11"""
12
13from pathlib import Path
14import os
15
16# Build paths inside the project like this: BASE_DIR / 'subdir'.
17BASE_DIR = Path(__file__).resolve().parent.parent
18
19
20# Quick-start development settings - unsuitable for production
21# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
22
23# SECURITY WARNING: keep the secret key used in production secret!
24SECRET_KEY = 'django-insecure-d^@mw27((%t$wzj+3eykdmfmweufzep44sgkhib)^n1thdh!y6'
25
26# SECURITY WARNING: don't run with debug turned on in production!
27DEBUG = True
28
29ALLOWED_HOSTS = []
30
31
32# Application definition
33
34INSTALLED_APPS = [
35 'landing_page',
36 'trading_log',
37 'django.contrib.admin',
38 'django.contrib.auth',
39 'django.contrib.contenttypes',
40 'django.contrib.sessions',
41 'django.contrib.messages',
42 'django.contrib.staticfiles',
43]
44
45MIDDLEWARE = [
46 'django.middleware.security.SecurityMiddleware',
47 'django.contrib.sessions.middleware.SessionMiddleware',
48 'django.middleware.common.CommonMiddleware',
49 'django.middleware.csrf.CsrfViewMiddleware',
50 'django.contrib.auth.middleware.AuthenticationMiddleware',
51 'django.contrib.messages.middleware.MessageMiddleware',
52 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53]
54
55ROOT_URLCONF = 'caspers_trading_tools.urls'
56
57TEMPLATES = [
58 {
59 'BACKEND': 'django.template.backends.django.DjangoTemplates',
60 'DIRS': [
61 BASE_DIR / "templates",
62 BASE_DIR / "templates" / "includes"
63 ],
64 'APP_DIRS': True,
65 'OPTIONS': {
66 'context_processors': [
67 'django.template.context_processors.debug',
68 'django.template.context_processors.request',
69 'django.contrib.auth.context_processors.auth',
70 'django.contrib.messages.context_processors.messages',
71 ],
72 },
73 },
74]
75
76WSGI_APPLICATION = 'caspers_trading_tools.wsgi.application'
77
78
79# Database
80# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
81
82DATABASES = {
83 'default': {
84 'ENGINE': 'django.db.backends.sqlite3',
85 'NAME': BASE_DIR / 'db.sqlite3',
86 }
87}
88
89
90# Password validation
91# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
92
93AUTH_PASSWORD_VALIDATORS = [
94 {
95 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96 },
97 {
98 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99 },
100 {
101 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102 },
103 {
104 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105 },
106]
107
108
109# Internationalization
110# https://docs.djangoproject.com/en/4.0/topics/i18n/
111
112LANGUAGE_CODE = 'en-us'
113
114TIME_ZONE = 'UTC'
115
116USE_I18N = True
117
118USE_TZ = True
119
120
121# Static files (CSS, JavaScript, Images)
122# https://docs.djangoproject.com/en/4.0/howto/static-files/
123
124STATIC_URL = 'static/'
125
126STATICFILES_DIRS = [
127 BASE_DIR / "static"
128]
129
130
131# Default primary key field type
132# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
133
134DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
135
136
137LOGGING = {
138 'version': 1,
139 'disable_existing_loggers': False,
140 'filters': {
141 'require_debug_true': {
142 '()': 'django.utils.log.RequireDebugTrue',
143 },
144 },
145 'handlers': {
146 'file': {
147 'level': 'DEBUG',
148 'class': 'logging.FileHandler',
149 'filename': '.\\logs\\tradinglog_log.log',
150 }
151 },
152 'loggers': {
153 '': {
154 'handlers': ['file'],
155 'level': 'DEBUG',
156 'propagate': True,
157 },
158 },
159}
160from django.contrib import admin
161from django.urls import path, include
162
163urlpatterns = [
164 path('admin/', admin.site.urls),
165 path("", include("landing_page.urls")),
166 path("tradinglog/", include("trading_log.urls"))
167]
168from django.urls import path
169
170from . import views
171
172urlpatterns = [
173 path("", views.starting_page, name="starting-page"),
174]
175
176from django.urls import path
177
178from . import views
179
180urlpatterns = [
181 path("", views.trading_log_starting_page, name="trading-log-page"),
182 path("all-orders", views.OrdersListView.as_view()),
183 path("all-trades", views.TradesListView.as_view(), name="all-trades-page"),
184 path("add-order", views.CreateOrderView.as_view(), name="add-order-page"),
185 path("add-trade", views.CreateTradeView.as_view())
186]
187from trading_log.forms import CreateOrderForm
188from django.shortcuts import render
189from django.views.generic import ListView, View
190from django.http.response import HttpResponseRedirect
191from django.urls import reverse
192from django.utils.text import slugify
193import logging
194import uuid
195
196from .forms import CreateTradeForm
197from .models import Trade, Order
198
199
200# Create your views here.
201class TradesListView(ListView):
202 template_name = "trading_log/all-trades.html"
203 model = Trade
204 context_object_name = "trades"
205
206 def get_queryset(self):
207 request = self.request
208 # this should be removed once user_ids are implemented through Django's built in user registration and login
209 request.session["user_id"] = 1
210 user_id = request.session.get("user_id")
211 filtered_data = super().get_queryset().filter(user_id=user_id)
212 return filtered_data
213
214
215class OrdersListView(ListView):
216 template_name = "trading_log/all-orders.html"
217 model = Order
218 context_object_name = "orders"
219
220 def get_queryset(self):
221 request = self.request
222 # this should be removed once user_ids are implemented through login system and session creation
223 request.session["user_id"] = 1
224 user_id = request.session.get("user_id")
225 filtered_data = super().get_queryset().filter(user_id=user_id)
226 return filtered_data
227
228
229# Creates order view
230class CreateTradeView(View):
231 def get(self, request,):
232 form = CreateTradeForm()
233 return render(request, "trading_log/add-trade.html", {"form": form})
234
235 def post(self, request):
236 pass
237
238
239# Creates order view
240class CreateOrderView(View):
241 def get(self, request,):
242
243 logging.debug("TEST")
244 # this should be removed once user_ids are implemented through login system and session creation
245 request.session["user_id"] = 1
246 # should be set to session.get("user_id") probably in the future
247 user_id = request.session.get("user_id")
248 trade_form = CreateTradeForm()
249 order_form = CreateOrderForm()
250
251 context = {}
252 context["user_id"] = user_id
253 context["order_form"] = order_form
254 context["trade_form"] = trade_form
255 return render(request, "trading_log/add-order.html", context)
256
257 def post(self, request):
258 logging.debug("DSFSDFSDFSFD")
259 logging.error("Error test TEST")
260 logging.critical("Error test TEST 2")
261 # section commented out to try and resolve the lack of logging in post()
262 # trade_form = CreateTradeView(request.POST)
263 # order_form = CreateOrderForm(request.POST)
264 # trade = trade_form.save(commit=False)
265 # order = order_form.save(commit=False)
266 # trade.user_id = request.session.get("user_id")
267 # trade.setup_id = request.POST.get("setup_id")
268 # trade.notes = request.POST.get("notes")
269 # slug = slugify(str(trade.user_id) + str(trade.setup_id.name) +
270 # str(order.asset_id.name) + uuid.uuid4())
271 # trade.trade_slug = slugify(slug)
272
273 # logging.info("TRADE", trade)
274 # logging.info("ORDER", order)
275
276 # return HttpResponseRedirect(reverse("add-order-page"))
277 return render(request, "trading_log/add-order.html")
278
279
280def trading_log_starting_page(request):
281 all_trades = Trade.objects.all()
282 return render(request, "trading_log/index.html", {
283 "all_trades": all_trades
284 })
285from django import forms
286from django.forms import ModelForm
287
288from .models import Order, Trade
289
290
291class DateInput(forms.DateTimeInput):
292 input_type = "datetime-local"
293
294
295class CreateOrderForm(forms.ModelForm):
296
297 class Meta:
298 model = Order
299 fields = ['asset_id', 'direction_id', 'num_contracts', 'contract_id', 'order_type_id',
300 'price', 'datetime', 'time_frame_id', 'chart_screenshot', 'notes', 'trade_id', 'order_slug']
301 widgets = {
302 'datetime': DateInput(),
303 }
304
305 labels = {
306 'asset_id': 'Asset',
307 'direction_id': 'Direction',
308 'contract_name_id': 'Contract Name',
309 'num_contracts': 'Number of Contracts',
310 'order_type_id': 'Order Type',
311 'datetime': 'Date Time',
312 'time_frame_id': 'Time Frame',
313 'chart_screenshot': 'Chart Screenshot',
314 }
315
316class CreateTradeForm(forms.ModelForm):
317 class Meta:
318 model = Trade
319 fields = ['setup_id', 'notes']
320
321 labels = {
322 "setup_id": "Setup",
323 "notes": "Overall Trade Notes"
324 }
325
template: add-order.html
1"""
2Django settings for caspers_trading_tools project.
3
4Generated by 'django-admin startproject' using Django 4.0.1.
5
6For more information on this file, see
7https://docs.djangoproject.com/en/4.0/topics/settings/
8
9For the full list of settings and their values, see
10https://docs.djangoproject.com/en/4.0/ref/settings/
11"""
12
13from pathlib import Path
14import os
15
16# Build paths inside the project like this: BASE_DIR / 'subdir'.
17BASE_DIR = Path(__file__).resolve().parent.parent
18
19
20# Quick-start development settings - unsuitable for production
21# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
22
23# SECURITY WARNING: keep the secret key used in production secret!
24SECRET_KEY = 'django-insecure-d^@mw27((%t$wzj+3eykdmfmweufzep44sgkhib)^n1thdh!y6'
25
26# SECURITY WARNING: don't run with debug turned on in production!
27DEBUG = True
28
29ALLOWED_HOSTS = []
30
31
32# Application definition
33
34INSTALLED_APPS = [
35 'landing_page',
36 'trading_log',
37 'django.contrib.admin',
38 'django.contrib.auth',
39 'django.contrib.contenttypes',
40 'django.contrib.sessions',
41 'django.contrib.messages',
42 'django.contrib.staticfiles',
43]
44
45MIDDLEWARE = [
46 'django.middleware.security.SecurityMiddleware',
47 'django.contrib.sessions.middleware.SessionMiddleware',
48 'django.middleware.common.CommonMiddleware',
49 'django.middleware.csrf.CsrfViewMiddleware',
50 'django.contrib.auth.middleware.AuthenticationMiddleware',
51 'django.contrib.messages.middleware.MessageMiddleware',
52 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53]
54
55ROOT_URLCONF = 'caspers_trading_tools.urls'
56
57TEMPLATES = [
58 {
59 'BACKEND': 'django.template.backends.django.DjangoTemplates',
60 'DIRS': [
61 BASE_DIR / "templates",
62 BASE_DIR / "templates" / "includes"
63 ],
64 'APP_DIRS': True,
65 'OPTIONS': {
66 'context_processors': [
67 'django.template.context_processors.debug',
68 'django.template.context_processors.request',
69 'django.contrib.auth.context_processors.auth',
70 'django.contrib.messages.context_processors.messages',
71 ],
72 },
73 },
74]
75
76WSGI_APPLICATION = 'caspers_trading_tools.wsgi.application'
77
78
79# Database
80# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
81
82DATABASES = {
83 'default': {
84 'ENGINE': 'django.db.backends.sqlite3',
85 'NAME': BASE_DIR / 'db.sqlite3',
86 }
87}
88
89
90# Password validation
91# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
92
93AUTH_PASSWORD_VALIDATORS = [
94 {
95 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96 },
97 {
98 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99 },
100 {
101 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102 },
103 {
104 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105 },
106]
107
108
109# Internationalization
110# https://docs.djangoproject.com/en/4.0/topics/i18n/
111
112LANGUAGE_CODE = 'en-us'
113
114TIME_ZONE = 'UTC'
115
116USE_I18N = True
117
118USE_TZ = True
119
120
121# Static files (CSS, JavaScript, Images)
122# https://docs.djangoproject.com/en/4.0/howto/static-files/
123
124STATIC_URL = 'static/'
125
126STATICFILES_DIRS = [
127 BASE_DIR / "static"
128]
129
130
131# Default primary key field type
132# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
133
134DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
135
136
137LOGGING = {
138 'version': 1,
139 'disable_existing_loggers': False,
140 'filters': {
141 'require_debug_true': {
142 '()': 'django.utils.log.RequireDebugTrue',
143 },
144 },
145 'handlers': {
146 'file': {
147 'level': 'DEBUG',
148 'class': 'logging.FileHandler',
149 'filename': '.\\logs\\tradinglog_log.log',
150 }
151 },
152 'loggers': {
153 '': {
154 'handlers': ['file'],
155 'level': 'DEBUG',
156 'propagate': True,
157 },
158 },
159}
160from django.contrib import admin
161from django.urls import path, include
162
163urlpatterns = [
164 path('admin/', admin.site.urls),
165 path("", include("landing_page.urls")),
166 path("tradinglog/", include("trading_log.urls"))
167]
168from django.urls import path
169
170from . import views
171
172urlpatterns = [
173 path("", views.starting_page, name="starting-page"),
174]
175
176from django.urls import path
177
178from . import views
179
180urlpatterns = [
181 path("", views.trading_log_starting_page, name="trading-log-page"),
182 path("all-orders", views.OrdersListView.as_view()),
183 path("all-trades", views.TradesListView.as_view(), name="all-trades-page"),
184 path("add-order", views.CreateOrderView.as_view(), name="add-order-page"),
185 path("add-trade", views.CreateTradeView.as_view())
186]
187from trading_log.forms import CreateOrderForm
188from django.shortcuts import render
189from django.views.generic import ListView, View
190from django.http.response import HttpResponseRedirect
191from django.urls import reverse
192from django.utils.text import slugify
193import logging
194import uuid
195
196from .forms import CreateTradeForm
197from .models import Trade, Order
198
199
200# Create your views here.
201class TradesListView(ListView):
202 template_name = "trading_log/all-trades.html"
203 model = Trade
204 context_object_name = "trades"
205
206 def get_queryset(self):
207 request = self.request
208 # this should be removed once user_ids are implemented through Django's built in user registration and login
209 request.session["user_id"] = 1
210 user_id = request.session.get("user_id")
211 filtered_data = super().get_queryset().filter(user_id=user_id)
212 return filtered_data
213
214
215class OrdersListView(ListView):
216 template_name = "trading_log/all-orders.html"
217 model = Order
218 context_object_name = "orders"
219
220 def get_queryset(self):
221 request = self.request
222 # this should be removed once user_ids are implemented through login system and session creation
223 request.session["user_id"] = 1
224 user_id = request.session.get("user_id")
225 filtered_data = super().get_queryset().filter(user_id=user_id)
226 return filtered_data
227
228
229# Creates order view
230class CreateTradeView(View):
231 def get(self, request,):
232 form = CreateTradeForm()
233 return render(request, "trading_log/add-trade.html", {"form": form})
234
235 def post(self, request):
236 pass
237
238
239# Creates order view
240class CreateOrderView(View):
241 def get(self, request,):
242
243 logging.debug("TEST")
244 # this should be removed once user_ids are implemented through login system and session creation
245 request.session["user_id"] = 1
246 # should be set to session.get("user_id") probably in the future
247 user_id = request.session.get("user_id")
248 trade_form = CreateTradeForm()
249 order_form = CreateOrderForm()
250
251 context = {}
252 context["user_id"] = user_id
253 context["order_form"] = order_form
254 context["trade_form"] = trade_form
255 return render(request, "trading_log/add-order.html", context)
256
257 def post(self, request):
258 logging.debug("DSFSDFSDFSFD")
259 logging.error("Error test TEST")
260 logging.critical("Error test TEST 2")
261 # section commented out to try and resolve the lack of logging in post()
262 # trade_form = CreateTradeView(request.POST)
263 # order_form = CreateOrderForm(request.POST)
264 # trade = trade_form.save(commit=False)
265 # order = order_form.save(commit=False)
266 # trade.user_id = request.session.get("user_id")
267 # trade.setup_id = request.POST.get("setup_id")
268 # trade.notes = request.POST.get("notes")
269 # slug = slugify(str(trade.user_id) + str(trade.setup_id.name) +
270 # str(order.asset_id.name) + uuid.uuid4())
271 # trade.trade_slug = slugify(slug)
272
273 # logging.info("TRADE", trade)
274 # logging.info("ORDER", order)
275
276 # return HttpResponseRedirect(reverse("add-order-page"))
277 return render(request, "trading_log/add-order.html")
278
279
280def trading_log_starting_page(request):
281 all_trades = Trade.objects.all()
282 return render(request, "trading_log/index.html", {
283 "all_trades": all_trades
284 })
285from django import forms
286from django.forms import ModelForm
287
288from .models import Order, Trade
289
290
291class DateInput(forms.DateTimeInput):
292 input_type = "datetime-local"
293
294
295class CreateOrderForm(forms.ModelForm):
296
297 class Meta:
298 model = Order
299 fields = ['asset_id', 'direction_id', 'num_contracts', 'contract_id', 'order_type_id',
300 'price', 'datetime', 'time_frame_id', 'chart_screenshot', 'notes', 'trade_id', 'order_slug']
301 widgets = {
302 'datetime': DateInput(),
303 }
304
305 labels = {
306 'asset_id': 'Asset',
307 'direction_id': 'Direction',
308 'contract_name_id': 'Contract Name',
309 'num_contracts': 'Number of Contracts',
310 'order_type_id': 'Order Type',
311 'datetime': 'Date Time',
312 'time_frame_id': 'Time Frame',
313 'chart_screenshot': 'Chart Screenshot',
314 }
315
316class CreateTradeForm(forms.ModelForm):
317 class Meta:
318 model = Trade
319 fields = ['setup_id', 'notes']
320
321 labels = {
322 "setup_id": "Setup",
323 "notes": "Overall Trade Notes"
324 }
325{% extends "base.html" %}
326{% load static %}
327
328{% block title %}Add Order{% endblock %}
329
330{% block css_files %}
331{% endblock %}
332
333{% block content %}
334 <form action="/" type="submit" method="post">
335 {% csrf_token %}
336 {% for field in order_form %}
337 <div class="form-control {% if field.errors %}errors{% endif %}" >
338 {{ field.label_tag }}
339 {{ field }}
340 {{ field.errors }}
341 </div>
342 {% endfor %}
343
344 {% for field in trade_form %}
345 <div class="form-control {% if field.errors %}errors{% endif %}" >
346 {{ field.label_tag }}
347 {{ field }}
348 {{ field.errors }}
349 </div>
350 {% endfor %}
351 <button>Send</button>
352 </form>
353{% endblock %}
354
ANSWER
Answered 2022-Jan-21 at 21:37Your form is redirecting to your index page, because that's what you've indicated in
1"""
2Django settings for caspers_trading_tools project.
3
4Generated by 'django-admin startproject' using Django 4.0.1.
5
6For more information on this file, see
7https://docs.djangoproject.com/en/4.0/topics/settings/
8
9For the full list of settings and their values, see
10https://docs.djangoproject.com/en/4.0/ref/settings/
11"""
12
13from pathlib import Path
14import os
15
16# Build paths inside the project like this: BASE_DIR / 'subdir'.
17BASE_DIR = Path(__file__).resolve().parent.parent
18
19
20# Quick-start development settings - unsuitable for production
21# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
22
23# SECURITY WARNING: keep the secret key used in production secret!
24SECRET_KEY = 'django-insecure-d^@mw27((%t$wzj+3eykdmfmweufzep44sgkhib)^n1thdh!y6'
25
26# SECURITY WARNING: don't run with debug turned on in production!
27DEBUG = True
28
29ALLOWED_HOSTS = []
30
31
32# Application definition
33
34INSTALLED_APPS = [
35 'landing_page',
36 'trading_log',
37 'django.contrib.admin',
38 'django.contrib.auth',
39 'django.contrib.contenttypes',
40 'django.contrib.sessions',
41 'django.contrib.messages',
42 'django.contrib.staticfiles',
43]
44
45MIDDLEWARE = [
46 'django.middleware.security.SecurityMiddleware',
47 'django.contrib.sessions.middleware.SessionMiddleware',
48 'django.middleware.common.CommonMiddleware',
49 'django.middleware.csrf.CsrfViewMiddleware',
50 'django.contrib.auth.middleware.AuthenticationMiddleware',
51 'django.contrib.messages.middleware.MessageMiddleware',
52 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53]
54
55ROOT_URLCONF = 'caspers_trading_tools.urls'
56
57TEMPLATES = [
58 {
59 'BACKEND': 'django.template.backends.django.DjangoTemplates',
60 'DIRS': [
61 BASE_DIR / "templates",
62 BASE_DIR / "templates" / "includes"
63 ],
64 'APP_DIRS': True,
65 'OPTIONS': {
66 'context_processors': [
67 'django.template.context_processors.debug',
68 'django.template.context_processors.request',
69 'django.contrib.auth.context_processors.auth',
70 'django.contrib.messages.context_processors.messages',
71 ],
72 },
73 },
74]
75
76WSGI_APPLICATION = 'caspers_trading_tools.wsgi.application'
77
78
79# Database
80# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
81
82DATABASES = {
83 'default': {
84 'ENGINE': 'django.db.backends.sqlite3',
85 'NAME': BASE_DIR / 'db.sqlite3',
86 }
87}
88
89
90# Password validation
91# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
92
93AUTH_PASSWORD_VALIDATORS = [
94 {
95 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96 },
97 {
98 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99 },
100 {
101 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102 },
103 {
104 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105 },
106]
107
108
109# Internationalization
110# https://docs.djangoproject.com/en/4.0/topics/i18n/
111
112LANGUAGE_CODE = 'en-us'
113
114TIME_ZONE = 'UTC'
115
116USE_I18N = True
117
118USE_TZ = True
119
120
121# Static files (CSS, JavaScript, Images)
122# https://docs.djangoproject.com/en/4.0/howto/static-files/
123
124STATIC_URL = 'static/'
125
126STATICFILES_DIRS = [
127 BASE_DIR / "static"
128]
129
130
131# Default primary key field type
132# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
133
134DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
135
136
137LOGGING = {
138 'version': 1,
139 'disable_existing_loggers': False,
140 'filters': {
141 'require_debug_true': {
142 '()': 'django.utils.log.RequireDebugTrue',
143 },
144 },
145 'handlers': {
146 'file': {
147 'level': 'DEBUG',
148 'class': 'logging.FileHandler',
149 'filename': '.\\logs\\tradinglog_log.log',
150 }
151 },
152 'loggers': {
153 '': {
154 'handlers': ['file'],
155 'level': 'DEBUG',
156 'propagate': True,
157 },
158 },
159}
160from django.contrib import admin
161from django.urls import path, include
162
163urlpatterns = [
164 path('admin/', admin.site.urls),
165 path("", include("landing_page.urls")),
166 path("tradinglog/", include("trading_log.urls"))
167]
168from django.urls import path
169
170from . import views
171
172urlpatterns = [
173 path("", views.starting_page, name="starting-page"),
174]
175
176from django.urls import path
177
178from . import views
179
180urlpatterns = [
181 path("", views.trading_log_starting_page, name="trading-log-page"),
182 path("all-orders", views.OrdersListView.as_view()),
183 path("all-trades", views.TradesListView.as_view(), name="all-trades-page"),
184 path("add-order", views.CreateOrderView.as_view(), name="add-order-page"),
185 path("add-trade", views.CreateTradeView.as_view())
186]
187from trading_log.forms import CreateOrderForm
188from django.shortcuts import render
189from django.views.generic import ListView, View
190from django.http.response import HttpResponseRedirect
191from django.urls import reverse
192from django.utils.text import slugify
193import logging
194import uuid
195
196from .forms import CreateTradeForm
197from .models import Trade, Order
198
199
200# Create your views here.
201class TradesListView(ListView):
202 template_name = "trading_log/all-trades.html"
203 model = Trade
204 context_object_name = "trades"
205
206 def get_queryset(self):
207 request = self.request
208 # this should be removed once user_ids are implemented through Django's built in user registration and login
209 request.session["user_id"] = 1
210 user_id = request.session.get("user_id")
211 filtered_data = super().get_queryset().filter(user_id=user_id)
212 return filtered_data
213
214
215class OrdersListView(ListView):
216 template_name = "trading_log/all-orders.html"
217 model = Order
218 context_object_name = "orders"
219
220 def get_queryset(self):
221 request = self.request
222 # this should be removed once user_ids are implemented through login system and session creation
223 request.session["user_id"] = 1
224 user_id = request.session.get("user_id")
225 filtered_data = super().get_queryset().filter(user_id=user_id)
226 return filtered_data
227
228
229# Creates order view
230class CreateTradeView(View):
231 def get(self, request,):
232 form = CreateTradeForm()
233 return render(request, "trading_log/add-trade.html", {"form": form})
234
235 def post(self, request):
236 pass
237
238
239# Creates order view
240class CreateOrderView(View):
241 def get(self, request,):
242
243 logging.debug("TEST")
244 # this should be removed once user_ids are implemented through login system and session creation
245 request.session["user_id"] = 1
246 # should be set to session.get("user_id") probably in the future
247 user_id = request.session.get("user_id")
248 trade_form = CreateTradeForm()
249 order_form = CreateOrderForm()
250
251 context = {}
252 context["user_id"] = user_id
253 context["order_form"] = order_form
254 context["trade_form"] = trade_form
255 return render(request, "trading_log/add-order.html", context)
256
257 def post(self, request):
258 logging.debug("DSFSDFSDFSFD")
259 logging.error("Error test TEST")
260 logging.critical("Error test TEST 2")
261 # section commented out to try and resolve the lack of logging in post()
262 # trade_form = CreateTradeView(request.POST)
263 # order_form = CreateOrderForm(request.POST)
264 # trade = trade_form.save(commit=False)
265 # order = order_form.save(commit=False)
266 # trade.user_id = request.session.get("user_id")
267 # trade.setup_id = request.POST.get("setup_id")
268 # trade.notes = request.POST.get("notes")
269 # slug = slugify(str(trade.user_id) + str(trade.setup_id.name) +
270 # str(order.asset_id.name) + uuid.uuid4())
271 # trade.trade_slug = slugify(slug)
272
273 # logging.info("TRADE", trade)
274 # logging.info("ORDER", order)
275
276 # return HttpResponseRedirect(reverse("add-order-page"))
277 return render(request, "trading_log/add-order.html")
278
279
280def trading_log_starting_page(request):
281 all_trades = Trade.objects.all()
282 return render(request, "trading_log/index.html", {
283 "all_trades": all_trades
284 })
285from django import forms
286from django.forms import ModelForm
287
288from .models import Order, Trade
289
290
291class DateInput(forms.DateTimeInput):
292 input_type = "datetime-local"
293
294
295class CreateOrderForm(forms.ModelForm):
296
297 class Meta:
298 model = Order
299 fields = ['asset_id', 'direction_id', 'num_contracts', 'contract_id', 'order_type_id',
300 'price', 'datetime', 'time_frame_id', 'chart_screenshot', 'notes', 'trade_id', 'order_slug']
301 widgets = {
302 'datetime': DateInput(),
303 }
304
305 labels = {
306 'asset_id': 'Asset',
307 'direction_id': 'Direction',
308 'contract_name_id': 'Contract Name',
309 'num_contracts': 'Number of Contracts',
310 'order_type_id': 'Order Type',
311 'datetime': 'Date Time',
312 'time_frame_id': 'Time Frame',
313 'chart_screenshot': 'Chart Screenshot',
314 }
315
316class CreateTradeForm(forms.ModelForm):
317 class Meta:
318 model = Trade
319 fields = ['setup_id', 'notes']
320
321 labels = {
322 "setup_id": "Setup",
323 "notes": "Overall Trade Notes"
324 }
325{% extends "base.html" %}
326{% load static %}
327
328{% block title %}Add Order{% endblock %}
329
330{% block css_files %}
331{% endblock %}
332
333{% block content %}
334 <form action="/" type="submit" method="post">
335 {% csrf_token %}
336 {% for field in order_form %}
337 <div class="form-control {% if field.errors %}errors{% endif %}" >
338 {{ field.label_tag }}
339 {{ field }}
340 {{ field.errors }}
341 </div>
342 {% endfor %}
343
344 {% for field in trade_form %}
345 <div class="form-control {% if field.errors %}errors{% endif %}" >
346 {{ field.label_tag }}
347 {{ field }}
348 {{ field.errors }}
349 </div>
350 {% endfor %}
351 <button>Send</button>
352 </form>
353{% endblock %}
354<form action="/" type="submit" method="post">
355
The /
goes to your index page. Try changing it to:
1"""
2Django settings for caspers_trading_tools project.
3
4Generated by 'django-admin startproject' using Django 4.0.1.
5
6For more information on this file, see
7https://docs.djangoproject.com/en/4.0/topics/settings/
8
9For the full list of settings and their values, see
10https://docs.djangoproject.com/en/4.0/ref/settings/
11"""
12
13from pathlib import Path
14import os
15
16# Build paths inside the project like this: BASE_DIR / 'subdir'.
17BASE_DIR = Path(__file__).resolve().parent.parent
18
19
20# Quick-start development settings - unsuitable for production
21# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
22
23# SECURITY WARNING: keep the secret key used in production secret!
24SECRET_KEY = 'django-insecure-d^@mw27((%t$wzj+3eykdmfmweufzep44sgkhib)^n1thdh!y6'
25
26# SECURITY WARNING: don't run with debug turned on in production!
27DEBUG = True
28
29ALLOWED_HOSTS = []
30
31
32# Application definition
33
34INSTALLED_APPS = [
35 'landing_page',
36 'trading_log',
37 'django.contrib.admin',
38 'django.contrib.auth',
39 'django.contrib.contenttypes',
40 'django.contrib.sessions',
41 'django.contrib.messages',
42 'django.contrib.staticfiles',
43]
44
45MIDDLEWARE = [
46 'django.middleware.security.SecurityMiddleware',
47 'django.contrib.sessions.middleware.SessionMiddleware',
48 'django.middleware.common.CommonMiddleware',
49 'django.middleware.csrf.CsrfViewMiddleware',
50 'django.contrib.auth.middleware.AuthenticationMiddleware',
51 'django.contrib.messages.middleware.MessageMiddleware',
52 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53]
54
55ROOT_URLCONF = 'caspers_trading_tools.urls'
56
57TEMPLATES = [
58 {
59 'BACKEND': 'django.template.backends.django.DjangoTemplates',
60 'DIRS': [
61 BASE_DIR / "templates",
62 BASE_DIR / "templates" / "includes"
63 ],
64 'APP_DIRS': True,
65 'OPTIONS': {
66 'context_processors': [
67 'django.template.context_processors.debug',
68 'django.template.context_processors.request',
69 'django.contrib.auth.context_processors.auth',
70 'django.contrib.messages.context_processors.messages',
71 ],
72 },
73 },
74]
75
76WSGI_APPLICATION = 'caspers_trading_tools.wsgi.application'
77
78
79# Database
80# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
81
82DATABASES = {
83 'default': {
84 'ENGINE': 'django.db.backends.sqlite3',
85 'NAME': BASE_DIR / 'db.sqlite3',
86 }
87}
88
89
90# Password validation
91# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
92
93AUTH_PASSWORD_VALIDATORS = [
94 {
95 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96 },
97 {
98 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99 },
100 {
101 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102 },
103 {
104 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105 },
106]
107
108
109# Internationalization
110# https://docs.djangoproject.com/en/4.0/topics/i18n/
111
112LANGUAGE_CODE = 'en-us'
113
114TIME_ZONE = 'UTC'
115
116USE_I18N = True
117
118USE_TZ = True
119
120
121# Static files (CSS, JavaScript, Images)
122# https://docs.djangoproject.com/en/4.0/howto/static-files/
123
124STATIC_URL = 'static/'
125
126STATICFILES_DIRS = [
127 BASE_DIR / "static"
128]
129
130
131# Default primary key field type
132# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
133
134DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
135
136
137LOGGING = {
138 'version': 1,
139 'disable_existing_loggers': False,
140 'filters': {
141 'require_debug_true': {
142 '()': 'django.utils.log.RequireDebugTrue',
143 },
144 },
145 'handlers': {
146 'file': {
147 'level': 'DEBUG',
148 'class': 'logging.FileHandler',
149 'filename': '.\\logs\\tradinglog_log.log',
150 }
151 },
152 'loggers': {
153 '': {
154 'handlers': ['file'],
155 'level': 'DEBUG',
156 'propagate': True,
157 },
158 },
159}
160from django.contrib import admin
161from django.urls import path, include
162
163urlpatterns = [
164 path('admin/', admin.site.urls),
165 path("", include("landing_page.urls")),
166 path("tradinglog/", include("trading_log.urls"))
167]
168from django.urls import path
169
170from . import views
171
172urlpatterns = [
173 path("", views.starting_page, name="starting-page"),
174]
175
176from django.urls import path
177
178from . import views
179
180urlpatterns = [
181 path("", views.trading_log_starting_page, name="trading-log-page"),
182 path("all-orders", views.OrdersListView.as_view()),
183 path("all-trades", views.TradesListView.as_view(), name="all-trades-page"),
184 path("add-order", views.CreateOrderView.as_view(), name="add-order-page"),
185 path("add-trade", views.CreateTradeView.as_view())
186]
187from trading_log.forms import CreateOrderForm
188from django.shortcuts import render
189from django.views.generic import ListView, View
190from django.http.response import HttpResponseRedirect
191from django.urls import reverse
192from django.utils.text import slugify
193import logging
194import uuid
195
196from .forms import CreateTradeForm
197from .models import Trade, Order
198
199
200# Create your views here.
201class TradesListView(ListView):
202 template_name = "trading_log/all-trades.html"
203 model = Trade
204 context_object_name = "trades"
205
206 def get_queryset(self):
207 request = self.request
208 # this should be removed once user_ids are implemented through Django's built in user registration and login
209 request.session["user_id"] = 1
210 user_id = request.session.get("user_id")
211 filtered_data = super().get_queryset().filter(user_id=user_id)
212 return filtered_data
213
214
215class OrdersListView(ListView):
216 template_name = "trading_log/all-orders.html"
217 model = Order
218 context_object_name = "orders"
219
220 def get_queryset(self):
221 request = self.request
222 # this should be removed once user_ids are implemented through login system and session creation
223 request.session["user_id"] = 1
224 user_id = request.session.get("user_id")
225 filtered_data = super().get_queryset().filter(user_id=user_id)
226 return filtered_data
227
228
229# Creates order view
230class CreateTradeView(View):
231 def get(self, request,):
232 form = CreateTradeForm()
233 return render(request, "trading_log/add-trade.html", {"form": form})
234
235 def post(self, request):
236 pass
237
238
239# Creates order view
240class CreateOrderView(View):
241 def get(self, request,):
242
243 logging.debug("TEST")
244 # this should be removed once user_ids are implemented through login system and session creation
245 request.session["user_id"] = 1
246 # should be set to session.get("user_id") probably in the future
247 user_id = request.session.get("user_id")
248 trade_form = CreateTradeForm()
249 order_form = CreateOrderForm()
250
251 context = {}
252 context["user_id"] = user_id
253 context["order_form"] = order_form
254 context["trade_form"] = trade_form
255 return render(request, "trading_log/add-order.html", context)
256
257 def post(self, request):
258 logging.debug("DSFSDFSDFSFD")
259 logging.error("Error test TEST")
260 logging.critical("Error test TEST 2")
261 # section commented out to try and resolve the lack of logging in post()
262 # trade_form = CreateTradeView(request.POST)
263 # order_form = CreateOrderForm(request.POST)
264 # trade = trade_form.save(commit=False)
265 # order = order_form.save(commit=False)
266 # trade.user_id = request.session.get("user_id")
267 # trade.setup_id = request.POST.get("setup_id")
268 # trade.notes = request.POST.get("notes")
269 # slug = slugify(str(trade.user_id) + str(trade.setup_id.name) +
270 # str(order.asset_id.name) + uuid.uuid4())
271 # trade.trade_slug = slugify(slug)
272
273 # logging.info("TRADE", trade)
274 # logging.info("ORDER", order)
275
276 # return HttpResponseRedirect(reverse("add-order-page"))
277 return render(request, "trading_log/add-order.html")
278
279
280def trading_log_starting_page(request):
281 all_trades = Trade.objects.all()
282 return render(request, "trading_log/index.html", {
283 "all_trades": all_trades
284 })
285from django import forms
286from django.forms import ModelForm
287
288from .models import Order, Trade
289
290
291class DateInput(forms.DateTimeInput):
292 input_type = "datetime-local"
293
294
295class CreateOrderForm(forms.ModelForm):
296
297 class Meta:
298 model = Order
299 fields = ['asset_id', 'direction_id', 'num_contracts', 'contract_id', 'order_type_id',
300 'price', 'datetime', 'time_frame_id', 'chart_screenshot', 'notes', 'trade_id', 'order_slug']
301 widgets = {
302 'datetime': DateInput(),
303 }
304
305 labels = {
306 'asset_id': 'Asset',
307 'direction_id': 'Direction',
308 'contract_name_id': 'Contract Name',
309 'num_contracts': 'Number of Contracts',
310 'order_type_id': 'Order Type',
311 'datetime': 'Date Time',
312 'time_frame_id': 'Time Frame',
313 'chart_screenshot': 'Chart Screenshot',
314 }
315
316class CreateTradeForm(forms.ModelForm):
317 class Meta:
318 model = Trade
319 fields = ['setup_id', 'notes']
320
321 labels = {
322 "setup_id": "Setup",
323 "notes": "Overall Trade Notes"
324 }
325{% extends "base.html" %}
326{% load static %}
327
328{% block title %}Add Order{% endblock %}
329
330{% block css_files %}
331{% endblock %}
332
333{% block content %}
334 <form action="/" type="submit" method="post">
335 {% csrf_token %}
336 {% for field in order_form %}
337 <div class="form-control {% if field.errors %}errors{% endif %}" >
338 {{ field.label_tag }}
339 {{ field }}
340 {{ field.errors }}
341 </div>
342 {% endfor %}
343
344 {% for field in trade_form %}
345 <div class="form-control {% if field.errors %}errors{% endif %}" >
346 {{ field.label_tag }}
347 {{ field }}
348 {{ field.errors }}
349 </div>
350 {% endfor %}
351 <button>Send</button>
352 </form>
353{% endblock %}
354<form action="/" type="submit" method="post">
355<form action="#" type="submit" method="post">
356
The # will take it to the current page. The form action
is what tells which view you want the form data to be sent to. The # basically means just the current page you're on. If you wanted to send the data to another view you would simply do <form action='{% url 'name_of_your_view' %} ...>
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Internationalization
Tutorials and Learning Resources are not available at this moment for Internationalization