How to support 2 languages in a model CharField?
Suppose I have a Book model that has a Title CharField. I want it to display english and spanish title when the page is displayed in respective language. How to do this? Also is it supported in default admin panel? Thanks!
/r/django
https://redd.it/8ry2bd
Suppose I have a Book model that has a Title CharField. I want it to display english and spanish title when the page is displayed in respective language. How to do this? Also is it supported in default admin panel? Thanks!
/r/django
https://redd.it/8ry2bd
reddit
r/django - How to support 2 languages in a model CharField?
0 votes and 3 so far on reddit
Django with RabbitMQ
Is there a way to connect to RabbitMQ without constantly haveing to open and close the connection?
Now I have to open a new connection for every message.
/r/django
https://redd.it/8ryj8u
Is there a way to connect to RabbitMQ without constantly haveing to open and close the connection?
Now I have to open a new connection for every message.
/r/django
https://redd.it/8ryj8u
reddit
r/django - Django with RabbitMQ
1 votes and 6 so far on reddit
10 common security gotchas in Python and how to avoid them
https://medium.com/@anthonypjshaw/10-common-security-gotchas-in-python-and-how-to-avoid-them-e19fbe265e03
/r/Python
https://redd.it/8rxbab
https://medium.com/@anthonypjshaw/10-common-security-gotchas-in-python-and-how-to-avoid-them-e19fbe265e03
/r/Python
https://redd.it/8rxbab
Hacker Noon
10 common security gotchas in Python and how to avoid them
Writing secure code is hard. When you learn a language, a module or a framework, you learn how it supposed to be used. When thinking about…
Top 20 Python libraries for data science in 2018
https://www.activewizards.com/blog/top-20-python-libraries-for-data-science-in-2018/?utm_source=reddit&utm_medium=python&utm_campaign=python_2018
/r/Python
https://redd.it/8rzp6x
https://www.activewizards.com/blog/top-20-python-libraries-for-data-science-in-2018/?utm_source=reddit&utm_medium=python&utm_campaign=python_2018
/r/Python
https://redd.it/8rzp6x
ActiveWizards: data science and engineering lab
Top 20 Python libraries for data science | ActiveWizards: data science and engineering lab
An expanded list of best Python libraries for data science with a fresh look to the ones we already talked about.
The Ultimate List of Python YouTube Channels
https://realpython.com/python-youtube-channels/
/r/Python
https://redd.it/8s07vc
https://realpython.com/python-youtube-channels/
/r/Python
https://redd.it/8s07vc
Realpython
The Ultimate List of Python YouTube Channels – Real Python
We couldn't find a good and updated list of Python developer or Python programming YouTube channels online. So we created our own list with the best and most Pythonic YouTubers.
give an API key for REST flask api
Hello
I made my rest api using flask. and I am using flask-jwt-extended for tokens. each request will generate access and refresh tokens. While testing everything worked perfectly
HOWEVER
I started learning react for my frontend. I pretty much followed this \[modern react with redux by stephen\]([https://www.udemy.com/react-redux/](https://www.udemy.com/react-redux/learn/v4/)). He used api keys on different occasions: youtube api, googlemap api, a weather api and a costume api he made to demonstrate.
Now I have also dealt with twitter and reddit api before. all of them give an "access" key of some sort. This key does not expire and it doesn't need any refresh.
my question is, how to make an "api" key for consumers? or more technically for my front-end usage?
Thank you
/r/flask
https://redd.it/8s2rzu
Hello
I made my rest api using flask. and I am using flask-jwt-extended for tokens. each request will generate access and refresh tokens. While testing everything worked perfectly
HOWEVER
I started learning react for my frontend. I pretty much followed this \[modern react with redux by stephen\]([https://www.udemy.com/react-redux/](https://www.udemy.com/react-redux/learn/v4/)). He used api keys on different occasions: youtube api, googlemap api, a weather api and a costume api he made to demonstrate.
Now I have also dealt with twitter and reddit api before. all of them give an "access" key of some sort. This key does not expire and it doesn't need any refresh.
my question is, how to make an "api" key for consumers? or more technically for my front-end usage?
Thank you
/r/flask
https://redd.it/8s2rzu
Udemy
Modern React with Redux Training Course
Master React and Redux. Apply modern design patterns to build apps with React Router, TailwindCSS, Context, and Hooks!
pypi? Nope, never heard of that website before. Sorry.
https://github.com/google/diff-match-patch/issues/17
/r/Python
https://redd.it/8s0ktr
https://github.com/google/diff-match-patch/issues/17
/r/Python
https://redd.it/8s0ktr
GitHub
pypi release out of date · Issue #17 · google/diff-match-patch
Hi, The version of diff-match-patch on pypi is pretty out of date (2012-2013): https://pypi.org/project/diff-match-patch/ Do you have the ability to update this?
What's next after basic CRUD?
Hello guys,
It's me again with another dumb question.
I've "finished" few basic apps in my project. I have working CRUD for each app/model and I feel lost now. I'd like to add few things, but I'm not sure what's the best next step
\- Dashboard with charts, maybe few basic forms to add quickly object for specific model
\- Few simple "buttons" to do special actions eg. quickly increase/decrease amount in IntegerField
\- Ability to use custom script (It takes list of IDs and create pdfs of chosen ids), smth like form in which i could add ids and amounts of each id to pass it to the script
What should I do? Things like this require some frontend tools like react? Or can I do it with plain Django?
If I have to use frontend framework, which is better (for project and future job), react or vue?
If I use frontend framework, do I need to create REST API for each app in my project?
Thanks for any advices!
/r/djangolearning
https://redd.it/8s276j
Hello guys,
It's me again with another dumb question.
I've "finished" few basic apps in my project. I have working CRUD for each app/model and I feel lost now. I'd like to add few things, but I'm not sure what's the best next step
\- Dashboard with charts, maybe few basic forms to add quickly object for specific model
\- Few simple "buttons" to do special actions eg. quickly increase/decrease amount in IntegerField
\- Ability to use custom script (It takes list of IDs and create pdfs of chosen ids), smth like form in which i could add ids and amounts of each id to pass it to the script
What should I do? Things like this require some frontend tools like react? Or can I do it with plain Django?
If I have to use frontend framework, which is better (for project and future job), react or vue?
If I use frontend framework, do I need to create REST API for each app in my project?
Thanks for any advices!
/r/djangolearning
https://redd.it/8s276j
reddit
r/djangolearning - What's next after basic CRUD?
7 votes and 4 so far on reddit
Overiq Djangobin - A project based tutorial for Django 1.11
Hello everyone!
I have just finished writing Django 1.11 tutorial, where we will build a pastebin application called djangobin.
Tutorial link: https://overiq.com/django/1.11/intro-to-django/
Live Demo: http://overiq.pythonanywhere.com/
Github source: https://github.com/overiq/djangobin
/r/django
https://redd.it/8rz0h4
Hello everyone!
I have just finished writing Django 1.11 tutorial, where we will build a pastebin application called djangobin.
Tutorial link: https://overiq.com/django/1.11/intro-to-django/
Live Demo: http://overiq.pythonanywhere.com/
Github source: https://github.com/overiq/djangobin
/r/django
https://redd.it/8rz0h4
i have prebinned data. how can i use pandas and seaborn to display histograms based on those bins
see title.
I have csv files of this form
mass (g),count
0-499,600
500-999,2244
1000-1499,3245
...
4500-4999,2095
5000-8165,201
i have 6 such csv files and i'd like to see 6 histograms. the fact that the data is prebinned is giving me issues. i'd appreciate a hint! thanks for your time.
/r/pystats
https://redd.it/8s5tty
see title.
I have csv files of this form
mass (g),count
0-499,600
500-999,2244
1000-1499,3245
...
4500-4999,2095
5000-8165,201
i have 6 such csv files and i'd like to see 6 histograms. the fact that the data is prebinned is giving me issues. i'd appreciate a hint! thanks for your time.
/r/pystats
https://redd.it/8s5tty
reddit
r/pystats - i have prebinned data. how can i use pandas and seaborn to display histograms based on those bins
1 votes and 2 so far on reddit
MozartFlow: Doing analysis on audio like gender classification, instrument recognition, voice separation, genre classification | Not completed; If anyone interested, do collab.
https://github.com/techcentaur/MozartFlow
/r/Python
https://redd.it/8s6ll7
https://github.com/techcentaur/MozartFlow
/r/Python
https://redd.it/8s6ll7
GitHub
techcentaur/MozartFlow
MozartFlow - Using machine learning for the study of music.
Need help with chart.js and django.
Im using chart.js to display charts in my django website. I am also using an API call that then parses out JSON data for the chart using python. Does anyone then know how to use an axios call within javascript to call and display the data through my index.html file?
/r/django
https://redd.it/8s89tb
Im using chart.js to display charts in my django website. I am also using an API call that then parses out JSON data for the chart using python. Does anyone then know how to use an axios call within javascript to call and display the data through my index.html file?
/r/django
https://redd.it/8s89tb
reddit
r/django - Need help with chart.js and django.
0 votes and 1 so far on reddit
What's everyone working on this week?
Tell /r/python what you're working on this week! You can be bragging, grousing, sharing your passion, or explaining your pain. Talk about your current project or your pet project; whatever you want to share.
/r/Python
https://redd.it/8s95kt
Tell /r/python what you're working on this week! You can be bragging, grousing, sharing your passion, or explaining your pain. Talk about your current project or your pet project; whatever you want to share.
/r/Python
https://redd.it/8s95kt
reddit
r/Python - What's everyone working on this week?
1 votes and 2 so far on reddit
queryset appears empty in debugger during testing, but not in console
Hello,
I'm testing REST APIs with `rest_framework.test.APITestCase`, using their client for making requests and `model_mommy` for creating objects in the `setUp()` method.
The general working is quite simple: the view is supposed to fetch a User and an object, and assign permissions for the former to the latter by means of django-guardian's `assign_perm`; the test creates a user and a group in the `setUp` method, then the actual test performs a POST passing their pk's as payload.
The issue I'm seeing, is that when the `User.objects.filter(pk__in=people_ids)` instruction is executed, the value I see in the debugger is that of an empty queryset, while if I type the exact same line in a console connected to the same session as the debugger I see the actual value being found.
Then the view gets to the `assign_perm` instruction, and it crashes with an `IndexError: list index out of range` error on the first evaluation of the queryset itself, which happens on the for loop at line 247 in the file core.py of the django-guardian library.
Is there something obvious that I should be looking at, because I really cannot wrap my head around this.
(django 1.11.13)
Thanks
/r/django
https://redd.it/8s9y48
Hello,
I'm testing REST APIs with `rest_framework.test.APITestCase`, using their client for making requests and `model_mommy` for creating objects in the `setUp()` method.
The general working is quite simple: the view is supposed to fetch a User and an object, and assign permissions for the former to the latter by means of django-guardian's `assign_perm`; the test creates a user and a group in the `setUp` method, then the actual test performs a POST passing their pk's as payload.
The issue I'm seeing, is that when the `User.objects.filter(pk__in=people_ids)` instruction is executed, the value I see in the debugger is that of an empty queryset, while if I type the exact same line in a console connected to the same session as the debugger I see the actual value being found.
Then the view gets to the `assign_perm` instruction, and it crashes with an `IndexError: list index out of range` error on the first evaluation of the queryset itself, which happens on the for loop at line 247 in the file core.py of the django-guardian library.
Is there something obvious that I should be looking at, because I really cannot wrap my head around this.
(django 1.11.13)
Thanks
/r/django
https://redd.it/8s9y48
reddit
r/django - queryset appears empty in debugger during testing, but not in console
1 votes and 0 so far on reddit
Made a custom user, then tried to createsuperuser but got TypeError: hasattr(): attribute name must be string
I've created a new Django project and the first thing I did was create a custom user with the help of Django docs: https://docs.djangoproject.com/en/2.0/topics/auth/customizing/
After I wrote all the code for a custom user, and after I did **makemigrations** and **migrate** for the first time in this Django project, I tried to create a superuser while my virtual env is active by writing:
python manage.py createsuperuser
But it gave me this error:
> TypeError: hasattr(): attribute name must be string
I wrote all the custom user code in an app called **accounts**.
In the **settings** file I added 'accounts' to the INSTALLED_APPS list, and added in the bottom this line:
AUTH_USER_MODEL = 'accounts.CustomUser'
Here's all my source code, starting with models.py:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError("Users must have an email address")
if not password:
raise ValueError("Users must have a password")
user = self.model(
email = self.normalize_email(email)
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, password, first_name, last_name):
if not first_name:
raise ValueError("Staff and superusers must have a first name")
if not last_name:
raise ValueError("Staff and superusers must have a last name")
user = self.create_user(
email,
password=password
)
user.first_name = first_name
user.last_name = last_name
user.is_staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, password, first_name, last_name):
user = self.create_staffuser(
email,
password=password,
first_name=first_name,
last_name=last_name
)
user.is_admin = True
user.is_superuser = True # Not sure if this is needed
user.save(using=self._db)
return user
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(null=True, max_length=80, unique=True)
USERNAME_FIELD = 'email'
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
first_name = models.CharField(max_length=25, blank=True, null=True)
last_name = models.CharField(max_length=25, blank=True, null=True)
date_joined = models.DateField(auto_now_add=True, null=True)
REQUIRED_FIELDS = [first_name, last_name]
objects = CustomUserManager()
def __str__(self):
return self.email
def get_short_name():
return first_name
def get_full_name():
return first_name + ' ' + last_name
Then I wrote this in forms.py:
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import CustomUser
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = CustomUser
fields = ('email', 'first_name', 'last_name')
def clean_password2(self
I've created a new Django project and the first thing I did was create a custom user with the help of Django docs: https://docs.djangoproject.com/en/2.0/topics/auth/customizing/
After I wrote all the code for a custom user, and after I did **makemigrations** and **migrate** for the first time in this Django project, I tried to create a superuser while my virtual env is active by writing:
python manage.py createsuperuser
But it gave me this error:
> TypeError: hasattr(): attribute name must be string
I wrote all the custom user code in an app called **accounts**.
In the **settings** file I added 'accounts' to the INSTALLED_APPS list, and added in the bottom this line:
AUTH_USER_MODEL = 'accounts.CustomUser'
Here's all my source code, starting with models.py:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError("Users must have an email address")
if not password:
raise ValueError("Users must have a password")
user = self.model(
email = self.normalize_email(email)
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, password, first_name, last_name):
if not first_name:
raise ValueError("Staff and superusers must have a first name")
if not last_name:
raise ValueError("Staff and superusers must have a last name")
user = self.create_user(
email,
password=password
)
user.first_name = first_name
user.last_name = last_name
user.is_staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, password, first_name, last_name):
user = self.create_staffuser(
email,
password=password,
first_name=first_name,
last_name=last_name
)
user.is_admin = True
user.is_superuser = True # Not sure if this is needed
user.save(using=self._db)
return user
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(null=True, max_length=80, unique=True)
USERNAME_FIELD = 'email'
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
first_name = models.CharField(max_length=25, blank=True, null=True)
last_name = models.CharField(max_length=25, blank=True, null=True)
date_joined = models.DateField(auto_now_add=True, null=True)
REQUIRED_FIELDS = [first_name, last_name]
objects = CustomUserManager()
def __str__(self):
return self.email
def get_short_name():
return first_name
def get_full_name():
return first_name + ' ' + last_name
Then I wrote this in forms.py:
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import CustomUser
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = CustomUser
fields = ('email', 'first_name', 'last_name')
def clean_password2(self
):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = CustomUser
fields = ('email', 'password', 'first_name', 'last_name', 'is_active', 'is_admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
And in admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import CustomUser
from .forms import UserCreationForm, UserChangeForm
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'first_name', 'last_name', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('first_name', 'last_name',)}),
('Meta', {'fields': ('date_joined', 'last_login', 'is_active',)}),
('Permissions', {'fields': ('is_admin', 'is_staff',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'first_name', 'last_name' 'password1', 'password2')}
),
)
search_fields = ('email', 'first_name')
ordering = ('email',)
filter_horizontal = ()
admin.site.register(CustomUser, UserAdmin)
This is the entire error traceback:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/base.py", line 282, in run_from_argv
options = parser.parse_args(argv[2:])
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/base.py", line 54, in parse_args
return super().parse_args(args, namespace)
File "/usr/lib/python3.6/argparse.py", line 1739, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "/usr/lib/python3.6/argparse.py", line 1760, in parse_known_args
if not hasattr(namespace, action.dest):
TypeError: hasattr(): attribute name must
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = CustomUser
fields = ('email', 'password', 'first_name', 'last_name', 'is_active', 'is_admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
And in admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import CustomUser
from .forms import UserCreationForm, UserChangeForm
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'first_name', 'last_name', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('first_name', 'last_name',)}),
('Meta', {'fields': ('date_joined', 'last_login', 'is_active',)}),
('Permissions', {'fields': ('is_admin', 'is_staff',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'first_name', 'last_name' 'password1', 'password2')}
),
)
search_fields = ('email', 'first_name')
ordering = ('email',)
filter_horizontal = ()
admin.site.register(CustomUser, UserAdmin)
This is the entire error traceback:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/base.py", line 282, in run_from_argv
options = parser.parse_args(argv[2:])
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/base.py", line 54, in parse_args
return super().parse_args(args, namespace)
File "/usr/lib/python3.6/argparse.py", line 1739, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "/usr/lib/python3.6/argparse.py", line 1760, in parse_known_args
if not hasattr(namespace, action.dest):
TypeError: hasattr(): attribute name must
SQLAlchemy - How does the relationship() function work?
I've ripped this straight out of the mega tutorial:
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')
def __repr__(self):
return '<User {}>'.format(self.username)
class Post(db.Model):
id = db.Column(db.Integer, primary_key = True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
I looked at the SQLAlchemy documentation and I'm still having trouble deciphering this. When I run my shell and create a post authored by my first list in my user query, my post object correctly has a user_id of the user who authors that post. But How does it know this? Does the `ForeignKey` argument look at all my classes and and find the `id` field under user? If so, that much makes sense. But how exactly creating a relationship in the User class, and then Post class knowing to relate it's foreign key to the author of the Post is an enigma to me. Anyone care to explain please.
/r/flask
https://redd.it/8s2fmq
I've ripped this straight out of the mega tutorial:
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')
def __repr__(self):
return '<User {}>'.format(self.username)
class Post(db.Model):
id = db.Column(db.Integer, primary_key = True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
I looked at the SQLAlchemy documentation and I'm still having trouble deciphering this. When I run my shell and create a post authored by my first list in my user query, my post object correctly has a user_id of the user who authors that post. But How does it know this? Does the `ForeignKey` argument look at all my classes and and find the `id` field under user? If so, that much makes sense. But how exactly creating a relationship in the User class, and then Post class knowing to relate it's foreign key to the author of the Post is an enigma to me. Anyone care to explain please.
/r/flask
https://redd.it/8s2fmq
reddit
r/flask - SQLAlchemy - How does the relationship() function work?
12 votes and 5 so far on reddit