简体   繁体   中英

Django functional Based view to FormView

I have my code written in functional-based views and I came to know about the generic views which are built into Django. I have made changes using Views, TemplateViews but I got stuck at FormView.

Functional Based View:

def NewTeam(request):
    form = NewTeamForm()
    if request.method == 'POST':
        form= NewTeamForm(request.POST, request.FILES)

        if form.is_valid():
            form.save(commit = True)
            return teams(request)
        else:
            print("Invalid Form")
    return render(request,'teamform.html', {'form':form})

FormView I tried

class NewTeam(FormView):
    template_name = 'teamform.html'
    form_class = NewTeamForm
    success_url = '.'

    def get_context_data(self,**kwargs):
        context = super(NewTeam, self).get_context_data(**kwargs)
        form = NewTeamForm()
        if request.method == 'POST':
            form= NewTeamForm(request.POST, request.FILES)

            if form.is_valid():
                form.save(commit = True)
                return teams(request)
            else:
                print("Invalid Form")
        context['form'] =form
        return context     

I can understand that I need to get the context in the first function and create a new function form_valid . I have seen the documentation and other stack answers but I couldn't get it like how to validate the form with in it. Thanks in Advance.

Django FormView automatically calls validation on the form

from django.http import HttpResponseRedirect


class NewTeam(FormView):
    template_name = 'teamform.html'
    form_class = NewTeamForm
    success_url = '.'

def form_valid(self, form):
    # Form is Valid
    new_team = form.save(commit=True)

    # Do whatever

    return HttpResponseRedirect(self.get_success_url())

def form_invalid(self, form):
    # Form is Invalid
    print(form.errors)

    return self.render_to_response(self.get_context_data(form=form))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM