Flask Many to Many relations get values - flask

I want to use many to many relationship in this scenario. I am trying make a compatible table. I don't know if this approch is okay or not. I can add data in os, python and ml table but not in associations table. How can I do it?? I want to add data in associations table and get data by query or anything from associations table.
Associations= db.Table('Associations',
db.Column('FKID_OS', db.Integer, db.ForeignKey('os.id'), primary_key=True),
db.Column('FKID_MLFRAMEWORK', db.Integer, db.ForeignKey('mlframework.id'), primary_key=True),
db.Column('FKID_PYTHON', db.Integer, db.ForeignKey('python.id'), primary_key=True)
)
class OS(db.Model):
__tablename__ = "os"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
def save(self):
db.session.add(self)
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
def update(self, data):
for key, val in data.items():
setattr(self, key, val)
db.session.commit()
def __repr__(self):
return f"<OS {self.id}>"
class MLFramework(db.Model):
__tablename__ = "mlframework"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
def save(self):
db.session.add(self)
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
def update(self, data):
for key, val in data.items():
setattr(self, key, val)
db.session.commit()
def __repr__(self):
return f"<MLFramework {self.id}>"
class Python(db.Model):
__tablename__ = "python"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
def save(self):
db.session.add(self)
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
def update(self, data):
for key, val in data.items():
setattr(self, key, val)
db.session.commit()
def __repr__(self):
return f"<Python {self.id}>"

Related

Django - how to use UpdateView modelform with custom field?

I would like to use a custom form field with an UpdateView. My code so far is:
models.py
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
paper = models.BooleanField(default=False)
pronouns = models.CharField(max_length=50, blank=True)
def __str__(self):
return self.username
forms.py
class CustomUserProfileForm(forms.ModelForm):
pronouns = forms.CharField(label='Pronouns', required=True)
class Meta:
model = get_user_model()
fields = ('first_name', 'last_name')
def __init__(self, *args, **kwargs):
_pronoun_list = ('he/him/his', 'she/her/hers', 'they/them/theirs')
super(CustomUserProfileForm, self).__init__(*args, **kwargs)
self.fields['pronouns'].widget = ListTextWidget(
data_list=_pronoun_list, name='pronoun-list')
This form references ListTextWidget although I don't think it directly relates to my issue:
class ListTextWidget(forms.TextInput):
def __init__(self, data_list, name, *args, **kwargs):
super(ListTextWidget, self).__init__(*args, **kwargs)
self._name = name
self._list = data_list
self.attrs.update({'list': 'list__%s' % self._name})
def render(self, name, value, attrs=None, renderer=None):
text_html = super(ListTextWidget, self).render(
name, value, attrs=attrs)
data_list = '<datalist id="list__%s">' % self._name
for item in self._list:
data_list += '<option value="%s">' % item
data_list += '</datalist>'
return (text_html + data_list)
Views.py
class CustomUserProfileview(UpdateView):
model = CustomUser
form_class = CustomUserProfileForm
template_name = 'account/customuser_change_form.html'
success_url = reverse_lazy('home')
def form_valid(self, form):
user = self.request.user
pronouns = form.cleaned_data['pronouns']
user.pronouns = pronouns
user.save()
return super().form_valid(form)
The form is displayed as I would expect, where I can change the first name, last name and choose pronouns from a list. If I print(user) and print(pronouns) I get my expected results, but the pronouns field is not being saved to the user. Even if it did save, I get the feeling that I'm not leveraging the UpdateView correctly.

(1048, "Column 'user_id' cannot be null") with Django DRF

I wrote code to create new users via POST and DRF (Django Rest Framework) successfully and I can obtain token correctly, however when I try to POST (via DRF) to fill Profile linked to that user I get
(1048, "Column 'user_id' cannot be null")
This is snippets of my code:
for serializers:
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = ('username','email','first_name','last_name','password')
def create(self, *args, **kwargs):
user = super().create(*args, **kwargs)
p = user.password
user.set_password(p)
user.save()
return user
def update(self, *args, **kwargs):
user = super().update(*args, **kwargs)
p = user.password
user.set_password(p)
user.save()
return user
class ProfileSerializer(ModelSerializer):
class Meta:
model = Profile
fields = ('bio','birth_date','location','country')
def create(self, *args, **kwargs):
profile = super().create(*args, **kwargs)
profile.save()
return profile
def update(self, *args, **kwargs):
profile = super().update(*args, **kwargs)
profile.save()
return profile
and for views:
class ProfileViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
permission_classes = IsAuthenticated,
serializer_class = ProfileSerializer
queryset = Profile.objects.all()
class UserViewSet(viewsets.GenericViewSet,mixins.CreateModelMixin,):
"""
API endpoint that allows users to be viewed or edited.
"""
#permission_classes= (IsAdminUser,)
serializer_class = UserSerializer
queryset = User.objects.all().order_by('-date_joined')
and for models:
#receiver(post_save, sender = settings.AUTH_USER_MODEL)
def create_auth_token(sender,instance=None,created=False, **kwargs):
if created:
Token.objects.create(user=instance)
class Country(models.Model):
iso = models.CharField(max_length = 2,unique = True)
name = models.CharField(max_length = 250)
iso3 = models.CharField(max_length = 6)
phonecode = models.CharField(max_length=6)
def __unicode__(self):
return '%s' % self.name
def __str__(self):
return '%s' % self.name
class Profile(models.Model):
#user = models.OneToOneField(User, on_delete=models.CASCADE,default = "")
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default = "")
bio = models.TextField(max_length=100, blank=True)
birth_date = models.DateField(null=True, blank=True)
location = models.CharField(max_length=254, blank=True)
country = models.ForeignKey(Country,on_delete=models.CASCADE,blank=True,null=True)
def __unicode__(self):
return '%s' % self.user
def __str__(self):
return '%s' % self.user
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
When I try with Postman and I pass a token for token authentication, it recognize the token correctly but I get this error:
(1048, "Column 'user_id' cannot be null") with Django DRF
I appreciate your help to solve this problem
Create() save to the database, so you need to set profile.user_id before calling the function.

Flask-login:AttributeError: 'User' object has no attribute 'is_active'

I'm following Corey Schafer's tutorial and w
henever I submit my login details, I keep getting the error
AttributeError: 'User' object has no attribute 'is_active'
The registration works fine though
\\
#app.route("/login", methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
return redirect(url_for('main'))
else:
flash('Login Unsuccessful check again')
return render_template('login.html', title='Login', form=form)
\\
\\
from datetime import datetime
from main import db, login_manager
from flask_login import UserMixin
#login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False,
default='default.jpg')
password = db.Column(db.String(60), nullable=False)
posts = db.relationship('Post', backref='author', lazy=True)
def is_active(self):
return True
def __repr__(self):
return f"User('{self.username}', '{self.email}', '{self.image_file}')"
\\
That's because you need to add a column is_active in your User model. For example:
is_active= db.Column(db.Boolean, default=True, nullable=False)

Catching some values in django signals

I'm using django signals to catching some values. My example:
#receiver(post_save, sender=Profile)
def my_example(sender, instance, created, **kwargs):
if created:
user_id = instance.user.id
level = instance.is_admin
company = instance.company
I need to catch user_id, level and company. But only user_id contains value. company value is always None and level is always False.
This is my basic model for profile:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
is_supervisor = models.BooleanField("Supervisor", default=False)
is_admin = models.BooleanField("Admin", default=False)
company = models.ForeignKey(
"core.company",
related_name="users",
on_delete=models.CASCADE,
blank=True,
null=True,
)
def __str__(self):
"""Unicode representation of MyUser."""
return self.user
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
And a simple test to pass values:
def test_example:
company = Company.objects.create(name="company1")
user_test = User.objects.create(username="user_test")
user_test.profile.company = company
user_test.profile.is_admin = True
user_test.profile.save()
user_test.save()
And the result:
user_id = user_test
company = None
level = False

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

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)