在基于类的视图中注册表单 [英] Register form in class based views

查看:65
本文介绍了在基于类的视图中注册表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在基于类的视图(CreateView)中编写以下基于函数的视图

How to write the below function based view in Class Based View(CreateView)

基于函数的视图

    def register(request):
        registered = False
        if request.method == 'POST':
            user_form = UserForm(data = request.POST)
            profile_form = UserProfileInfoForm(data = request.POST)
            if user_form.is_valid() and profile_form.is_valid():
                user = user_form.save()
                user.set_password(user.password)
                user.save()
                profile = profile_form.save(commit=False)
                profile.user = user
                if 'profile_pic' in request.FILES:
                    profile.profile_pic = request.FILES['profile_pic']
                profile.save()
                registered = True
            else:
                print(user_form.errors,profile_form.errors)
        else:
            user_form = UserForm()
            profile_form = UserProfileInfoForm()
        return render(request,'app_one/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered })

基于类的视图

class register(CreateView):
    model = userinfo, UserProfileInfo
    form_class = Userinfoform, UserProfileInfoForm


推荐答案

您可以覆盖该通用视图的 post 功能。

You can override the post function of that generic view.

示例:

def post(self, request, *args, **kwargs):
        user_form = UserForm(data = request.POST)
        profile_form = UserProfileInfoForm(data = request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']
            profile.save()
            registered = True
        else:
            print(user_form.errors,profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()
    return render(request,'app_one/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered })

如果要检查视图的所有可用功能,可以转到其核心文件夹。

If you wanted to check all the available function for the view, you can go to its core folder.

def post(self,request,* args,** kwargs):

如果您的请求是POST,将被触发。

will be trigger if you request is POST.

def get(self,request,* args,** kwargs):

如果您的请求已发布,则会触发。

Will trigger if your request is post.

这篇关于在基于类的视图中注册表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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