can I call a function to set my USERNAME_FIELD = ''? - python-3.x

can I call a function in USERNAME_FIELD = '' to create an optional choice for login, using email or phone number? if yes how?

yes, you can
you can write special login function in your view and use query like this :
user = User.objects.filter(Q(email=value)|Q(username=value)).first()
login(request, user)
I use Q django db functions to complex query and I can use Or in my queries for example in up code I filter email equal by value or username equal by value so if uaer enter username or email I can find him
in other ways I can use two query but its not common
like this :
user_by_username=User.objects.filter(usernsme=value).first()
if user_by_username:
login(request,user)
else:
user_by_email=User.objects.filter(email=value).first()
if user_by_email:
login(request,user_by_email)
and default user model hasn't mobile field you can save mobile as username or create special usermodel
or create new model for your user profile

Related

How to generate random ID instead of auto increment in Mongoose

I am creating an app where customers can scan codes, and when scanned, it opens a website which basically redeems that code. The problem is that all these codes have an auto-incremented ID, so the customer could just redeem all possible codes just by increasing the ID number in the url.. Is there a way to generate random uuid's in mongoose instead of the default auto incremented ObjectID?
You can achieve what you are looking for by the below command:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
where 4edd40c86762e0fb12000003 is the custom ObjectId you desire for.
To generate a completely random non-incrementing string, use the below code.
let randomString = _.times(16, () = (Math.random()*0xF<<0).toString(24)).join('');
var id = mongoose.Types.ObjectId(randomString);
Make sure that you are Inserting/Updating is a valid ObjectId on length 24 and a duplicate of the same ObjectId doesn't exist in another document in the same collection.
To generate a random ObjectId, use the below code.
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();
Note: A random ObjectId will be created if you don't pass any value to the parameter
Furthermore, you can insert any custom _id key inside MongoDB of any recognized MongoDB types, as long as its' unique in that collection, it will work.
Example:
db.col.insertMany([{"_id": 1}, {"_id": 2}])
db.col.insertMany([{"_id": "Product1"}, {"_id": "Product2"}])
will work just fine.
Instead of replacing the entire unique ObjectId with a random number, could you append a random number when printing out the code?
For example, parseInt(Math.floor(Math.random()*65536),16) will give you a random 4-character code. Store that as a validator when writing the document to the database, and append it to the ObjectId when generating the scannable token.
When the user scans the code, you can use the first 24 characters to look up the document, then verify that the last 4 characters match the validator. No external libraries required.
If you want to get even fancier, append a check digit or checksum on the code (such as is done with credit card numbers) so that the client side can sometimes determine that a code is invalid without even consulting the database.

How get data of single user's in own_reactions using stream_python?

In order to fetch a feed using stream_client the documentation says.
feed = stream_client.feed('feed_group', 'some valid id')
feed_data = feed.get(enrich=True, reactions = {'own':True})
In this case, own_reactions contains data of more than one users.
How can I filter the own_reactions by only one user while fetching the feed?
You shuould specify user_id when doing feed.get like so:
feed_data = feed.get(enrich=True, reactions={'own': True}, user_id='jelte')
This is also shown in the docs here: https://getstream.io/docs/python/#reactions_read-feeds

Python - Querying dictionaries within dictionaries

I have a question if anyone would be so kind to help me? :) Could you help me with a little bit of code regarding dictionaries within dictionaries:
A simple program that prompts a user for an email address (that must be stored in the database) in order to gain access to the webpage
Here we shall build dictionaries to hold the data... within a dictionary that will hold the entire database:
database_of_users = {
"Cleaus": {"email" : "c#gmail.com"},
"Jay" : {"email" : "j#hotmail.com"},
"Tremaine" : {"email" : "t#gmail.com"},
"Kyla" : {"email" : "k#outlook.com"}
}
Next bit:
user_email = input("To gain access to this feed, you must be a member
of the site. \n\nIf you are already a member, please enter your
email address below: \n\n").strip().lower()
Then:
while True:
if "#gmail.com" in user_email or "#hotmail.com" in user_email or
"#outlook.com" in user_email:
break
elif "#gmail.com" not in user_email or "#hotmail.com" not in
user_email or "#outlook.com" not in user_email:
user_email = input("\nPlease enter a valid email
address (gmail/hotmail/outlook): \n\n").strip().lower()
Here I am stuck on how to search all of the secondary (nested) dictionary value entries within the main dictionary. I have tried turning it into a list first and then calling what I thought would be the value entries in the second dictionary to query them, but it is not working:
database_aslist = list(database_of_users.values()
I realise the if statement below is just calling the first bit before the 'item' = (key:value), so in this case the name "Cleaus", "Jay","Tremaine","Kyla", but I am just unsure of how to query all data within the main dictionary completely, keys and values included, at the same time? Is it possible?
if user_email in database_of_users:
print("\nOk, I have found you. Please enjoy the show!")
print("\n\n[GAINED ENTRY]")
if user_email not in database_of_users:
print("\nSorry, that email address does not seem to be in our database.
To gain access, please register for one of our packages here:
\n\n[LINK WHERE THEY CAN SIGN UP]\n\nThank you!\n")
Thanking you all in advance for your help!
I've never known a way without walking through the dictionary. Something like this:
user_found=False
for user in database_of_users:
if database_of_users[user]["email"]==user_email:
user_found=True
break
if user_found:
print("\nOk, I have found you. Please enjoy the show!")
print("\n\n[GAINED ENTRY]")
else:
print("\nSorry, that email address does not seem to be in our database.
To gain access, please register for one of our packages here:
\n\n[LINK WHERE THEY CAN SIGN UP]\n\nThank you!\n")
Though, if email is what is being entered, changing the database_of_users to use emails in the first nesting might be the easier way to go if that's an option:
database_of_users={
"c#gmail.com": {"name":"Cleaus"},
"j#hotmail.com": {"name":"Jay"},
...
}

Get SPListItem in another format

I want to get different Rows from an SPListItem. I'll show you my problem with an example.
This code
Console.WriteLine(SPItemName["Created By"]);
or
Console.WriteLine(SPItemName["Created By"].ToString);
returns "8;UserName" (8 is the User ID).
If I look up the row in SharePoint Designer, i can choose even a format for this data field.
So i could get the html code of this field.
How to set the format (like html code or text) of a datafield in c#?
thanks
Use Either SPFieldLookupValue
If you need just the username, use SPFieldLookupValue to seperate id from value:
var userValue = new SPFieldLookupValue(SPItemName["Created By"] as string)
Then you can:
userValue.LookupValue to return UserName
userValue.LookupId to return Id
Or SPFieldUserValue
Or better yet, you can create SPFieldUserValue object to access any other user properties like email, login name, etc..
SPFieldUserValue objUserFieldValue = new SPFieldUserValue(web, SPItemName["Created By"].ToString());
Afterwards you can use:
objUserFieldValue.User.LoginName;
objUserFieldValue.User.Name;
objUserFieldValue.User.ID;
objUserFieldValue.User.Groups;
objUserFieldValue.User.Roles;
objUserFieldValue.User.Email;
objUserFieldValue.User.Sid;
objUserFieldValue.User.UserToken;
http://www.sharepointkings.com/2009/04/spfielduservalue-and.html
Note: to create SPFieldUserValue you must pass reference to web, that's because SharePoint has to get additional user information from user information list to construct SPFieldUserValue object.

Setting author field in SPListItem won't persist

I am trying to copy an SPListItem (with file) from one site collection to another. I do this by creating the file like this:
var archiveFile = newsArchive.Lists[listName].RootFolder.Files.Add(originalItem.File.Name, originalItem.File.OpenBinary());
var archiveItem = archiveFile.Item;
through a utility method I wrote i then set all field values of the new item to correspond with the original item like so
Utilities.PopulateListItemMetadata(....)
The thing is, this does not persist the Author field.
I tried setting the Author field explicitely in every way imaginable, for instance like so:
string userName = originalItem.GetUser("Created by").LoginName;
SPUser user = newsArchive.SiteUsers[userName];
archiveItem["Author"] = user.ID + ";#" + user.LoginName;
archiveItem.Update();
And like so
string userName = originalItem.GetUser("Created by").LoginName;
SPUser user = newsArchive.SiteUsers[userName];
archiveItem["Author"] = user;
archiveItem.Update();
But as soon as the SPListItem.Update() method is called, the archiveItem["Author"] field has reverted to sharepoint\system. I'm a bit at a loss here, this should work..
P.S. the SPListItem.GetUser method is an extension method
P.P.S. Code is being run from a timer job...
Edit: Did some more digging by adding a new field to the content type and then setting that field to reflect the Author of the original item, but that is not set either. However, the web.EnsureUser(username) does return the correct user. Is this weird or what!?!
Found the answer, using
SPFieldUserValue val = new SPFieldUserValue(newsArchive, user.ID, user.Name);
archiveItem["Author"] = val;
archiveItem.SystemUpdate(false);
did the trick!
I've experienced the same problem. Have a look at this question.
The way that worked for me is to wrap the same code you have in your final example in elevated privileges.
Edit
Why don't you try replacing:
SPUser user = newsArchive.SiteUsers[userName];
with:
SPUser user = newsArchive.EnsureUser(userName);
Then you will know the user is in the web and also get a reference to them. The SiteUsers collection gives you the users in the site collection - they have not necessarily been added to the web. If SharePoint doesn't find the user it will probably use system account.

Resources