My Django Password encryption is not working - python

I have a User table that has some attributes where the Password is being stored as a String. I am trying to store it as an encrypted string using bcrypt, but for some reason it is not changing and the password continues to be the one before encryption.
I have this in my settings.py:
enter image description here
And the method to add my User to the table is in views.py as this:
enter image description here
What am I doing wrong and how can I fix it?

I think you shouldn't do custom encryption. Django already has an encryption system. You can easily integrate bcrpyt as in the documentation. Then all you have to do is;
passwd = user_data['passwd']
user = user_serializer.save()
user.set_password(passwd)
user.save()
EDIT:
Changing password Django doc

Your django configurations are wrong, they should be these:
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
]

this is not the why you should create users with API
first install django rest framework (DRF)
then do this
serializers.py
from django.conf import settings
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
"""Serializes a user object"""
class Meta:
model = User
fields = ('__all__')
extra_kwargs = {
'password': {
'write_only': True,
'style': {'input_type': 'password'}
}
}
def create(self, validated_data):
"""Create and return new user"""
user = User.objects.create_user(**validated_data)
return user
permissions.py
from rest_framework import permissions
class UpdateOwnUser(permissions.BasePermission):
"""Allow user to just change their own profile"""
def has_object_permission(self, request, view, obj):
"""Check if user is trying to change their own profile"""
if request.method in permissions.SAFE_METHODS:
return True
return obj.id == request.user.id
views.py
from rest_framework.authentication import TokenAuthentication
from rest_framework import viewsets
from . import permissions, serializers
class UserViewSet(viewsets.ModelViewSet):
"""Handle creating and updating profiles"""
serializer_class = serializers.UserSerializer
queryset = User.objects.all()
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.UpdateOwnUser,)
urls.py
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register('profile', views.UserProfileViewSet)
urlpatterns = [
path('', include(router.urls)),
]
in the root url.py:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('profiles_api.urls')),
]

Related

Why my response data is not being shown in the postman and how do I see the request data in Django

views.py
from django.shortcuts import render
from rest_framework import viewsets
from django.http import HttpResponse
from .serializers import TodoSerializer
from .serializers import UserSerializer
from .models import Todo
from .models import User
class TodoView(viewsets.ModelViewSet):
serializer_class = TodoSerializer
queryset = Todo.objects.all()
def get_object(request):
return "Added";
class UserView(viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
def get_object(request):
print("request", request)
return "Registered";
class LoginView(viewsets.ModelViewSet):
#serializer_class = UserSerializer
#queryset = User.objects.all()
#print("queryset = ",queryset[len(queryset)-1].email_id)
#print("serializer_class = ",serializer_class)
def get_object(self,request):
return HttpResponse("request")
# Create your views here.
urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from todo import views
router = routers.DefaultRouter()
router.register(r'users', views.UserView)
router.register(r'todos', views.TodoView)
router.register(r'login', views.LoginView)
print("In url file")
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(router.urls)),
]
This is my views.py file and urls.py file.
I have a model created for user, with fields- email_id and password
CRUD operations are implemented automatically, so how do I validate data passed from the login form in frontend
Please tell me what's wrong in the code. I am not able to do the login part.

Django REST Framework got Server Error 500

I followed the turial at django-rest-framework quickstart
I have two URLs namely /users/ and /groups/
The group works perfectly:
but the user url gets a error like this:
server error 500
I set DEBUG to False then add some host to ALLOWED_HOST in settings.py:
DEBUG = False
ALLOWED_HOSTS = [
'127.0.0.1',
'localhost'
]
INSTALLED_APPS = [
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
my urls.py:
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from django_rest.django_rest_app import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
this is my serializers.py:
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url','username','email','group']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url','name']
and this is my views.py:
from django.shortcuts import render
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from django_rest.django_rest_app.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated]
UPDATE
when I set DEBUG to True again, I got this:
Field name group is not valid for model User
I'm still a beginner, I hope you can help
Thanks.
You have made mistake in UserSerializer class
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url','username','email','group']
Please change as follows
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url','username','email','groups']
there is no field named 'group' in User model. Instead it is 'groups'.

Is there any way to make a second LOGIN_REDIRECT_URL in settings.py in Django?

I am creating an app in Django which have two external users:
1. Teacher
2. Student
I have to create total of 3 apps, one the base app that contains home.html template, other the student app that contains student.html template and third teacher app that contains teacher.html template.
I have just created two apps for now, base app and student app, I have created login, logout and register pages for student app, now I am successfully able to redirect the user (student) to the student.html whenever the student logs into the system and I did this by putting LOGIN_REDIRECT_URL = 'student' in my settings.py.
I want to do the same for Teacher app as well but I want to redirect teacher to the teacher.html.
Is there any way that I can create the second LOGIN_REDIRECT_URL in settings.py to fulfil this purpose or it will be done any other way?
My Project Structure
django_project
|__esacp(main system)
|_____migrations
|_____templates
|________esacp
|__________base.html
|__________home.html
|__________student.html
|__________teacher.html
|_____apps.py
|_____forms.py
|_____models.py
|_____views.py
|__django_project
|__student
|_____migrations
|_____templates
|________student
|___________login.html
|___________logout.html
|___________register.html
|_____apps.py
|_____forms.py
|_____models.py
|_____views.py
|__teacher
|__db.sqlite3
|__manage.py
Code of models.py of esacp app
from django.db import models
from django.utils import timezone
class StudentType(models.Model):
studenttype_id = models.IntegerField(primary_key=True)
type_title = models.CharField(max_length=50)
def __str__(self):
return self.type_title
class StudentDetails(models.Model):
name = models.CharField(max_length=50)
username = models.CharField(max_length=50, primary_key=True)
password = models.CharField(max_length=50)
email_id = models.CharField(max_length=100)
contact = models.CharField(max_length=100)
studenttype = models.ForeignKey(StudentType, on_delete=models.CASCADE)
registration_date = models.DateTimeField(default=timezone.now)
modify_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
Code of urls.py of esacp app
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='esacp-home'),
path('student', views.student, name='student'),
]
Code of urls.py of main project
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from users import views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('tlogin/', auth_views.LoginView.as_view(template_name='teacher/tlogin.html'), name='tlogin'),
path('tlogout/', auth_views.LogoutView.as_view(template_name='teacher/tlogout.html'), name='tlogout'),
path('esacp/', include('esacp.urls')),
Code of views.py of teacher app
from django.shortcuts import render
from django.contrib.auth.views import LoginView
class MyLoginView():
def get_success_url(self):
url = self.get_redirect_url()
return url
Code of views.py of esacp app
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'esacp/home.html')
#login_required
def student(request):
return render(request, 'esacp/student.html')
and below I have the statement in setting.py
LOGIN_REDIRECT_URL = 'student'
You have two login URLs. Therefore you can use a different login view for each one, and override get_success_url so that you are redirected to the correct page after login.
For example, the teacher login view would look something like:
from django.contrib.auth.views import LoginView
class TeacherLoginView(LoginView):
template_name = 'teacher/tlogin.html'
def get_success_url(self):
url = self.get_redirect_url()
return url or '/teacher/' # FIXME use reverse here instead of hardcoding the URL
Then use that view instead of TeacherView in your URL patterns.
path('login/', TeacherLoginView.as_view(), name='login'),

Django custom LoginView not logging user in

I'm fairly new to Django, but I'm trying to build a customized authentication system by subclassing the generic Django authentication components. The main issue is that my custom LoginView does not seem to do anything besides refresh the page.
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, ReadOnlyPasswordHashField, AuthenticationForm, UsernameField
from django.utils.translation import gettext, gettext_lazy as _
from .models import CustomUser
BUREAU_CHOICES = [ ('HR', 'Human Resources'),
('CRT', 'Creative'),
('ACC', 'Accounting'),]
class CustomAuthForm(AuthenticationForm):
bureau = forms.ChoiceField(widget=forms.Select, choices=BUREAU_CHOICES)
email = forms.CharField(widget=forms.TextInput(attrs={'autofocus': True, 'placeholder': 'Email'}))
password = forms.CharField(
label=_("Password"),
strip=False,
widget=forms.PasswordInput(attrs={'autocomplete': 'current-password', 'placeholder': 'Password'}),
)
class Meta:
model = CustomUser
fields = ('email', 'password',)
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.contrib.auth.views import LoginView
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
from .forms import CustomAuthForm
class CustomLoginView(LoginView):
form_class = CustomAuthForm
authentication_form = CustomAuthForm
template_name = 'users/login.html'
urls.py
from django.urls import path
from . import views
app_name='users'
urlpatterns = [
path('login/', views.CustomLoginView.as_view(), name='login'),
]
So I've read answers here, here and here which all seem to involve overriding methods from the superclass LoginView. When I rewrite my CustomLoginView to override a method, they are not being called. For example:
views.py
class CustomLoginView(LoginView):
form_class = CustomAuthForm
authentication_form = CustomAuthForm
template_name = 'users/login.html'
def form_valid(self, request):
print(self.request)
return super().form_valid(form)
This does nothing. I can't seem to find any reference to which methods I need to override and within which to place login logic.

Please why is there a circular import error

I am working on a django project, but it returns the included urlconf "myapp.urls"does not appear to have any patterns in it.
I tried checking my views to ensure I imported everything correctly
from django.contrib import admin
from django.urls import path
from .views import home
from accounts.views import login_view
urlpatterns = [
path('admin/', admin.site.urls),
path('',home),
path('accounts/login/', login_view),
]
I expect the site to run and redirect me to the login page
This is my views in the same directory with the urls.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
#login_required
def home(request):
return render(request,"home.html")
This is the views.py for the accounts.
from django.shortcuts import render,redirect
from django.contrib.auth import(
authenticate,
get_user_model,
login,
logout
)
from .forms import UserLoginForm, UserRegisterForm
def login_view(request):
next = request.GET.get('next')
form = UserLoginForm()
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username,password=password)
login(request,user)
if next:
return redirect(next)
return redirect("/")
context = {
'form': form,
}
return render(request, "login.html",context)
When I run your project on Django 2.2, I don't see a circular import. Instead I see the error:
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form UserRegisterForm needs updating.
Looking at your form, you haven't set fields, you have model = Userfields = [...] instead.
class UserRegisterForm(forms.ModelForm):
...
class Meta:
model = Userfields = [
'username',
'email',
'password',
"c_password"
]
Change it so that you set fields. You can remove 'password' and 'c_password' since you define these on your form separately.
class UserRegisterForm(forms.ModelForm):
...
class Meta:
fields = [
'username',
'email',
]

Categories