将基于函数的视图转换为只有表单而没有模型(对象)的基于类的视图 [英] Converting a function based view to a class based view with only a form and no model (object)

查看:28
本文介绍了将基于函数的视图转换为只有表单而没有模型(对象)的基于类的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,这是在用户配置文件中更改密码的方式.知道不涉及模型,将其转换为基于类的视图的最佳方法是什么?

Right now, this is how the password is changed within a user profile. What is the best way of converting this to a class based view knowing that there is no model involved?

这是修改密码的视图

@login_required
def profile_change_password(request):
    """ 
    Change password of user.
    """
    user = get_object_or_404(User, username__iexact=request.user.username)

    if request.method == 'POST':
        form = PasswordChangeFormPrivate(user=user, data=request.POST)
        if form.is_valid():
            form.save()                       
            messages.add_message (request, messages.INFO, 
                                _('password changed'))
            return HttpResponseRedirect(reverse('profile_view_details'))
    else:
        form = PasswordChangeFormPrivate(user=request.user)

    return render_to_response('profiles/profile_change_password.html',
                              { 'form': form,},
                              context_instance=RequestContext(request)
                             )

这是修改密码的表格

class PasswordChangeFormPrivate(PasswordChangeForm):
    def __init__(self, *args, **kwargs):
        super(PasswordChangeForm, self).__init__(*args, **kwargs)

    def clean_new_password2(self):
        password1 = self.cleaned_data.get('new_password1')
        password2 = self.cleaned_data.get('new_password2')
        if password1 and password2:
            if password1 != password2:
                raise forms.ValidationError(_("The two password fields didn't match."))

        min_len = getattr(settings, "PASSWORD_MINIMUM_LENGHT", 6)
        if len(password1) < min_len:
            raise forms.ValidationError(_("Password too short! minimum length is ")+" [%d]" % min_len)

        return password2

这是网址

url(r'^password/change/$',
    profile_change_password,
    name='profile_change_password'
),

如您所见,不涉及任何模型,因为密码将在验证时替换用户"密码字段.将其转换为基于类的视图的任何简单方法?重要吗?

As you see no model is involved as the password will replace "User" password field up on validation. Any simple way of converting this to a class-based view? Does it matter?

推荐答案

不需要涉及模型——你可以使用 FormView.它看起来像这样:

There doesn't need to be a model involved -- you can use a FormView. It would look something like this:

from django.core.urlresolvers import reverse
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views.generic.edit import FormView

from myapp.forms import PasswordChangeFormPrivate

class ProfileChangePassword(FormView):
    form_class = PasswordChangeFormPrivate
    success_url = reverse('profile_view_details')
    template_name = 'profiles/profile_change_password.html'

    def get_form_kwargs(self):
        kwargs = super(ProfileChangePassword, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

    def form_valid(self, form):
        form.save()
        messages.add_message(self.request, messages.INFO, _('profile changed'))
        return super(ProfileChangePassword, self).form_valid(form)

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(ProfileChangePassword, self).dispatch(*args, **kwargs)

我不知道你为什么有

user = get_object_or_404(User, username__iexact=request.user.username)

无论如何您都需要登录表单,因此 request.user 保证是有效用户.

You require login for the form anyway, so request.user is guaranteed to be a valid user.

这篇关于将基于函数的视图转换为只有表单而没有模型(对象)的基于类的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆