AttributeError: 'User' object has no attribute 'is_active' - flask

I try to run my app for login But when I submit the form to check the user id and email I got this error.AttributeError: 'User' object has no attribute 'is_active' So Thanks if you help
rv = self.dispatch_request()
File "/home/peg/flask/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/peg/flask/app/view.py", line 45, in login
login_user(user_in_db, remember = form.remember_me.data)
File "/home/peg/flask/venv/lib/python2.7/site-packages/flask_login.py", line 675, in login_user
if not force and not user.is_active():
view.py
#app.route('/login', methods = ['GET', 'POST'])
def login():
form = LoginForm()
#checks if the user is authernticated
#or not, if yes it skips authentfic.
if current_user is not None and current_user.is_authenticated():
return redirect(request.args.get('next') or url_for('index'))
#does not allow user to use get method
if request.method == 'GET':
return render_template('login.html',
form = form,
title = 'Login')
#taking the user submitted data and checking if it exists in the database
user_in_db = User.query.filter_by(name=form.name.data.lower()).first()
#if the username is not wrong
if user_in_db is not None and user_in_db != False:
if form.email.data != user_in_db.email:
flash('email is incorrect')
return redirect(url_for('login'))
#here I got error
login_user(user_in_db, remember = form.remember_me.data)
return redirect(request.args.get('next') or url_for('index'))
else:
flash('Username does not exists')
return render_template('login.html',
form = form,
title = 'Login')
model.py
class User(db.Model):
__tablename__ = "Contacts"
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(50))
email = db.Column(db.String(50))
age = db.Column(db.Integer)
def __init__(self, name, email, age ):
self.name = name
self.email = email
self.age = age
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<User %r>' %(self.name)

Your indentation is wrong. Instead of defining methods on User, you've defined module-level functions.
class User(db.Model):
__tablename__ = "Contacts"
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(50))
email = db.Column(db.String(50))
age = db.Column(db.Integer)
def __init__(self, name, email, age ):
self.name = name
self.email = email
self.age = age
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<User %r>' %(self.name)

You need to have your model class inherit from UserMixin
from flask_login import UserMixin
class User(db.Model, UserMixin):
__tablename__ = "Contacts"
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(50))
email = db.Column(db.String(50))
age = db.Column(db.Integer)

Related

Handling form fields in django for logged in user

Im trying to handle the existing name of a Category, so that users wont be allowed to create 2 categories with the same name, but at the moment its taking all categories from the database, not only for the logged-in user. I dont know how and where to implement request.user.
I`m building an inventory app where everyone creates their own categories and adds items.
Thank you.
This is my model:
class Category(models.Model):
user = models.ForeignKey(User, default=1, on_delete=models.CASCADE,
related_name='category', null=True)
name = models.CharField(max_length=100, null=False, blank=False)
slug = models.SlugField(max_length=100)
created_on = models.DateTimeField(auto_now_add=True)
timestamp = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-timestamp']
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('category_detail', kwargs={'slug': self.slug})
This is my form:
class CategoryForm(forms.ModelForm):
add_category = forms.BooleanField(widget=forms.HiddenInput, initial=True)
class Meta:
model = Category
fields = ['name']
def clean_name(self):
name = self.cleaned_data.get('name')
if (name == ""):
raise forms.ValidationError('This field cannot be left blank')
for instance in Category.objects.all():
if instance.name == name:
raise forms.ValidationError('There is a category with the name ' + name)
return name
This is my view:
#login_required
def index(request):
categories = Category.objects.filter(user=request.user)
items = Item.objects.all()
add_item = ItemForm()
add_category = CategoryForm()
query = None
if request.method == 'POST':
if 'add_item' in request.POST:
add_item = ItemForm(request.POST)
if add_item.is_valid():
form = add_item.save(commit=False)
form.category = get_object_or_404(
Category, name=request.POST.get('category'),
user=request.user)
add_item.save()
return redirect('home')
else:
add_category = CategoryForm(request.POST)
if add_category.is_valid():
category_form = add_category.save(commit=False)
category_form.save()
messages.success(request, f'{name} has been added')
return redirect('home')
Edit Category View
#login_required
def category_edit(request, pk):
category = Category.objects.get(id=pk)
if request.method == 'POST':
form = CategoryForm(request.POST, instance=category)
if form.is_valid():
form.save()
messages.info(request, f'{category.name} has been updated!')
return redirect('home')
else:
form = CategoryForm(instance=category, user=request.user)
context = {
'form': form,
}
return render(request, 'category_edit.html', context)
Ive tried adding user = request.user in the form class, but that resulted in an error Ive tried adding category_form.user = request.user before saving the form but that was still taking names from every other user
Pass the request's user to the form:
class CategoryForm(forms.ModelForm):
add_category = forms.BooleanField(widget=forms.HiddenInput, initial=True)
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
class Meta:
model = Category
fields = ['name']
def clean_name(self):
name = self.cleaned_data.get('name')
if (name == ""):
raise forms.ValidationError('This field cannot be left blank')
qs = Category.objects.filter(user=self.user, name=name)
if self.instance.pk:
# EXCLUDE CURRENT INSTANCE TO ENABLE EDIT
qs = qs.exclude(pk=self.instance.pk)
if qs.exists():
raise forms.ValidationError('There is a category with the name ' + name)
return name
then in the view you need to pass the user:
#login_required
def index(request):
categories = Category.objects.filter(user=request.user)
items = Item.objects.all()
add_item = ItemForm()
add_category = CategoryForm(user=request.user)
query = None
if request.method == 'POST':
if 'add_item' in request.POST:
add_item = ItemForm(request.POST)
if add_item.is_valid():
form = add_item.save(commit=False)
form.category = get_object_or_404(
Category, name=request.POST.get('category'),
user=request.user)
add_item.save()
return redirect('home')
else:
add_category = CategoryForm(user=request.user, data=request.POST)
if add_category.is_valid():
category_form = add_category.save(commit=False)
category_form.save()
messages.success(request, f'{name} has been added')
return redirect('home')

Need to search user based on email and then deactivate his profile

I am trying to create a search form, Where admin can search users and then deactivate their profiles, if it is the right account.
tried function based views and then class based views. It shows the profile in function based views but doesn't update it. and in class based view it wouldn't even show the profile.
models.py
class User(AbstractBaseUser):
objects = UserManager()
email = models.EmailField(verbose_name='email address', max_length=255, unique=True,)
type = models.CharField(max_length = 50, choices = type_choices)
name = models.CharField(max_length = 100)
department = models.CharField(max_length = 100, null = True, blank = True, choices = department_choices)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a superuser
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['type']
forms.py
class SearchForm(forms.Form):
email = forms.EmailField(required=True)
views.py
#method_decorator(login_required, name='dispatch')
class adminDeleteProfileView(LoginRequiredMixin, View):
def render(self, request):
return render(request, 'admin/view_account.html', {'form': self.form})
def form_valid(self, form):
self.form = SearchForm(request.POST)
print('im here', form.cleaned_data.get('email'))
User.objects.filter(email = form.cleaned_data.get('email')).update(active = False)
#print('Donot come here')
def get(self, request):
self.form = SearchForm()
return self.render(request)
#login_required
def admin_deactivate_profile_view(request):
error_text = ''
if request.method == 'POST':
print('here')
user_email = request.POST.get('email')
try:
print('Deactivating',user_email, 'Account.')
profile = User.objects.filter(email = user_email).first()
if request.POST.get('delete'):
User.objects.filter(email = user_email).update(active = False)
messages.success(self.request, 'Profile Updated!')
except Exception as e:
print(e)
messages.success(self.request, 'There was an error!')
return render(request, "admin/delete_profile.html", {'profile':profile})
simple query .
user=User.objects.get(email="user#email.com")
user.activate=false
user.save()

sqlalchemy.orm.exc.UnmappedInstanceError: Class '__main__.User' is not mapped on Flask-SQLAlchemy

I just got a problem when implementing Flask-SQLAlchemy to my Flask-Restplus. It consistently show an error:
sqlalchemy.orm.exc.UnmappedInstanceError: Class '__main__.User' is not mapped
The code I've written below is the simplified version (1 file) of the Flask-Restplus example project on github: https://github.com/postrational/rest_api_demo
I've checked again and again, but have no idea why the error still appears.
Here is my code:
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_restplus import Resource, Api, fields
app = Flask(__name__)
api = Api(app, version='v0.1')
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
ns = api.namespace('users', description='User API')
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(80))
password = db.Column(db.String(80))
def __init__(self, email, password):
self.email = email
self.password = password
def __repr__(self):
return '<User %s>' % self.email
user = api.model('user', {
"id": fields.Integer(readOnly=True),
"email": fields.String(required=True),
"password": fields.String(required=True),
})
def create_user(data):
email = data.get('email')
password = data.get('password')
user = User(email, password)
db.session.add(user)
db.session.commit()
def update_user(user_id, data):
user = User.query.filter(User.id == user_id).first()
user.email = data.get('email')
user.password = data.get('password')
db.session.add(user)
db.session.commit()
def delete_user(user_id):
user = User.query.filter(User.id == user_id).first()
db.session.delete(user)
db.session.commit()
#ns.route('/')
class UserList(Resource):
#ns.marshal_list_with(user)
def get(self):
users = User.query.all()
return users
#ns.marshal_with(user)
#ns.expect(user)
def post(self):
data = request.json
create_user(data)
return None, 201
#ns.route('/<int:id>')
class User(Resource):
#ns.marshal_with(user)
def get(self, id):
user = User.query.filter(User.id == id).first()
return user
#ns.expect(user)
#ns.marshal_with(user)
def put(self, id):
data = request.json
user = update_user(id, data)
return None, 204
def delete(self, id):
delete_user(id)
return None, 204
db.create_all()
user = User(email= 'saffsds#gmail.com', password= '4324dsfdsfa')
db.session.add(user)
db.session.commit()
user = User(email= 'sdfsdf#gmail.com', password= '5435rs')
db.session.add(user)
db.session.commit()
users = User.query.all()
print users
if __name__ == "__main__":
app.run(debug=True)
Is there anything I missed on the code? I use python2.7 anyway..
im pretty sure its because you are overloading User.__init__, but you didnt call super, so do this and see if it maps:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(80))
password = db.Column(db.String(80))
def __init__(self, email, password):
self.email = email
self.password = password
super(User,self).__init__()
def __repr__(self):
return '<User %s>' % self.email

what causes the weird "UNIQUE constraint failed: auth_user.username" error?

I try to insert data in user model into other model by one to one relationship. In specific, I want insert username,email and password attributes of User into other models.In Addtional, I intend to create both User model and other model in one form. So, I override the save method in modelform. It works partially and be able to insert data in both models and databases, except throw a UNIQUE constraint failed: auth_user.username error.
In models.py
class Staff(models.Model):
yes_or_no = ((True, 'Yes'),(False, 'No'))
male_or_female = ((True,'Male'),(False,'Female'))
user = models.OneToOneField(User, unique=True)
gender = models.BooleanField(default = True, choices = male_or_female)
birthday = models.DateField(default =None,blank = False, null = False)
created = models.DateTimeField(default=datetime.now, blank=True)
authorized = models.BooleanField(default=False,choices = yes_or_no)
store_id = models.ForeignKey(Store,default=1)
#property
def name(self):
return self.user.username
#property
def email(self):
return self.user.email
#property
def password(self):
return self.user.password
#property
def first_name(self):
return self.user.first_name
#property
def last_name(self):
return self.user.last_name
def __str__(self):
return self.user.username
In forms.py
class StaffForm(forms.ModelForm):
name = forms.CharField(max_length=100)
email= forms.EmailField(max_length=100, required=True)
password = forms.CharField(max_length=50)
store_id = forms.ModelChoiceField(queryset = Store.objects.all(),empty_label="--------") # select values ?
first_name = forms.CharField(required = True,max_length=100)
last_name = forms.CharField(required = True,max_length=100)
class Meta:
model = Staff
fields = ('gender','birthday','authorized','store_id')
widgets = {'authorized':forms.RadioSelect,
'gender':forms.RadioSelect,
'birthday':SelectDateWidget(years=range(date.today().year-50,date.today().year))
}
def save(self,*args,**kwargs):
Staff = super(StaffForm,self).save(commit=False)
user = User.objects.create(
username=self.cleaned_data['name'],
first_name=self.cleaned_data['first_name'],
last_name = self.cleaned_data['last_name'],
email= self.cleaned_data['email'])
user.set_password(self.cleaned_data['password'])
if self.cleaned_data['authorized']:
user.is_staff = True
Staff.user = user
Staff.save()
In views.py
#login_required(login_url='/dataInfo/login/')
def createstaff(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = StaffForm(request.POST or None)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
form.save()
return HttpResponseRedirect('/dataInfo/staff_view/')
# if a GET (or any other method) we'll create a blank form
else:
form = StaffForm()
return render(request, 'dataInfo/create_staff.html', {'form': form})

django customuser matching query does not exist

I think it originates in this view, since it's being transfered to the home view (see below):
#login_required
def HomePage(request):
if request.user.get_profile().phone == "":
return HttpResponseRedirect('/phone')
else:
add_list = add.objects.all()
ctx = {'last_login':request.session.get('social_auth_login_backend')}
return render_to_response("homepage.html", {'add_list': add_list, 'ctx':ctx}, context_instance=RequestContext(request))
And the model:
class customuser(models.Model):
last_login = models.DateTimeField(blank=True, null=True)
is_active = models.BooleanField()
nickname = models.CharField(max_length=255)
regdate = models.DateField(auto_now=True)
phone = models.CharField(max_length=255)
user = models.OneToOneField(User)
city = models.ForeignKey(locations, null=True)
def __str__(self):
return "%s user " % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = customuser.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
class Admin:
pass
I'm not sure if this is the cause of you're problem, but the context dictionary that you're passing to your template looks wrong. The view should probably be re-written -
def HomePage(request):
if request.user.get_profile().phone == "":
return HttpResponseRedirect('/phone')
else:
ctx = {'last_login':request.session.get('social_auth_login_backend'),
'add_list': add.objects.all()}
return render(request, "homepage.html", ctx)