我已经找到了一些例子,但是我想知道对我的案子最好的用途是什么。
基本上,我有一种形式:用于更改用户密码和更新会话哈希(我认为那是PasswordChangeView的工作方式),以及另一种形式,用于更改用户数据,例如用户名和国家/地区。
我试图通过返回相同URL的多个视图来执行此操作,但是我失去了对字段的控制,并且仍然有些不一致,因为成功后它只会重定向到同一页面,所以我想用户始终停留在同一页面上。
有任何使用技巧吗?
我认为我可以使用函数安静地执行此操作,但是它的代码非常code肿,我正在寻找一种更“干净”的替代方法。
ps:我的观点:
class PasswordChangePage(
SuccessMessageMixin, LoginRequiredMixin, auth_views.PasswordChangeView
):
"""
Change password and return redirect
"""
template_name = "users/registration/password_change.html"
success_url = reverse_lazy("users:settings")
success_message = "password changed"
和
class UserEditPage(LoginRequiredMixin, generic.View):
def get(self, request, *args, **kwargs):
template_name = "users/registration/update.html"
form = ProfileUpdateForm(instance=request.user)
context = {"form": form}
return render(request, template_name, context)
def post(self, request, *args, **kwargs):
form = ProfileUpdateForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
messages.add_message(
request, messages.SUCCESS, "profile updated"
)
return redirect("users:settings")
表格:
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth import get_user_model
User = get_user_model()
class ProfileCreationForm(UserCreationForm):
# have default fields: password1/2
class Meta:
model = User
fields = ("username", "email", "country")
class ProfileUpdateForm(UserChangeForm):
# have only 3 fields to update
class Meta:
model = User
fields = ("username", "email", "country")