ValueError: Invalid salt in flask - flask

I am still in learning phase and having this issue while going through tutorials
I do not understand why I am getting this error ValueError: Invalid salt
Complete Error Code is:
File "C:\Users\Aparichit\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py",
line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Aparichit\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py",
line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Aparichit\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py",
line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\Aparichit\Desktop\NoViewsIndia\noViews\views.py", line 46, in login_page
if attempted_user and bcrypt.check_password_hash(attempted_user.password_hash,
attempted_password):
File "C:\Users\Aparichit\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask_bcrypt.py",
line 193, in check_password_hash
return safe_str_cmp(bcrypt.hashpw(password, pw_hash), pw_hash)
File "C:\Users\Aparichit\AppData\Local\Programs\Python\Python39\Lib\site-packages\bcrypt_init_.py",
line 105, in hashpw
raise ValueError("Invalid salt")
My model.py code is:
class User(db.Model, UserMixin):
name = db.Column(db.String(20), nullable=False)
userName = db.Column(db.String(15), primary_key=True, nullable=False)
password_hash = db.Column(db.String(20), nullable=False)
#property
def password(self):
return self.password
#password.setter
def password(self, plain_text_password):
self.password_hash = bcrypt.generate_password_hash(plain_text_password).decode('utf-8')
And views.py is
#app.route('/admin_login', methods=['GET', 'POST'])
def login_page():
login_form =Login()
if login_form.validate_on_submit():
attempted_password = login_form.pWord.data
attempted_user = User.query.filter_by(userName = login_form.uName.data).first()
print(f'Route Username is {login_form.uName.data}')
print(f'Route User is {attempted_user}')
print(f' Route Password is {attempted_password}')
print(f'Route Hashed Password is {attempted_user.password_hash}')
if attempted_user and bcrypt.check_password_hash(attempted_user.password_hash, attempted_password):
login_user(attempted_user)
flash(f'You have successfully logged in, {attempted_user.name}')
else:
flash('Invalid Username and Password')
return render_template('admin_login.html', loginForm=login_form)
And form.py is
class Login(FlaskForm):
uName = StringField(label='User Name')
pWord = PasswordField(label='Password')
submit = SubmitField(label='Login')
And password that are saved:
Hassed Password

You need to decode your data before storing the data
pw_hash = bcrypt.generate_password_hash(‘hunter2’).decode(‘utf-8’)
read the docs

Related

Cannot resolve keyword 'user' into field. Choices are: create_account, email, full_name

Im Created 2 Models.
Account
UserProfil
First Of All, User Register email, fullname, password1, password2. The data Sending To Database in table Account.
Second, User Will Login, if success, he will go to dashboard. in dashboard have a profil Form.
In The Profil Form, He Will input data profil, likes number phone, birth date. etc. and will store in table UserProfil
All of data in UserProfil relationship with Account.
Im Try to create 'Profil Form'. Like This.
my Question is How To Put the data Full_Name in this form ?
i got Error Cannot resolve keyword 'user' into field. Choices are: create_account, email, full_name ...
authentication/models.py
class Account(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
full_name = models.CharField(max_length=150)
create_account = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_reviewer = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name']
def __str__(self):
return self.full_name
dashboard/models.py
class UserProfil(models.Model):
jenis_kelamin_choice = (
('Pria', 'Pria'),
('Wanita', 'Wanita' ),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,)
nik = models.CharField(max_length=11, null=True, unique=True)
nidn = models.CharField(max_length=11, null=True, unique=True)
def __str__(self):
return str(self.user)
dashboard/views.py
class UserProfilFormView(CreateView):
template_name = 'dashboard/profil.html'
form_class = UserProfilForm
def form_valid(self, form):
userPofil = form.save(commit=False)
userPofil.user = Account.objects.get(user__full_name=self.request.user)
userPofil.save()
messages.success(self.request, 'Data Profil Berhasil Disimpan.')
print(self.request.user)
return super().form_valid(form)
File Traceback :
Internal Server Error: /dashboard/profil
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "D:\Project\hibahinternal\dashboard\views.py", line 26, in
form_valid
userPofil.user = Account.objects.get(user__full_name=self.request.user)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 424, in get
clone = self._chain() if self.query.combinator else self.filter(*args,
**kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 941, in filter
return self._filter_or_exclude(False, args, kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 961, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 968, in
_filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1393, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1286, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1112, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted,
self.get_meta())
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1539, in names_to_path
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'user' into
field. Choices are: create_account, email, full_name, groups, id,
is_active, is_admin, is_reviewer, is_staff, is_superuser, last_login,
logentry, password, user_permissions, userprofil
[20/Dec/2021 19:31:48] "POST /dashboard/profil HTTP/1.1" 500 136397
Thanks
Your Account has no user field, this also would not make much sense, since that is the user account. You do not need to make a query to the Account model anyway: request.user works with the user model, here account, so you can use request.user directly:
from django.contrib.auth.mixins import LoginRequiredMixin
class UserProfilFormView(LoginRequiredMixin, CreateView):
template_name = 'dashboard/profil.html'
form_class = UserProfilForm
def form_valid(self, form):
form.instance.user = request.user
messages.success(self.request, 'Data Profil Berhasil Disimpan.')
print(self.request.user)
return super().form_valid(form)
Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].

django NOT NULL constraint failed error

I am having an error in the form django.db.utils.IntegrityError: NOT NULL constraint failed:
in my app I ask the user to create a new project and then is ask via a form to add team member name mail.if the mail already exist in the database the user is invited to by mail to login to the app if the mail is not in the database the user is asked by mail to sign in. Then the invited member is added to the team.
I am getting that error when trying to assign an existing user in the data base
here is my code :
def TeamRegister2(request):
#import pdb; pdb.set_trace()
InviteFormSet = formset_factory(InviteForm2)
if request.method == 'POST':
formset = InviteFormSet(request.POST)
if(formset.is_valid()):
for i in formset:
mail = i.cleaned_data['Email']
if MyUser.objects.filter(email = mail).exists():
user = MyUser(email = mail)
u1 = user.id # get user ID
a1 = MyUser.objects.get(email = request.user.email) #get user email
a2 = Project.objects.filter(project_hr_admin = a1) #get all project created by the user
a3 = a2.latest('id') # extract the last project
a4 = a3.team_id # extract the team linked to the project
a4.members.add(u1) # add the member to the team
invited_user = MyUser.objects.get(email = mail)
current_site = get_current_site(request)
message = render_to_string('acc_join_email.html', {
'user': invited_user.first_name,
'domain':current_site.domain,
})
mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app'
to_email = mail
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
else:
user = MyUser(email = mail)
password = MyUser.objects.make_random_password()
user.set_password(password)
user.is_active = False
user.is_employee = True
user.save()
u1 = user.id #get user id
a1 = MyUser.objects.get(email = request.user.email) #get user email
a2 = Project.objects.filter(project_hr_admin = a1) #get all project created by the user
a3 = a2.latest('id') # extract the last project
a4 = a3.team_id # extract the team linked to the project
a4.members.add(u1) # add the member to the team
current_site = get_current_site(request)
message = render_to_string('acc_active_email.html', {
'user':user,
'domain':current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app'
to_email = user.email
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
messages.success(request, 'testouille la fripouille')
return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk':a3.id}))
else:
print("The entered form is not valid")
else:
formset = InviteFormSet()
return render(request,'team_register.html', {'formset':formset})
MyUser Model:
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=150, blank=True, null=True)
last_name = models.CharField(max_length=150, blank=True, null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_hr = models.BooleanField(default=False)
is_candidate = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
company = models.CharField(max_length=100, blank=True, null=True)
Team model:
class Team(models.Model):
team_name = models.CharField(max_length=100, default = '')
team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
members = models.ManyToManyField(MyUser, related_name="members")
def __str__(self):
return self.team_name
Project models:
class Project(models.Model):
name = models.CharField(max_length=250)
team_id = models.ForeignKey(Team, blank=True, null=True)
project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True)
candidat_answers = models.ManyToManyField('survey.response')
any idea how to fix that error and add the user to the team ?
thx you ;)
traceback:
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
328. return Database.Cursor.execute(self, query, params)
The above exception (NOT NULL constraint failed: website_team_members.myuser_id) was the direct cause of the following exception:
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/raphaelbendenoun/Documents/Django Projects/Authentication_project/registration/views.py" in TeamRegister2
85. a4.members.add(u1) # add the member to the team
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in add
934. self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in _add_items
1103. for obj_id in new_ids
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in bulk_create
443. ids = self._batched_insert(objs_without_pk, fields, batch_size)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in _batched_insert
1099. self._insert(item, fields=fields, using=self.db)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in _insert
1076. return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
1107. cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
80. return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/utils/six.py" in reraise
685. raise value.with_traceback(tb)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
328. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /registration/auth_team_register3/
Exception Value: NOT NULL constraint failed: website_team_members.myuser_id
You are trying to add an unsaved MyUser instance to the manytomany field. You have to get the object instead of creating a new object.
user = MyUser.objects.get(email=mail)
a4.members.add(user)

search using django filter

I am trying to perform search on name and email field.
For email field its giving an error "invalid literal for int() with base 10: 'abc#xyz.com'". but when I am using the user.id its giving correct result.
For name field, its giving Cannot resolve keyword 'first_name' into field.
How do i get it to work. Any help will be highly appreciated.
my two models are:
class publication(models.Model):
title = models.CharField(max_length=500)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
....
class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), max_length=254,
unique=True)
first_name = models.CharField(_('first name'), max_length=30,
blank=True)
last_name = models.CharField(_('last name'), max_length=30,
blank=True)
.....
My view:
def search(request):
result = publication.objects.all()
query = request.GET.get("query")
if query:
result = result.filter(
Q(title__icontains=query) |
Q(user__first_name__icontains=query) |
Q(user__email=query)
).distinct()
user_filter = UserFilter(request.GET, queryset=result)
return render(request, "search.html", {'filter': user_filter})
My filter:
class UserFilter(filters.FilterSet):
title = filters.CharFilter(lookup_expr='icontains')
first_name = filters.CharFilter(lookup_expr='iexact')
user = filters.CharFilter(lookup_expr='exact')
class Meta:
model = publication
fields = ['title', 'first_name', 'user']
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django_filters/views.py", line 66, in get
self.object_list = self.filterset.qs
File "/usr/local/lib/python2.7/dist-packages/django_filters/filterset.py", line 214, in qs
qs = filter_.filter(qs, value)
File "/usr/local/lib/python2.7/dist-packages/django_filters/filters.py", line 171, in filter
qs = self.get_method(qs)(**{'%s__%s' % (self.name, lookup): value})
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/query.py", line 781, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/query.py", line 799, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/sql/query.py", line 1260, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/sql/query.py", line 1286, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/sql/query.py", line 1216, in build_filter
condition = lookup_class(lhs, value)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/fields/related_lookups.py", line 110, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/fields/__init__.py", line 962, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'abc#xyz.com'
If you need to filter by relation model's field you can use name argument of filed class:
class UserFilter(filters.FilterSet):
title = filters.CharFilter(lookup_expr='icontains')
first_name = filters.CharFilter(name='user__first_name', lookup_expr='iexact')
user = filters.CharFilter(name='user__email', lookup_expr='exact')
See details here.
UPD
To filter full name try to implement custom method:
full_name = CharFilter(method='my_custom_filter')
def my_custom_filter(self, queryset, name, value):
first_name, last_name = value.split()
return queryset.filter(Q(user__first_name__icontains=first_name) | Q(user__last_name__icontains=last_name))
I use on my views.py for case search query on table blognews, for this code use for form post method search with name input keyword:
def list_content(request):
shelf = content.objects.all()
if(request.method=="POST"):
keyword=request.POST.get('keyword')
shelf=blogsnews.objects.filter(judul__icontains=keyword)
return render(request,'homepage/list_news.html',{'shelf':shelf})
for function filter "icontains or contains please visit docs django manual

Exception Type: ValidationError at /home Exception Value: [u"'1a3288b3-7588-483f-8e85-1affa952dbbf' value must be an integer."]

I have created registration page , model for it and when user gets registered he gets redirected to home page. When i click on register user is getting inserted in database but when it redirects to home page i am getting this error:
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\KR\Desktop\projects\project2\welcome\homeview.py" in home
14. if request.user.is_authenticated():
File "C:\Python27\lib\site-packages\django\utils\functional.py" in inner
234. self._setup()
File "C:\Python27\lib\site-packages\django\utils\functional.py" in _setup
380. self._wrapped = self._setupfunc()
File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in
24. request.user = SimpleLazyObject(lambda: get_user(request))
File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in get_user
12. request._cached_user = auth.get_user(request)
File "C:\Python27\lib\site-packages\django\contrib\auth__init__.py" in get_user
180. user_id = _get_user_session_key(request)
File "C:\Python27\lib\site-packages\django\contrib\auth__init__.py" in _get_user_session_key
59. return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
File "C:\Python27\lib\site-packages\django\db\models\fields__init__.py" in to_python
927. params={'value': value},
Exception Type: ValidationError at /home
Exception Value: [u"'1a3288b3-7588-483f-8e85-1affa952dbbf' value must be an integer."]
This is the model:
class user_model(AbstractBaseUser):
user_id = models.CharField(max_length=50, primary_key=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(max_length=50, default="None")
last_name = models.CharField(max_length=50, default="None")
email = models.EmailField(default="None")
password = models.CharField(max_length=150, default="abc123")
'''Custom user information fields. '''
myself = models.CharField(max_length=300, default="None")
address = models.CharField(max_length=300, default="None")
mobilePh = models.CharField(max_length=20, default="None")
workPh = models.CharField(max_length=20, default="None")
workEmail = models.EmailField(default="None")
last_login = models.CharField(max_length=50, default="None")
profile_pic = models.ImageField(width_field=None, height_field=None,
blank=True, default="None",
upload_to=upload_profile_pic)
banner_pic = models.ImageField(width_field=None, height_field=None,
blank=True, default="None",
upload_to=upload_banner_pic)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['user_id']
class Meta:
db_table = 'user_model'
app_label = 'welcome'
This is the register view
def register(request):
if request.method == 'POST':
if validate_registration_attributes(request.POST):
user_uuid = uuid.uuid4()
try:
user = User.objects.create(user_id=str(user_uuid), last_login=str(datetime.datetime.now()),
username=request.POST['username'],
first_name=request.POST['first_name'],
last_name=request.POST['last_name'],
email=request.POST['email'],
profile_pic="blank_image.png",
banner_pic="blank_image.png",
password='',
)
user.set_password(request.POST['passwd_1'])
user.save()
login(request, user)
return HttpResponseRedirect('/home')
except Exception as err:
user.delete()
print "Something happened"
raise Exception("""EXCEPTION at register-user.objects.create in
userObject:%s""" % (err))
global exceptmsg
return HttpResponseRedirect('/welcome')
else:
print "New account registration form validation failed"
context = {'RegisterResponse': exceptmsg}
return render(request, 'welcome.html', context)
This is the home view:
def home(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/home')
else:
return HttpResponseRedirect('/welcome')
Is it the problem with the model or anything else. Please help.
I had forgot to override the default user model in settings.py. I changed the value of AUTH_USER_MODEL to myappname.user_model. Now it works fine.

Flask Roles AttributeError: 'User' object has no attribute 'has_roles'

I am getting the error below. I think that for some reason my UserMixin import does not include the has_role property that #role_required requires. Do I need to use RoleMixin. Can anyone help?
Traceback (most recent call last):
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request
return view_func(**req.view_args)
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/flask_login.py", line 792, in decorated_view
return func(*args, **kwargs)
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/flask_user/decorators.py", line 69, in decorated_view
if not current_user.has_roles(*role_names):
File "/Users/henry.arnold/anaconda/lib/python3.5/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'User' object has no attribute 'has_roles'
My model
import datetime as dt
from flask_login import UserMixin
from flaskapp.database import Column, Model, SurrogatePK, db
from flaskapp.teams.models import Teams
class User(UserMixin, SurrogatePK, Model):
"""A user of the app."""
__tablename__ = 'users'
user_id = Column(db.BigInteger, unique=True, nullable=False)
first_name = Column(db.String(30), nullable=True)
last_name = Column(db.String(80), nullable=True)
email = Column(db.String(80), unique=True, nullable=False)
isaf_id = Column(db.String(10), nullable=True)
primary_team_id = Column(db.Integer, db.ForeignKey(Teams.id), nullable=True)
primary_team = db.relationship('Teams', foreign_keys='User.primary_team_id')
is_admin = Column(db.Boolean(), default=False)
created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
roles = db.relationship('Role', secondary='user_roles',
backref=db.backref('users', lazy='dynamic'))
def __init__(self, user_id=user_id, first_name=first_name, last_name=last_name, email=email, is_admin=is_admin, **kwargs):
"""if int(user_id) in current_app.config['ADMINS']:
self.is_admin = True
else:
self.is_admin = False"""
db.Model.__init__(self, user_id=user_id, first_name=first_name, last_name=last_name, email=email, is_admin=is_admin, **kwargs)
"""Create instance."""
#property
def full_name(self):
"""Full user name."""
return '{0} {1}'.format(self.first_name, self.last_name)
def __repr__(self):
"""Represent instance as a unique string."""
return '{0} {1}'.format(self.first_name, self.last_name)
# Define Role model
class Role(db.Model):
role_id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
# Define UserRoles model
class UserRoles(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('users.user_id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(), db.ForeignKey('role.role_id', ondelete='CASCADE'))
to create the user I do the following
#blueprint.route('/callback/<provider>')
def oauth_callback(provider):
if not current_user.is_anonymous:
return redirect(url_for('public.home'))
oauth = OAuthSignIn.get_provider(provider)
user_id, first_name, last_name, email, is_admin = oauth.callback()
if user_id is None:
flash('Authentication failed.')
return redirect(url_for('public.home'))
user = User.query.filter_by(user_id=user_id).first()
if not user:
User.create(user_id=user_id, first_name=first_name, last_name=last_name, email=email, is_admin = is_admin)
user = User.query.filter_by(user_id=user_id).first()
if is_admin:
print('is admin')
admin = Role.query.filter(Role.name == 'admin').first()
user.roles.append(admin)
User.query.filter_by(user_id=user_id).update({'is_admin': True})
else:
print('is not admin')
User.query.filter_by(user_id=user_id).update({'is_admin': False})
login_user(user, True)
db.session.commit()
return redirect(url_for('public.home'))
I think check the user is an admin
from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import current_user, login_required
from flask_user import roles_required
from flaskapp.events.forms import CreateEventForm
from flaskapp.events.models import Events
from flaskapp.database import db
from datetime import date
from collections import OrderedDict
#blueprint.route('/add_event', methods=['POST', 'GET'])
#login_required
#roles_required('admin')
def add_event():
UserMixin class from flask_login does not provide has_roles attribute (source). You can provide it by yourself in your User class:
class User(UserMixin, SurrogatePK, Model):
# ... Everything that you've written so far
def has_roles(self, *args):
return set(args).issubset({role.name for role in self.roles})
Also, you can use UserMixin class not from flask_login module, but from flask_user module (yes, there is a confusion in names). The latter class indeed does provide has_roles method. In this case all you need to do is change this line
from flask_login import UserMixin
to this:
from flask_user import UserMixin