Register form in class based views

喜欢而已 提交于 2019-12-13 03:44:21

问题


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

function based view

    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 based VIew

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

回答1:


You can override the post function of that generic view.

Example:

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):

will be trigger if you request is POST.

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

Will trigger if your request is post.



来源:https://stackoverflow.com/questions/51371675/register-form-in-class-based-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!