How to access cookie and IP fields in DjangoRatings? - python

I'm using the djangoratings library found here and I have everything running and set up. In my views.py file I have a button which executes this line of code when pushed:
myinstance.rating.add(score=1, user=request.user, ip_address=request.META['REMOTE_ADDR'], request.COOKIES)
Everything works fine. The backend works, my columns are updated with the votes etc etc, but how can I access/call the IP and cookie fields and columns in djangoratings so that I can write a quick if condition that refuses to run the 'add' line if the cookies and IP have already voted?
Thanks in advance for any help. I've been really struggling with this a lot.

myinstance.rating contains method get_ratings() - which returns queryset to calculate all votes related to object. You can easily extend it for retrive necessary information. For example:
# it's lazy object
rating = myinstance.rating.get_ratings()
# do additional query for db
if not rating.filter(user=user, ip_address=request.META['REMOTE_ADDR']).exists():
...

Related

rtcclient ownedBy returns User ID and not email address

I am using the Python package rtclcient (v0.6.0) to get info from work item.
Some of the properties I am querying from my RTC work item include:
returned_properties_list = [
"rtc_cm:modifiedBy",
"dc:modified",
"rtc_cm:contextId",
"dc:subject",
"oslc_cm:priority",
"dc:creator",
"rtc_cm:due",
"rtc_cm:estimate",
"rtc_cm:correctedEstimate",
"rtc_cm:timeSpent",
"rtc_cm:startDate",
"dc:created",
"rtc_cm:resolvedBy",
"rtc_cm:plannedFor",
"rtc_cm:ownedBy",
]
When the query for these items finish and I examine the returned variables, I notice that the 'ownedBy' value is the user's id, not their email address.
If I look at the value of raw_data['rtc_cm:ownedBy']['#rdf:resource'] it is a link which goes to that user's profile.
On the profile I can see the same User ID which is being recieved as the 'ownedBy' value.
Also on the profile is the User's E-mail Address. This email address value is what I need, but I can't seem to find a way to query for this value using the rtcclient python package.
I've tried adding "rtc_cm:emailAddress" to my query properties but no luck,
Can anyone help me get the ownedBy user email address for a RTC ticket using the rtcclient package? Thanks
fixed by cloning the rtcclient repo, and adding my own custom function getUserEmail

Getting SalesforceMalformedRequest: Malformed request error

I am trying to execute this following code to push data to Salesforce using the simple_salesforce python library :
from simple_salesforce import Salesforce
staging_df = hive.execute("select * from hdmni")
staging_df = staging_df.toPandas()
# # staging_df['birth_date']= staging_df['birth_date'].dt.date
staging_df['birth_date'] = staging_df['birth_date'].astype(str)
staging_df['encounter_start_date'] = staging_df['encounter_start_date'].astype(str)
staging_df['encounter_end_date'] = staging_df['encounter_end_date'].astype(str)
bulk_data = []
for row in staging_df.itertuples():
d= row._asdict()
del d['Index']
bulk_data.append(d)
sf = Salesforce(password='', username='', security_token='')
sf.bulk.Delivery_Detail__c.insert(bulk_data)
I am getting this error while trying to send dictionary to salesforce :
SalesforceMalformedRequest: Malformed request
https://subhotutorial-dev-ed.my.salesforce.com/services/async/38.0/job/7500o00000HtWP6AAN/batch/7510o00000Q15TnAAJ/result.
Response content: {'exceptionCode': 'InvalidBatch',
'exceptionMessage': 'Records not processed'}
There's something about your query that is not correct. While I don't know your use case, by reading this line, you can tell that you are attempting to insert into a custom object/entity in Salesforce:
sf.bulk.Delivery_Detail__c.insert(bulk_data)
The reason you can tell is because of the __c suffix, which gets appended onto custom objects and fields (that's two underscores, by the way).
Since you're inserting into a custom object, your fields would have to be custom, too. And note, you've not appended that suffix onto them.
Note: Every custom object/entity in Salesforce does come with a few standard fields to support system features like record key (Id), record name (Name), audit fields (CreatedById, CreatedDate, etc.). These wouldn't have a suffix. But none of the fields you reference are any of these standard system fields...so the __c suffix would be expected.
I suspect that what Salesforce is expecting in your insert operation are field names like this:
Birth_Date__c
Encounter_Start_Date__c
Encounter_End_Date__c
These are referred to as the API name for both objects and fields, and anytime code interacts with them (whether via integration, or on code that executes directly on the Salesforce platform) you need to make certain you're using this API name.
Incidentally, you can retrieve this API name through a number of ways. Probably easiest is to log into your Salesforce org, and in Setup > Object Manager > [some object] > Fields and Relationships you can view details of each field, including the API name. Here's a screen shot.
You can also use SObject describe APIs, either in native Apex code, or via integration and either the REST or SOAP APIs. Here's part of the response from the describe API request to the describe REST endpoint for the same object as my UI example above, found here at https://[domain]/services/data/v47.0/sobjects/Expense__c/describe:
Looking at the docs for the simple-salesforce python library you're using, they've surfaced the describe API. You can find some info under Other Options. You would invoke it as sf.SObject.describe where "SObject" is the actual object you want to find the information about. For instance, in your case you would use:
sf.Delivery_Detail__c.describe()
As a good first troubleshooting step when interacting with a Salesforce object, I'd always recommend double-checking correctly referencing an API name. I can't tell you how many times I've bumped into little things like adding or missing an underscore. Especially with the __c suffix.

Trying to change a username in Python Google Admin SDK

I'm trying to change a username using the Admin SDK. I'm trying the following code to update this, using a dict object to store the new info, and using patch to update:
userinfo['primaryEmail'] = D['new_user'] + '#' + D['domain']
appsservice.users().patch(userKey = userEmail, body=userinfo)
It doesn't seem to be working, when I look at the admin console. The original username remains unchanged. I'm just wondering if I'm using the correct method. Should I be updating a different variable than primaryEmail or without using the domain affiliation? Seems like I'm just missing something rather obvious.
Thanks,
Tom
Add:
.execute()
To the end of the 2nd line to actually execute the api operation.

Item won't update in database

I'm writing a method to update several fields in multiple instances in my database. For now, I'm trying to get it to work just for one.
My user uploads a CSV file with all the information to change (including the pk). I've written the function that parses all the information, and this all works fine. I can even assign the data to an item, and if I print it from that function, it comes out correctly. However, when I save the updates (using item.save()) nothing seems to change in the database.
Here's a very stripped down version of the method. I really don't know why it isn't working. I've done something very similar in other spots (getting data through a form, setting the field, calling save, and then displaying the changed information), and I've used a very similar CSV uploading technique to create new entries.
Small piece of relevant code:
reader = csv.reader(f)
for row in reader:
pk = row[0]
print(pk)
item = POObject.objects.get(pk=pk)
p2 = item.purchase2
print item.purchase.requested_start_date
print p2.requested_start_date
requested_start_date=row[6]
requested_start_date = datetime.datetime.strptime(requested_start_date, "%d %b %y")
print requested_start_date
p2.requested_start_date = requested_start_date
p2.save()
print p2.requested_start_date
item.purchase2 = p2
item.save()
print item.purchase.requested_start_date
return pk
Obviously I have lots of prints in there to find where stuff went wrong. Basically what I find is that if I look at item, it looks fine, but if I query the server again (after saving) i.e. dong item2=POObject.objects.get(pk=pk) it won't have had any updates. Does anyone have any idea why save() isn't doing anything?
UPDATE:
The mystery continues.
If I update a field that isn't contained within an FK relation (say, a text field or something), everything seems to work fine. However, what I really need to do is update an item, and then set that item as the fk relation to the main item in question. I'm not sure why this isn't working in the normal way (updating the internal item, saving it, and then setting the fk to that new, updated item).
Whoa. Feel a little ashamed that I didn't figure this out. I had forgotten exactly how I had designed one of my models, and there was another object within it that needed to be updated, but I wasn't saving it.

Selecting the next formfield with Selenium RC and python

I am running an automated test to test a webform for my company. They have just installed a zipcode service which automatically adds the Street and City/Region when you fill in the Address and housenumber.
This autofill appears when you deselect the last form element (e.g. that of the housenumber).
This is the order of the fields I'm using;
form:zipcode
form:housenumber
form:addition (optional)
form:street (gets filled in by service after zipcode and housenumber are provided)
form:city (the other autofill field)
When you fill this form out manually, the address appears as soon as you click or tab into the addition field (as it is optional) but when it's done automated it doesn't work.
I have tried several things like;
focus('form:addition') or
select('form:addition') but these don't work. I have tried
type('\t') to tab to the form field, and
type('form:addition', ' ') to type a space into the add. field and even
type('form:addition', "") to leave it empty. None of these attempts have worked so far.
Is there anyone that can help me with this?
Hi i got a solution for this i think,
problem is with generating the user interactions to the addition field.
use these statements
focus("form:addition");
keyPressNative("10") //this is ENTER command
it should work
Yesterday I found out that the zipcode service uses an Ajax call to retrieve the information. This call is executed when the zipcode and housenumber fields are both 'out of focus' (i.e. deselected).
The right statement I found to use this in my advantage is this;
selenium.fireEvent('form:number', 'blur') which deselects the last field where data was entered.

Categories