Im trying to save value to a textfield in django with a celery task, but if the textfield has a value, I want to append the new value to the old value.
Here is my model:
class Profile(models.Model):
username = models.CharField(max_length=200)
info = models.TextField(blank=True)
Here is what I have tried:
#shared_task
def update_profile(data, profile_username):
#Get the profile
profile = Profile.objects.get(username=profile_username) #(WORKING)
#Check if info is in dataset
if 'info' in data: #(WORKING)
#Check if there is an old value
if profile.info: #(WORKING)
#Old value found
old_info = profile.info
#Append old and new value
new_info = '{}\n{}'format(old_info, data['info'])
profile.info = new_info
else:
#No old value fond, save the new value
profile.info = data['info'] #(WORKING)
#Save profile
profile.save() #(WORKING)
If the field does not have an old value, I can save the new value just fine, but when I try save the old and new value together, I will not work! I can only save one of them, not "update" the field like I want to.
Edit:
I see now that new_info = '{}\n{}'format(old_info, data['info']) is working, but I get this error : UnicodeEncodeError('ascii', u'Test\xf8', 128, 129, 'ordinal not in range(128)')
You need to simplify the loop, so that you can debug it correctly. Use get (a method of dictionaries) to fetch the key, and you can assign it a default value if the key doesn't exist.
Putting this together, your code now is:
def update_profile(data, profile_username):
profile = Profile.objects.get(username=profile_username) #(WORKING)
profile.info = u'{}\n{}'.format(profile.info, data.get('info', '').encode('utf-8'))
profile.save()
Related
I am not that familiar with Python and SQLAlchemy so please be patient :)
I need to capture if, within a FORM that holds multiple ICONS(files), one or more ICONS have been changed when editing the record.
To see which ICONS have been changed I created an Object holding the changes with "Database Model Name" as the "Key" and its "Value"
{'icon': <FileStorage: 'fire.png' ('image/png')>}
key = used as database model name
value = file.filename
now when I try the get the data within a for loop and add this data to the Database model, nothing happens and it looks like I am not really accessing variable "k" in the loop.
for k, v in notequalat.items():
responseteamdata.k = v.filename
My question is, how can I combine the Database model class "responseteamdata" and the variable "k" so that I can add the changes to the database model dynamically.
here is the full code:
if not notequalat:
try:
responseteamdata.title = title
responseteamdata.abbreviation = abbreviation
responseteamdata.isfireteam = booleanisfireteam
responseteamdata.iconposition = newlatlng
db.session.commit()
except IntegrityError:
db.session.rollback()
db.session.close()
res = make_response(jsonify("message ", "Error Updating the Team"), 500)
return res
else:
responseteamdata.title = title
responseteamdata.abbreviation = abbreviation
responseteamdata.isfireteam = booleanisfireteam
responseteamdata.iconposition = newlatlng
for k, v in notequalat.items():
responseteamdata.k = v.filename
db.session.commit()
dbevent = "updated"
db.session.close()
To be able to dynamically assign the Table Column Name the following command has been working for me:
setattr(DB-Object, ColumnName, Value)
which means in my case:
setattr(responseteamdata, k, v.filename)
Hay I am new to Odoo Customizing and Python and wanted to know how I can iterate through a field and take the values out of the field and put them in a new one.
The field I want to iterate through contains multiple email adresses. I want to iterate through these email adress fields, collect the email adresses and store them together in a new field.
For that I need a function.
The field I want to iterate through:
My One2many field contains multiple mail adresses which I want to iterate through and collect.
field_contacts_customer_info = fields.One2many(
'contacts.customer.information', 'another_id', string='Contacts for customer information')
The field I want to store the collected email adresses in:
selected_email = fields.Char(compute='compute_email')
This is my class:
I want to collect all the email adresses from the mail_contacts field.
_name = 'contacts.customer.information'
_rec_name = 'name_contacts'
name_contacts = fields.Many2one(
'res.partner', string="Person", domain = [('is_company', '=', False)])
mail_contacts = fields.Char(
related = 'name_contacts.email' ,string="Email")
another_id = fields.Many2one('res.partner', string="AnotherID")
My Try: This function collects only the last set record of the field_contacts_customer_info field and puts this record in the selected_email field of every company.So it does not work right. It should collect all the mails of the field_contacts_customer_info field for every company seperated and then put them in the selected_mail field of the belonging company.
#api.onchange('field_contacts_customer_info.mail_contacts')
def compute_email(self):
list_email = []
for record in self:
if record.is_company:
for element in record.field_contacts_customer_info:
if element.name_contacts:
list_email.append(element.mail_contacts)
for email in list_email:
self.selected_email = email
Thanks.
You need to iterate over self which is a record set and loop over field_contacts_customer_info field to get mail_contacts field values.
#api.depends('field_contacts_customer_info.mail_contacts')
def get_email(self):
for record in self:
record.selected_email = ','.join(info.mail_contacts for info in record.field_contacts_customer_info if info.mail_contacts)
Then set the compute attribute to get_email:
selected_email = fields.Char(string="Mail4Info", compute='get_email')
You can check the ORM documentation on how to use the computed fields.
Edit (compute method):
You are setting the value of selected_email to each element of list_email, after the compute_email is executed the value of selected_email will always be the last value of list_email.
The last for loop is executed each time we loop over record.field_contacts_customer_info, it should be at the same level as the second loop.
The list_email is declared before we loop over records (it is not reset in the loop), after the first record, each record will use the email values of previous records.
When record.is_company is evaluated to False, the compute method will not assign a field value, you should see the following error:
ValueError: Compute method failed to assign {record description}.selected_email
It happens because the compute method must assign a field value
Example:
#api.depends('field_contacts_customer_info.mail_contacts')
def compute_email(self):
for record in self:
list_email = []
if record.is_company:
for element in record.field_contacts_customer_info:
if element.name_contacts:
list_email.append(element.mail_contacts)
emails = ""
for email in list_email:
emails += email + " "
record.selected_email = emails
else:
record.selected_email = ""
You can change the list_email type to a string and avoid looping again to get the field value:
Example:
#api.depends('field_contacts_customer_info.mail_contacts')
def compute_email(self):
for record in self:
list_email = ""
if record.is_company:
for element in record.field_contacts_customer_info:
if element.name_contacts:
list_email += element.mail_contacts
record.selected_email = list_email
I want to update the "on_hand_qty" field of existing record
_inherit="product.product"
on_hand_qty=fields.Float('onhand', compute='copy_quant' ,store=True)
#api.constrains('qty_available')
def copy_quant(self):
for rec in self:
rec.on_hand_qty = rec.qty_available
I want this field with store =True
but this field is not updated in old records with store= True. please suggest how to achieve this.
user10810227
Make the related field of qty_available
on_hand_qty=fields.Float(related='qty_available', string="Your Field")
Is there a way to automatically set field values for models in Django when defining the model?
I need t define some values of fields automatically in my model using function.
my function get input image path calculate and I need that calculation results to define my database fields in Django.
first to I want is something like this :
my view :
def myview(request):
uploadimages = UploadImagesForm(request.POST or None, request.FILES or None)
if uploadimages.is_valid():
# Get the images that have been browsed
if request.FILES.get('multipleimages', None) is not None:
images = request.FILES.getlist('multipleimages')
for image in images:
MyModel.objects.create(field1=request.user,field2=image)
that doesn't work because to work my function need first to upload image in server to get the path to work.
any idea how to define my model automate using my function ?
update
instance = MyModel.objects.create(user=request.user, upload=image)
instance.field1 = name
instance.field2 = myvalue
instance.field3 = myvalue2
instance.field4 = myvalue3
instance.field5 = myvalue4
instance.save()
error in this code is the my function cant understand the image path to create the calculation to set the values in fields.
if I use this :
MyModel.objects.create(user=request.user, upload=image)
instance = MyModel.objects.create(user=request.user, upload=image)
instance.field1 = name
instance.field2 = myvalue
instance.field3 = myvalue2
instance.field4 = myvalue3
instance.field5 = myvalue4
instance.save()
that work but create me duplicates in database .
You can try:
instance = MyModel.objects.create(field1=request.user, field2=image)
instance.field3 = myfunc(image)
instance.field4 = myfunc(image)
instance.save()
Hi I'm trying to get the value from request.args(0) and use it in the submitting of a form.
I want 'game_id' to be automatically assigned the args value (which is the unique ID of the game in my games table.
def review():
getId = db.games(request.args(0)) or redirect(URL('default', 'index'))
formReview = SQLFORM(db.reviews,fields = ['game_id','title','review']).process()
db.reviews.game_id.default= request.args(0)
formReview.vars.game_id = request.args(0)
if formReview.accepted: redirect(URL('index'))
return dict(formReview=formReview, getId=getId)
db.define_table('reviews',
Field('title',requires=IS_NOT_EMPTY()),
Field('review','text',requires=IS_NOT_EMPTY()),
Field('game_id', 'reference games'))
I thought the line:
formReview.vars.game_id = request.args(0)
would pre populate the field but it isn't working.
The most reliable way to pre-populate the form is by setting the field's default value (which must be done before creating the form):
def review():
getId = db.games(request.args(0)) or redirect(URL('default', 'index'))
db.reviews.game_id.default = request.args(0)
formReview = SQLFORM(db.reviews, fields=['game_id','title','review']).process()
if formReview.accepted: redirect(URL('index'))
return dict(formReview=formReview, getId=getId)