Is it right to use django.contrib.auth.models.User in views.py?

I want to create and delete users in my view for my IPN.

django.contrib.auth.models import User 

Or should it be done in models.py? If so, how do I do this?

Not sure if this is technically wrong or just a bad style.

Thank you very much!

+6
source share
2 answers

I find it best to use django.contrib.auth.get_user_model() .

 from django.contrib.auth import get_user_model ... User = get_user_model() 

Thus, the situation will not be violated if you later decide to enable the django application, which extends or cancels the built-in authentication model (it also avoids the class of errors associated with dependency cycles).

+5
source

yes, use it correctly in views.py :

you can get a user model like paulo scardine , paulo scardine .:

 from django.contrib.auth import get_user_model User = get_user_model() 

Now to create a user:

 User.objects.create_user(username='user2', password='pass') 

Now delete the user:

It is recommended to set the is_active flag to False instead of deleting accounts; That way, if your applications have any foreign keys for users, the foreign keys will not be broken. doc

 user_rem=User.objects.get(username='user2') user_rem.is_active=False user_rem.save() 
+2
source

Source: https://habr.com/ru/post/972479/


All Articles