I need to pass the current user's entire activity log to an html page, but it seems I cannot find any helpful solution regarding the same.
Is it possible? If yes, please direct me in the right way?
Thanks in advance!
Update:
I found a solution making use of a get() call to django's LogEntry model, but I am clueless as to what shall be the appropriate parameters for doing the same.
Yet another UPDATE:
I am looking for a way to access the activity log of a particular user from the django's log entries WITHOUT saving it to any database
Take a look below listed.....Hope it will help::
lets example::
Create Two Field in Models:
last_activity_ip = models.IPAddressField()
last_activity_date = models.DateTimeField(default = datetime(1960, 1, 1))
user = models.OneToOneField(User, primary_key=True)
Since the User and UserActivity models are now related one-to-one we can now type:
Run the Query Like this:
a = User.objects.get(username__exact='mpcabd')
print a.useractivity.last_activity_ip
b = UserActivity.objects.get(user=a)
print b.user.username
** To track the activity use this **
activity = None
try:
activity = request.user.useractivity
except:
activity = UserActivity()
activity.user = request.user
activity.last_activity_date = datetime.now()
activity.last_activity_ip = request.META['REMOTE_ADDR']
activity.save()
return
activity.last_activity_date = datetime.now()
activity.last_activity_ip = request.META['REMOTE_ADDR']
activity.save()
This question don't has a short answer, you can use sentry project by side of main django project. below link can helping you:
https://sentry.readthedocs.org/en/latest/
Related
This question already has an answer here:
How can I create a django model instance with deferred fields without hitting the database?
(1 answer)
Closed 8 months ago.
I want to know if I can instanciate an empty fake model just with id of database record.
I found way to create mockup model, but I want a production-friendly solution.
Explanation of my issue :
I want to list users settings for users who choose to be displayed on public mode :
user_displayed_list = UserPublicProfile.objects.filter(
displayed = True,
).only(
'user_id',
'is_premium',
)
user_settings_list = []
for user_displayed in user_displayed_list:
# I have to send user Instance to the next method :
user_settings = self.get_user_settings(user_displayed.user)
user_settings_list.append(user_settings)
# But ’user_displayed.user’ run an new SQL query
I know I can improve my queryset as :
user_displayed_list = UserPublicProfile.objects.filter(
displayed = True,
).select_related(
'user'
).only(
'user',
'is_premium',
)
But It makes an useless join because I need only the user id field in get_user_settings():
The get_user_settings() method (it could help to understand context):
def get_user_settings(self, user)
user_settings = UserSettings.objects.get(user = user)
return user_settings
In real project, this method run more business feature
Is there a way to instanciate a User model instance with only id field filled ?
I don't want to use a custom empty class coded for this purpose. I really want an object User.
I didn't find anything for that. If it's possible, I could use it by this way :
for user_displayed in user_displayed_list:
FakeUser = User.objects.create_fake(id = user_displayed.user_id)
# I have to send user Instance to the next method :
user_settings = self.get_user_settings(FakeUser)
Without seeing the complete models, I'm assuming a bit. Assuming that UserSettings has a ForeignKey to User. Same for UserPublicProfile. Or User has ForeignKey to UserSettings. Works as well.
Assuming that, I see two solutions.
Solution #1; use the ORM to full potential
Just saw your comment about the 'legacy method, used many times'.
Django relations are very smart. They accept either the object or the ID of a ForeignKey.
You'd imagine this only works with a User. But if you pass the id, Django ORM will help you out.
def get_user_settings(self, user)
user_settings = UserSettings.objects.get(user = user)
return user_settings
So in reality, these work the same:
UserSettings.objects.get(user=1)
UserSettings.objects.get(user_id=1)
Which means this should work, without a extra query:
user_displayed_list = UserPublicProfile.objects.filter(
displayed = True,
).only(
'user_id',
'is_premium',
)
user_settings_list = []
for user_displayed in user_displayed_list:
# I have to send user Instance to the next method :
user_settings = self.get_user_settings(user_displayed.user_id) # pass the user_id instead of the object.
user_settings_list.append(user_settings)
Solution #2: chain relations
Another solution, again, still assuming quite a bit ;)
It would think you can chain the model together.
Assuming these FK exists: UserPublicProfile -> User -> UserSetting.
You could do this:
user_displayed_list = UserPublicProfile.objects.filter(
displayed = True,
).select_related(
'user', 'user__usersettings', # depends on naming of relations
).only(
'user',
'is_premium',
)
for user_displayed in user_displayed_list:
# I have to send user Instance to the next method :
user_settings = user_displayed.user.usersettings # joined, so should cause no extra queries. Depends on naming of relations.
user_settings_list.append(user_settings)
I have a django model, PhoneNumberVerification.
It has two columns: phone number, and code.
I want to be able to get the code if I am given a phone number. Essentially, search the table for which row has the phone number as my phone number, and fetch the code for that given row.
I could write SQL for this, but I do not know how to execute that to fetch data in django models, and I was wondering if there was a better non-sql way to do this.
My model:
class PhoneNumberVerification(models.Model):
phone_number = models.TextField(max_length = 20, blank = False, unique = True)
code = models.CharField(max_length = 8, blank = False)
What I want:
from .models import PhoneNumberVerification
def get_code(phone_number):
# do some stuff
return code
def get_code(phone_number):
verification = PhoneNumberVerification.objects.get(phone_number=phone_number)
return verification.code
Django's documentation has great tutorial for beginners.
Writing your first Django app, part 2
to get the object, you can simply use:
def get_code(phone_number):
try:
phone_number_verification = PhoneNumberVerification.objects.get(phone_numer=phone_number)
code = phone_number_verification.code
return code
except PhoneNumberVerification.DoesNotExist:
pass # django will raise exception in case if number does not exist
if you know there is only one object that matches your query, you can use the get(), which will return the object directly.
Otherwise, you can use filter(), more on that here
I'm getting a very slow lookup in my Django models.
I have two tables:
class Scan(models.Model):
scan_name = models.CharField(max_length=32, unique=True, validators=[alphanumeric_plus_validator])
class ScanProcessingInfo(models.Model):
scan_name = models.CharField(max_length=32)
processing_name = models.CharField(max_length=64)
in_progress = models.BooleanField(default=False)
When I perform the following operation to get a list of all Scan objects which have a ScanProcessingInfo for a specific processing_name:
scans = models.Scan.objects.all()
scan_set = []
for scan in scans:
if self.set_type_definition.test_scan(scan, self.arg1, self.arg2):
scan_set.append(scan)
(test_scan routes to)
def get_proc_info_been_done(scan, spd_name):
try:
proc_info = models.ScanProcessingInfo.objects.get(scan_name = scan.scan_name)
except models.ScanProcessingInfo.DoesNotExist:
proc_info = None
if proc_info == None:
return False
return not proc_info.in_progress
the request takes about 10 seconds. There are 300 Scans in total and 10 ScanProcessingInfos. The db backend is an RDS MySQL db. I also expect someone will tell me off for using strings for the cross-table identifiers, but I doubt that's the cause here.
I'm sure I'm doing something obvious wrong, but would appreciate a pointer, thank you.
I think what you're asking is how to get all Scans for which a matching ScanProcessingInfo exists.
The first thing to do is to declare the actual relationship. You don't need to change your database (you should, but you don't have to); you can use your existing underlying field, but just tell Django to treat it as a foreign key.
class ScanProcessingInfo(models.Model):
scan = models.ForeignKey('Scan', to_field='scan_name', db_field='scan_name', on_delete=models.DO_NOTHING)
Now you can use this relationship to get all the scans in one go:
scan_set = Scan.objects.exclude(scanprocessinginfo=None)
Edit
To get all matching objects with a specific attribute, use the double-underscore syntax:
scan_set = Scan.objects.filter(scanprocessinginfo__processing_name=spd_name)
Use Many-to-one relationship.
scan_name = ForeignKey(Scan, related_name='processing_infos',on_delete=models.CASCADE)
i have a models
class FriendsWith(models.Model):
username = models.ForeignKey(User,on_delete=models.CASCADE)
fusername =models.ForeignKey(User,on_delete=models.CASCADE,related_name='fusername')
time = models.DateTimeField(auto_now_add=True)
confirm_request = models.SmallIntegerField(default=1)
blocked_status = models.IntegerField(default=0)
i wanted to search all the friends of currently logged in user.So,i am doing like this
obj1=FriendsWith.objects.filter(username=request.user).select_related('fusername')
obj2=FriendsWith.objects.filter(fusername=request.user).values('username')
obj=obj1 | obj2
friendslist=User.objects.filter(username__in=obj)
Where User is a django User model
I am trying to combine two queryset(obj1 and obj2) set here But it's not working.I can do the same thing in sql by using alias .But here i am not sure what to do.
I am getting this error while performing the above code:
TypeError: Merging 'QuerySet' classes must involve the same values in each case
Please help in achieving this task
I think you should do the 'or' in the filter function:
from django.db.models import Q
friendship = FriendsWith.objects.filter(Q(username=request.user)|Q(fusername=request.user))
friendship is a queryset where the current user can be a username or a fusername. You can use that set to get the alternative user that should be their friend.
Another solution is to use django-friendship. It is a good django library for handling friendship and friend requests between users and so on.
I am having some troubles with Django's save() method.
1 / I have this simple Model :
class User (models.Model):
userId = models.IntegerField()
appInstance = models.TextField(null=True, blank=True)
2 / Then in a view, I check if the appInstance does exist and if not I call a function:
if not u.appInstance:
instance = autoAddApplication(request)
3 / and autoAddApplication is defined as follows:
def autoAddApplication(request):
session = request.session
user = get_object_or_404(User, userId = session['user_id'])
## do stuff here and end up with an 'instanceMap' dictionary
user.appInstance = simplejson.dumps(instanceMap)
user.save()
return instanceMap
The code runs with no error, but I don't get the Model saved in the database when the autoAddApplication function is called from the condition in step 2.
I tried to call this 'autoAddApplication' function directly by mapping a URL diretly to this function and then it does work and I get my Model saved in the DB.
I'm completely puzzled here. Why doesn't it work when I call this 'autoAddApplication' function from within another function ? Any help would be greatly appreciated.
EDIT
I finally found what I was doing wrong.
Later in step 2 I had a u.save() which was indeed saving u (and therefore overridding the changes I made in the autoAddApplication function).
I solved it by passing along u to the autoAddApplication function.
Anyway thanks for your help.
Try changing the class name from User to MyUser or something like that, you may be having troubles with the User model defined in Django.
How about to use autoAddApplication as a private function inside the view?
def _auto_add_application(session):
user = get_object_or_404(User, user_id = session['user_id'])
user.app_instance = simplejson.dumps(instance_map)
user.save()
return instance_map