I have a basic CustomUser model in my project. When I want to update it I fill my form with instance where I try to make user's password null, but anyway in the form I receive: "No password set.
Set password
Raw passwords are not stored, so there is no way to see the user’s password." And Set password is a link that leads me to nowhere. I just want a password field to be null in my update form.
views.py
...
class CustomUserUpdateView(View):
def get(self, request, *args, **kwargs):
user_id = kwargs["user_id"]
if request.user.is_authenticated:
user = get_object_or_404(CustomUser, id=user_id)
user.password = None
if request.user == user:
form = CustomUserChangeForm(instance=user)
return render(
request, "users/update.html", {"form": form, "user_id": user_id}
)
else:
return HttpResponse("you damn wrong")
else:
return HttpResponse("you idiot")
def post(self, request, *args, **kwargs):
user_id = kwargs["user_id"]
user = get_object_or_404(CustomUser, id=user_id)
form = CustomUserChangeForm(request.POST, instance=user)
if form.is_valid():
form.save()
return redirect("users_list")
return render(
request, "users/update.html", {"form": form, "user_id": user_id}
)
...
models.py
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
pass
def __str__(self):
return self.username
forms.py
...
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('first_name', 'last_name', 'username', 'password')
update.html
{% extends "base.html" %}
{% block content %}
{% if form.errors %}
<div>
<ul>
{% for error in form.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ul>
</div>
{% endif %}
<form action="{% url 'users_update' user_id=user_id %}" method="post">
{% csrf_token %}
<table border="1">
{{ form.as_p }}
</table>
<input type="submit" value="Сохранить">
</form>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.IndexView.as_view(), name='users_list'),
path('signup/', views.SingUpView.as_view(), name='signup'),
path('<int:user_id>/update/', views.CustomUserUpdateView.as_view(), name='users_update'),
path('<int:user_id>/delete/', views.CustomUserDeleteView.as_view(), name="users_delete"),
path('logout/', views.view_logout, name="logout"),
]
SetPasswordForm.SetPasswordFormis just a form with some extra logic. But I don't really see why password should be in the form, if you just want to set a password toNULL/None/...?user.set_unusable_passwordto make it to some random string, and you can call it before save the form.