Creating view for update table via foregien key access in django - postgresql

I am really new to django and stuck in using foreign key in django queries.Can anyone help me.
Situation:I created a sign up page with username and email field.So when a new user registered, its username and email address saved to auth_user table.
Q: I want to create a model instance in class UserDetails each time a new user register. or you can say entry of user as a foregien key in table userdetails. I am using postgresql database.
Myapp/models.py
class Pincode(models.Model):
pincode = models.CharField("PinCode",null=False)
geom = GeopositionField("Location")
objects = models.GeoManager()
def __unicode__(self):
return u'%s' %(self.pincode)
class UserDetails(models.Model):
user = models.OneToOneField(User, related_name='User_Details',unique=True)
pin= models.ForeignKey(Pincode,related_name='pin', null= True, blank=True)
rating= models.CharField(max_length=12, null=True, blank=True)
def __unicode__(self):
return u'%s, %s, %s' % (self.user, self.pin, self.rating)
views.py
def index(request):
update_user_details()
return render_to_response("larb/index.html",
RequestContext(request))
def update_user_details(request): ## **Stuck here**
user_details = UserDetails.objects.all()
new_entry= User.objects.exclude() # Don't know how to do
currently i am thinking of creating a function in the views that update the table.
first it checks for new entries means entries in auth_user which are not in userdetails table. If found update userdetails table.

I hope i solved it and it's seems fine now:
Here is views.py code
def index(request):
update_user_details()
return render_to_response("larb/index.html",
RequestContext(request))
def update_user_details():
id_past_entries = UserDetails.objects.all().values_list('user_id', flat = True)
new_entries = User.objects.exclude(id__in=id_past_entries)
if new_entries:
for new_id in new_entries:
new = User.objects.get(id=new_id)
UserDetails.objects.create(user=new)
UserDetails.save()

Related

How to give users a user role based on their email in Python?

I'm creating a registration page which contains 3 input fields: name, email, password. In my User model class, I've created a user_role method:
from models.base_model import BaseModel
from flask_login import UserMixin
import peewee as pw
class Users(BaseModel, UserMixin):
name = pw.CharField(max_length=100, unique=True)
email = pw.CharField(max_length=100, unique=True)
password = pw.CharField()
role = pw.CharField(max_length=50)
def __init__(self, name, email, password):
self.name = name
self.email = email
self.password = password
def __repr__(self):
return f"User: {self.name}, {self.email}, {self.role}"
def user_roles(self):
user_email = self.email
self.roles = ["user","admin"]
check_email = ["test#testing.com"]
if user_email == check_email:
return self.roles == "admin"
else:
return self.roles == "user"
The check_email is use to check if the email that a user fill in the field is equal to the check_email value. If it does, the role should be assign as 'admin'. In my route file, this is what it look like when saving to the database:
if form.validate_on_submit():
name = form.name.data
email = form.email.data
raw_password = form.password.data
password = generate_password_hash(raw_password, method="sha256", salt_length=20)
role = Users.user_roles(email)
new_user = Users(name=name, email=email, password=password, role=role)
Now when I tried to test out the registration form, this is the error it gave me:
I want to know is there a way to fix this error?
PS: I'm doing this for testing purposes to see if I could assign user role. I would probably add more user roles in the future, so I don't think Flask-Admin could help me
You have your user_roles method defined as a class method when it can and should probably be a static method. Also you are calling user_roles with the email string but the try to access self.email in the method. Just change that and you are good to go.
def get_role(email):
check_email = "test#testing.com"
if email == check_email:
return "admin"
else:
return "user"
Edit: Forgot to remove brackets as we don't want an array but just the string.

How do I explicitly specify language of email I want to send?

I have a custom user model that have a preferred_language field. I want all the emails (activation and password reset) to be sent translated to the language that user specified in profile.
class CustomUser(AbstractBaseUser, PermissionsMixin):
...
LANGUAGE_CHOICES = (
(1, "English"),
(2, "Русский")
)
preferred_language = models.PositiveSmallIntegerField(choices=LANGUAGE_CHOICES, default=2,
verbose_name=_("Preferred language"))
I thought about setting custom email class but didn't saw in navive djoser's classes any points where I could explicitly set the language of outcome emails despite of ready-to-be-translated style of email templates:
class ActivationEmail(BaseEmailMessage):
template_name = 'email/activation.html'
def get_context_data(self):
context = super(ActivationEmail, self).get_context_data()
user = context.get('user')
context['uid'] = utils.encode_uid(user.pk)
context['token'] = default_token_generator.make_token(user)
context['url'] = settings.ACTIVATION_URL.format(**context)
return context
Reset password view (which's refference is settings.EMAIL.activation used in ActivationEmail class above):
class ResetPassword(ActionViewMixin, generics.GenericAPIView):
...
def send_password_reset_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
settings.EMAIL.password_reset(self.request, context).send(to)
def send_activation_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
settings.EMAIL.activation(self.request, context).send(to)
In your case I would use the override context manager that stores the current language on enter (in order to sent the email) and restores it on exit.
from django.utils import translation
def send_password_reset_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
lang_code = user.lang_code # retrieve user's language code here
with translation.override(lang_code):
settings.EMAIL.password_reset(self.request, context).send(to)
def send_activation_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
lang_code = user.lang_code # retrieve user's language code here
with translation.override(lang_code):
settings.EMAIL.activation(self.request, context).send(to)

Associate a product to a record in own custom module

I'm new to odoo , i want to create a new product in the product module when a new record is created in my own custom module! how can i achieve this goal !?
by the way i'm using odoo v12
Override create method of your custom model and created product in it.
#api.model
def create(self, vals):
res = super(YouClassName, self).create(vals)
self.env['product.product'].create({'name': 'Product1'})
return res
Here is my create function :
#api.model
def create(self, vals):
res = super(GroupsalesGroupsales, self).create(vals)
main_category = self.env['product.category'].search([])
if main_category:
main_category = main_category[0]
self.env['product.template'].create({'name': vals['name'],
'categ_id': main_category.id,
'list_price':vals['prix_rabais'],
'default_code': 'GS-PROD',
'image_small' : vals['image_small'], })
return res
When i try to add _inherits: {'product.product': 'product_id'}
i get this error:
'ERROR:null value in column "name" violates not-null constraint'

Mongoengine and add_to_set doesn't seem to be working

I'm trying to save references to mp3's to a database. I'm saving artist, song, and album to their own respective schemas and referencing between them via ReferenceFields.
I'm using eyeD3 to parse id3 data, if there is any, and save that to the database. My problem is that I want to save all three schema types at the same time but I might going about it the wrong way. I'm using python 2.7.10.
example schema:
class Artist(db.Document):
"""Schema for Artist"""
name = db.StringField(max_length=255, required=True, unique=True)
albums = db.ListField(db.ReferenceField('Album'))
songs = db.ListField(db.ReferenceField('Song'))
def __unicode__(self):
return self.name
class Album(db.Document):
"""Schema for albums"""
title = db.StringField(max_length=255, required=True, unique=True)
artist = db.ReferenceField(Artist)
songs = db.ListField(db.ReferenceField('Song'))
def __unicode__(self):
return self.title
class Song(db.Document):
"""Schema for songs"""
title = db.StringField(max_length=255, required=True, unique=True)
artist = db.ReferenceField(Artist)
album = db.ReferenceField(Album)
path = db.StringField(max_length=255, required=True)
def __unicode__(self):
return self.title
and the code to save to db:
for root, dirs, files in os.walk(dir):
for f in files:
if '.mp3' in f:
id3 = eyed3.load(os.path.join(root, f))
song = Song(title=id3.tag.title, path=os.path.join(root, f))
album = Album(title=id3.tag.album)
artist = Artist(name=id3.tag.artist)
song.save()
album.save()
artist.save()
Artist.objects(id=artist.id).update(add_to_set__albums=album, add_to_set__songs=song)
Album.objects(id=album.id).update(artist=artist, add_to_set__songs=song)
Song.objects(id=song.id).update(artist=artist, album=album)
After saving, add_to_set is only saving one object to each ListField instead of pushing it on to the end.
I'm having a hard time figuring out how to do this correctly. Any help would be appreciated. Thanks
Ok so I found the culprit. Because some attributes of the schema are unique, when I assign an object to a variable that is already inserted into the db:
artist = Artist(name=id3.artist)
it returns a dulpicate error. Then I try to use that variable to push to another object:
Album.objects(title=id3.album).update(artist=artist)
but that variable is not set due to the duplicate error.
Here is my refactored code using upserts:
Song.objects(title=song.tag.title).update(path=path, upsert=True)
so = Song.objects.get(title=song.tag.title)
Album.objects(title=song.tag.album).update(add_to_set__songs=so, upsert=True)
al = Album.objects.get(title=song.tag.album)
Artist.objects(name=song.tag.artist).update(add_to_set__songs=so, add_to_set__albums=al, upsert=True)
ar = Artist.objects.get(name=song.tag.artist)
so.update(artist=ar, album=al)
al.update(artist=ar, add_to_set__songs=so)

How can I insert and get PK Id using Entity Framework?

currently I'm Inserting like:
MyNamedEntities db = new MyNamedEntities();
MyTableEntity field = new MyTableEntity();
field.Name = "me";
db.MyTableEntity.AddObject(field);
db.SaveChanges()
But now I want to insert child elements and I need that field.Id part
MyOtherTableEntity field = new MyOtherTableEntity();
field.TableId = new MyTableEntity.First(x => x.Id.Equals( ... ));
How can I get the field.Id ?
If your table has defined the Id as an INT IDENTITY column, then you don't really have to do anything at all! :-)
In that case, just insert your entity and after the call to .SaveChanges(), your object should contain the new Id value:
MyTableEntity field = new MyTableEntity();
field.Name = "me";
db.MyTableEntity.AddObject(field);
db.SaveChanges();
int newID = field.Id;
You can also just add them to the parent by the association before or after the save changes
Something like this.
address a = new address();
a.city = "Detroit";
field.address.add(a);
db.SaveChanges();