Last seen a user in django - python

How can i show the time of last seen(be online)of user in django?
Is there any default function or library to import it to do that?
Or if there any code inn github tell me please
**Note : ** when a user close page or disconnect the time update

You should inherit django's AbstractBaseUser in your user model, it already has an inbuilt last_login attribute. In fact it is considered a good practice to inherit AbstractBaseUser for creating your user which is provided in django default auth modules.

There is few options.
you can add a code to your views to check for user or session id (depends on how do you want it to work. for registered users or every users or ... ) and every time a user request for a page, you can update that this user has been active on the site on this time.
but this option seem to be usable when you need to track a user in a small project with few pages.
another option which seem more right to do is to use middleware. by using middleware you don't need to change your code in all of your views. simply make a custom middleware and everything will be done with few lines of code
you can check an example of this middleware here:
Django: How can I check the last activity time of user if user didn't log out?
or
Django get last user visit date
and for disconnected part i think you can't do much with django. and also you can't be sure when user closed the page.
the best option here is to use a javascript code to run like every 10 sec and tell django that the user is still on the page.

Related

Is there any implementation of Logging out of other browsers and devices in Flask?

I have to implement a function in my website where there can only be one login per account. So, if a user logs into one browser, the others will automatically be logged out. I am using Flask for backend. Is there any such implementation in Flask, and if not, what are some ways by which I can implement this?
I don't know of any implementation. The first thing that comes to my mind is to modify the user model. You could add a column for logged_in, which get's changed to True when the user is logged in and to False if the user logs out/ the session is dropped.
You would need to check this attribute when verifying the user login. For further specific help consider posting an MRE of your question.

Django User Sessions, Cookies and Timeout

I'm working with a Django application and my current goal is to keep track of the user session with cookies. I have a feeling that, as always, my understanding is a bit off with regards to how I do this.
For starters, I would like to manage how long it has been since a user has logged in, that way I can successfully log them out if they haven't visited a new page in "x" hours. I am not sure what exactly is standard (for a social network).
Is this information I store on my server? Do cookies actually have any relevancy here? I've used cookies before to store things like a user's timezone, but I am struggling to deal with how I keep track of the user.
All I currently have in terms of user back end is from the django.contrib.auth package.
The only thing I really know how to do in terms of "grabbing" the user's info is done by using statements like if request.user.is_authenticated(): (etc.).
I realize this is somewhat of a complex question, so I will try and narrow it down:
How do I extend my existing information about the current user to capture "last activity" so I can log him/her out if they haven't been using the site in a certain period of time?
Do I need to define a custom user model?
My next step after is to create a different type of user, so I feel like I need to make custom user models - beyond just extending the normal user form to make a profile etc.
Thanks for your understanding,
I know I can be confusing when I don't understand things.
Thanks for your time,
James
You can configure the session middleware for logging out the user automatically,
configure the SESSION_COOKIE_AGE, to some low value, and provide the SESSION_SAVE_EVERY_REQUEST, as True.
This will automatically logout the user after certain inactivity, without any need of extending the profile.
SESSION_COOKIE_AGE
Default: 1209600 (2 weeks, in seconds)
>> The age of session cookies, in seconds.
SESSION_SAVE_EVERY_REQUEST
Default: False
>> Whether to save the session data on every request.
If this is False (default), then the session data will only be saved if it has been modified – that is, if any of its dictionary values have been assigned or deleted.
And for creating custom/extending User Profile, Django 1.5, comes with configurable User model, please check the docs for examples.

Django - authentication, registration with email confirmation

I'm looking at the API for authentication
https://docs.djangoproject.com/en/1.3/topics/auth/
I can't seem to find information on simple user registration form that would send confirmation email as it is the usual way on web sites.
I guess I could do this:
1) Display a form
2) User enters info and submits
3) Save user as inactive, with a confirmation code
4) Send a link with confirmation code
5) User clicks a confirmation link and becomes active
It doesn't seem that difficult but I have a feeling this might be done already, and also there are quite a few edge cases that would need to be considered.
It's not built into Django. There is a reusable app called django-allauth, which will fit your needs.
An app called django-registration used to be recommended, but that is now unmaintained and out of date.
Editor note: django-registration is not unmaintained as of December 2016.
While django-registration used to be the registration system du jour, it has been abandoned by the maintainer and doesn't work on Django 1.6 without patching.
Try maybe django-allauth - I would have used it if I had known about it when I was looking. (As it turned out, I found this question first and used django-registration, wasting a lot of time.)
EDIT 10/2016: Looks like django-registration is maintained again. It's on GitHub now: https://github.com/ubernostrum/django-registration
You can do this:
Define a function to activate the user (i. e. def
activate(request))
Configure in the url.py the route to that function (i.e /activate/)
Create a form to register user
Create the post function to create the user
When you create the user set field 'is_active' to 0.
In the same function send the email with a link inside, this link must have the target as the configured route

Remove the "Add" functionality in Django admin [duplicate]

This question already has answers here:
Django Admin - Disable the 'Add' action for a specific model
(5 answers)
Closed 10 years ago.
Is there a way to remove the "Add" functionality on the Django admin site? For certain entities, I only want the Django admin to be able to view them or change existing ones, but not add new ones.
See: Django Admin - Disable the 'Add' action for a specific model for true solution.
Sure, you can customize admin VERY granularly by following the instructions here -- I believe that what you want can be obtained in part by overriding ModelAdmin.save_model(self, request, obj, form, change) in your own ModelAdmin subclass, to ensure nothing happens on the store when change is false (i.e. an attempt to add rather than change), and in part by overriding ModelAdmin.add_view(self, request, form_url='', extra_context=None) to display an "add view" that makes it very clear to the admin that they're NOT going to be allowed to add object through this route. I haven't actually done the specific admin customization you require, but I've done others and they do seem to work pretty smoothly!
You can customize the permission for each user group from within the admin interface: try going to /admin/auth/group and it should be straightforward from there.
This won't be as granular as the solution offered by the earlier answer, but it will take care of most of your needs without needing to customize the admin.
If you change the permissions to restrict access then you'll still get the plus sign by a FK/MtM field. Clicking that will open a popup window with 'Permission Denied' in it.
You can actually completely remove the plus sign by not simply not registering the model with the admin.
I have a situation where I have predefined categories that I want users to be able to select more than one of. The best way to do this is with a models.ManyToMany field. You can register the model with the admin, enter the data as required and then remove the registration.
An easy effective way is to set max_num=0 for that particular inline.
Satya's suggestion of setting max_num=0 works perfectly.
Per the Django docs on the ModelForm class:
For users with JavaScript-enabled browsers, an "Add another" link is provided to enable any number of additional inlines to be added in addition to those provided as a result of the extra argument.
The dynamic link will not appear if the number of currently displayed forms exceeds max_num, or if the user does not have JavaScript enabled.
and
As with regular formsets, you can use the max_num and extra parameters to modelformset_factory to limit the number of extra forms displayed.
max_num does not prevent existing objects from being displayed

how to overwrite User model

I don't like models.User, but I like Admin view, and I will keep admin view in my application.
How to overwirte models.User ?
Make it just look like following:
from django.contrib.auth.models import User
class ShugeUser(User)
username = EmailField(uniqute=True, verbose_name='EMail as your
username', ...)
email = CharField(verbose_name='Nickname, ...)
User = ShugeUser
That isn't possible right now. If all you want is to use the email address as the username, you could write a custom auth backend that checks if the email/password combination is correct instead of the username/password combination (here's an example from djangosnippets.org).
If you want more, you'll have to hack up Django pretty badly, or wait until Django better supports subclassing of the User model (according to this conversation on the django-users mailing list, it could happen as soon as Django 1.2, but don't count on it).
The answer above is good and we use it on several sites successfully. I want to also point out though that many times people want to change the User model they are adding more information fields. This can be accommodated with the built in user profile support in the the contrib admin module.
You access the profile by utilizing the get_profile() method of a User object.
Related documentation is available here.

Categories