django and linking tables - python-3.x

I am trying to create a specialized membership application using django. I am having some trouble planning out my app + table structure and data flow. For example: I have the basic django user model. I am using a package called "allauth" and I have created a "Profile" model that holds basic person info. I have tied all that together and it works for sign-up, account verification, logout and getting to a primitive "user page". The next step is where I am getting a bit lost and getting an import error.
The person that creates a log-in must be 18 years old or more. That person might be an adult member or the parent of one or more youth members or be both a parent and an adult member. In any case the logged in person is thought of as being financially responsible for the member-account(s) associated with them. There is also a case where more than one log-in person (like spouses) could share multiple "accounts" between them. For example, either person in an adult couple could be financially responsible for paying the bills.
So, for a given log-in "profile" I need a ManyToMany relation to an "accounts" table. An account can have ManyToMany relations to one or more member records and member "records" should live in the "profile" table but might not have login records in the "User" table.
Now we approach my problem. With the allauth config and an account_adaptor method I have the django "User" model attached to the account profile, a la: (trimmed for brevity)
# PROFILE
import uuid
from auditlog.models import AuditlogHistoryField
from auditlog.registry import auditlog
from django.contrib.auth.models import User
from django.db import models
from .account import Account
class Profile(models.Model):
id = models.UUIDField(
max_length=32,
default=uuid.uuid4,
editable=False,
primary_key=True,
blank=False,
null=False,
)
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
unique=True,
blank=True,
null=True,
)
name_info = ...
birthdate = models.DateField(
blank=False,
null=False
)
address_info = ...
# ACCOUNT
import uuid
from auditlog.models import AuditlogHistoryField
from auditlog.registry import auditlog
from django.db import models
from .student import Student
from Billing.models.payment import Payment
class Account(models.Model):
id = models.UUIDField(
max_length=32,
default=uuid.uuid4,
editable=False,
primary_key=True,
blank=False,
null=False,
)
students = models.ManyToManyField(Student)
payments = models.ManyToManyField(Payment)
# STUDENT
import uuid
from auditlog.models import AuditlogHistoryField
from auditlog.registry import auditlog
from django.db import models
from .profile import Profile
class Student(models.Model):
id = models.UUIDField(
max_length=32,
default=uuid.uuid4,
editable=False,
primary_key=True,
blank=False,
null=False,
)
profile = models.OneToOneField(
Profile,
on_delete=models.CASCADE,
unique=True,
blank=False,
null=False,
)
When I do makemigrations I get the stacktrace:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\me\myProject\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\me\myProject\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\me\myProject\venv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\me\myProject\venv\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\me\myProject\venv\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Program Files (x86)\Python3-6-5\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\me\myProject\myApp\Manager\models\__init__.py", line 2, in <module>
from .group_list import *
File "C:\me\myProject\myApp\Manager\models\group_list.py", line 5, in <module>
from Members.models.profile import Profile
File "C:\me\myProject\myApp\Members\models\__init__.py", line 1, in <module>
from .profile import *
File "C:\me\myProject\myApp\Members\models\profile.py", line 8, in <module>
from .account import Account
File "C:\me\myProject\myApp\Members\models\account.py", line 7, in <module>
from .student import Student
File "C:\me\myProject\myApp\Members\models\student.py", line 7, in <module>
from .profile import Profile
ImportError: cannot import name 'Profile'
My thought is that this is creating some circular linking that django doesn't but I don't understand this well enought to work around it.
Thoughts: the Student table could be its own table but that feels wastful as the Profile table already has the necessary columns
Edit
I think this is a duplicate of this post

Related

Django 'migrate' command suggesting errors related to packages

I am new to Django and python and am presently taking a course on full stack web development, after following the course exactly the way it shows I have typed the following code within the models.py file:
from django.db import models
# Create your models here.
class Topic(models.Model):
top_name = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic)
name = models.CharField(max_length=264,unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage)
date = models.DateField()
def __str__(self):
return str(self.date)
And have tried to execute the command:
python manage.py migrate
The following is the error I get when calling this command:
Traceback (most recent call last):
File "C:\Users\Naseem\desktop\my_django_stuff\first_project\manage.py", line 22, in <module>
main()
File "C:\Users\Naseem\desktop\my_django_stuff\first_project\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 395, in execute
django.setup()
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\apps\registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\apps\config.py", line 224, in create
import_module(entry)
File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
The following is the settings.py file, installed_apps:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'first_app',
]
And the admin.py file:
from django.contrib import admin
The course showed the models.py file working without adding anything to admin.py, I am not sure why it is showing these errors.
When using foreign keys in your models, you have to set the on_delete parameter so django knows what to do with the entries when the model entry your foreign key is pointing to is deleted.
You could fix your models.py like this:
# Create your models here.
class Topic(models.Model):
top_name = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
name = models.CharField(max_length=264,unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage, on_delete=models.CASCADE)
date = models.DateField()
def __str__(self):
return str(self.date)
You can read more about the different choices you have for this field here and what they are doing.
First of all, in your installed_app list write
INSTALLED_APPS = [
.........
'first_app.apps.FirstAppConfig',
]
insted of just 'first_app'
then in admin.py file add this
from django.contrib import admin
from .models import *
myModels = [models.modelname, models.modelname.......]
admin.site.register(myModels)
then in your cmd first write
python manage.py makemigrations
and then write
python manage.py migrate
Hope this will work.

Is there a safe way to safely delete a Model field in Django?

I'm making a blog application in Django, and I want to modify a field of the Post class:
I want to change the meta_description field to just description.
From:
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
meta_description = models.TextField(blank=True, null=True)
body = models.TextField()
def __str__(self):
"""
Show the title and the author in the admin Page
"""
return self.title + " by " + str(self.author)
def get_absolute_url(self):
return reverse("blog:article_page", kwargs={"pk": self.pk})
⏎
To:
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
description = models.TextField(blank=True, null=True)
body = models.TextField()
def __str__(self):
"""
Show the title and the author in the admin Page
"""
return self.title + " by " + str(self.author)
def get_absolute_url(self):
return reverse("blog:article_page", kwargs={"pk": self.pk})
When I do that in the model: I have an error Making the migration:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 368, in execute
self.check()
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check
all_issues = checks.run_checks(
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 408, in check
for pattern in self.url_patterns:
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/DeveloperRode/urls.py", line 26, in <module>
path("blog/", include('blog.urls')),
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/blog/urls.py", line 2, in <module>
from .views import BlogView, ArticleDetail, PostCreateView, EditPost, PostDeleteView
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/blog/views.py", line 8, in <module>
from .forms import PostForm, EditForm
File "/home/daniel/MEGA/my-git/github/Developer-road-website/DeveloperRode/blog/forms.py", line 4, in <module>
class PostForm(forms.ModelForm):
File "/home/daniel/MEGA/my-git/github/Developer-road-website/venv/lib/python3.8/site-packages/django/forms/models.py", line 268, in __new__
raise FieldError(message)
What Can I do?
The reason this happens is because besides models, you likely have forms, views, serializers, etc. that still use meta_description. If you thus have a PostForm like:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['meta_description']
# change to description &uparrow;
then you should alter this to description as well. You thus should perform a search with meta_description through your project and alter the occurrences of meta_description, but be careful: not all the meta_descriptions per see refer to the field of the Post model, if it is about another model, you of course should not modify this.
I solved the Problem, It seem to be a Form problem, where I was calling the Old field meta_description.
I correct it in forms.py file and make the makemigrations command, after that it showed a prompt:
Did you rename post.meta_description to post.description (a TextField)? [y/N] y
And now there the problem is solved.

Python Django 3.1 The included URLconf 'mysite.urls' does not appear to have any patterns in it

I'm currently learning django by tutorial.
So I changed my return-renders to class-generic in views.
in URLs I added as_view() and then it gave me an error.
my traceback:
File "D:\Anaconda3\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "D:\Anaconda3\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "D:\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "D:\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "D:\Anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check
databases=databases,
File "D:\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "D:\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf 'mysite.urls' does not appear to have any patterns in it. If you see valid patter
ns in the file then the issue is probably caused by a circular import.
urls.py:
from django.urls import path
from . import views
app_name = 'myapp'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:id>/', views.DetailView.as_view(), name='detail'),
path('<int:id>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from .models import Question
from django.template import loader
from django.views import generic
class IndexView(generic.listView):
template_name = 'myapp/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')
class DetailView(generic.DetailView):
model = Question
template_name = 'myapp/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'myapp/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, id=question_id)
try:
selected_choice = question.choice_set.get(id=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'myapp/detail.html',
{'question': question,
'error_message': "You didn't select a choice."}
)
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseResponse(reverse_lazy('myapp:results', args=(question_id,)))
I considered other tutorials and threads but found nothing about my subject. I think I missed something about IDs and PKs.
class IndexView(generic.listView): please change it to class IndexView(generic.ListView):. Here you use listView is incorrect.
I got this error message just bcoz of error in code. I didnt specify the class name when imported the models page
from . models import classname
is the right where this class is used in that page
from . models import
is wrong

Django AttributeError: module 'clients' has no attribute 'models'

I'm running this command python manage.py makemigrations clients and I keep getting an AttributeError. Here are my models;
from django.db import models
import datetime
import calendar
import clients.models
from django.core.urlresolvers import reverse
# Create your models here.
class PartnerInfo(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
phone = models.IntegerField()
price = models.IntegerField()
class NewPartnerLead(models.Model, LeadStage):
new_name = models.CharField(max_length=50)
email = models.CharField(max_length=50)
phone_num = models.IntegerField()
lead_stage = LeadStage.lead_stage()
class Booking(models.Model, ClientLead):
number_of_bookings = models.IntegerField()
clients_name = ClientLead.client_name()
clients_phone = ClientLead.phone_number()
clients_email = ClientLead.email_address()
class BookingDetail(Booking):
start_date = datetime.datetime.date()
end_date = datetime.datetime.date()
destination = models.CharField(max_length=50)
#static
def number_of_days(self, start_date, end_date):
return end_date-start_date
class Payment(models.Model, PartnerInfo.price, Booking.BookingDetail.number_of_days):
cash_out = models.IntegerField()
#static
def client_payment(self, number_of_days, price):
return price*number_of_days
#static
def provider_cut(self, client_payment):
provider_cut = 0.8*client_payment
return provider_cut
#static
def balance(self, provider_cut):
provider_cut-cash_out
class Action(Actions):
status = Actions.status()
action = Actions.action()
models on clients.py
class ClientLead(models.Model):
client_name = models.CharField(max_length=100)
phone_number = models.IntegerField()
email_address = models.CharField(max_length=50)
class LeadStage(models.Model):
lead_stage = models.IntegerField()
#static
def lead_status(self, lead_stage):
if lead_stage == 1:
lead_status = 'cold'
if lead_stage == 2:
lead_status = 'interested'
if lead_stage == 3:
lead_status = 'engaged(verbally agreed to pay)'
if lead_stage == 4:
lead_status = 'sold'
return lead_status
class Detail(models.Model, partners.models.Booking):
client = models.ForeignKey(Client_lead, on_delete=models.CASCADE)
destination = models.CharField(max_length=20)
number_of_days = models.IntegerField()
delivery = models.CharField(max_length=4)
start = Bookings.booking_detail.startdate()
end = Bookings.booking_detail.enddate()
class CarDetails(models.Model):
car_type = models.CharField(max_length=50)
car_model = models.CharField(max_length=50)
car_make = models.CharField(max_length=50)
model_year = models.IntegerField()
car_price = models.IntegerField()
#static
def opportunity(self, car_price, number_of_days):
return car_price*number_of_days+delivery
class Actions(models.Model, Leadstage, Detail):
request_start = Detail.start()
request_destination = Detail.destination()
request_delivery = Detail.delivery()
status = models.ForeignKey(Lead_stage, on_delete=models.cascade)
action = models.charfield(max_length=100
when I try the makemigrations command, it raises the aforementioned attribute error. when I import the specific classes I require from partners.models, I get an import error.
Here Is the attribute error it keeps raising:
c:\users\marsha11\source\repos\telemetree\telemetree>python manage.py makemigrations clients
Traceback (most recent call last):
File "manage.py", line 17, in <module>
execute_from_command_line(sys.argv)
File "c:\users\marsha11\source\repos\telemetree\telemetree\env\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line
utility.execute()
File "c:\users\marsha11\source\repos\telemetree\telemetree\env\lib\site-packages\django\core\management\__init__.py", line 338, in execute
django.setup()
File "c:\users\marsha11\source\repos\telemetree\telemetree\env\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "c:\users\marsha11\source\repos\telemetree\telemetree\env\lib\site-packages\django\apps\registry.py", line 108, in populate
app_config.import_models()
File "c:\users\marsha11\source\repos\telemetree\telemetree\env\lib\site-packages\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "c:\users\marsha11\source\repos\telemetree\telemetree\clients\models.py", line 8, in <module>
import partners.models
File "c:\users\marsha11\source\repos\telemetree\telemetree\partners\models.py", line 19, in <module>
class NewPartnerLead(models.Model, clients.models.LeadStage):
AttributeError: module 'clients' has no attribute 'models'
I've been thinking that its because of the imports but it still is not working and haven't found out why its happening online.

Flask-SQLAlchemy: How do I call an instance method on a model instance before committing it to the database?

I have a model that I would like to initialize, e.g. SomeModel(name='george', password='whatever').
Before committing this to the database, I want to call another method (we'll call it gen_password_hash) to create a hashed version of the password, and set it as an attribute on the model instance.
So I want this to happen after instantiation, but before being committed to the database.
Update
I wanted to see if I could accomplish this by defining an __init__ function on my model.
def __init__(self, **kwargs):
self.set_pass(kwargs.pop('password'))
super(User, self).__init__(**kwargs)
self.generate_email_address_confirmation_token()
This is the traceback I get when trying to drop/recreate tables among other things to reset my app:
Traceback (most recent call last):
File "main.py", line 7, in <module>
import gg.cli
File "/home/blaine/freelance/myproject/gg/cli/__init__.py", line 183, in <module>
reset_all()
File "/home/blaine/freelance/myproject/gg/cli/__init__.py", line 164, in reset_all
load_test_data()
File "/home/blaine/freelance/myproject/gg/cli/__init__.py", line 51, in load_test_data
admin=True)
File "<string>", line 4, in __init__
File "/home/blaine/freelance/myproject/lib/python3.4/site-packages/sqlalchemy/orm/state.py", line 414, in _initialize_instance
manager.dispatch.init_failure(self, args, kwargs)
File "/home/blaine/freelance/myproject/lib/python3.4/site-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/home/blaine/freelance/myproject/lib/python3.4/site-packages/sqlalchemy/util/compat.py", line 187, in reraise
raise value
File "/home/blaine/freelance/myproject/lib/python3.4/site-packages/sqlalchemy/orm/state.py", line 411, in _initialize_instance
return manager.original_init(*mixed[1:], **kwargs)
File "/home/blaine/freelance/myproject/gg/users.py", line 67, in __init__
self.generate_email_address_confirmation_token()
File "/home/blaine/freelance/myproject/gg/users.py", line 71, in generate_email_address_confirmation_token
token.update(self.email_address.encode() + current_app.secret_key + \
File "/home/blaine/freelance/myproject/lib/python3.4/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/home/blaine/freelance/myproject/lib/python3.4/site-packages/werkzeug/local.py", line 306, in _get_current_object
return self.__local()
File "/home/blaine/freelance/myproject/lib/python3.4/site-packages/flask/globals.py", line 51, in _find_app
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in a way. To solve
this set up an application context with app.app_context(). See the
documentation for more information.
I used this question for reference.
The following is my interpretation of what you are looking to do. You want to create a static method that converts a given string password into a hashed password. Obviously python's hash is not a password hashing function, so I would recommend using something else more consistent and reliable. This hashing method can be used during the initialization of the User model inside your application. What this means is that every time you create a user with a username, email and password, that password is hashed first before it is made an attribute of the ensuing User object. Take a look at the following for an illustration:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
password = db.Column(db.String(36))
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = self.generate_pwd_hash(password)
#staticmethod
def generate_pwd_hash(pwd):
"""
This is where you define how
to hash the user's password.
"""
return str(hash(pwd)) # This is, of course, not the way to hash a password
db.create_all()
user = User(username='george',
email='george#example.com',
password='whatever')
try:
db.session.add(user)
db.session.commit()
except:
print("This username must already exist.")

Resources