简体   繁体   中英

in Django, how to implement CreateView's function with based-function views?

here is based-class views code:

# views.py
class ObjectCreate(CreateView):
    model = ObjectModel
    fields = "__all__"

its simple to create an object and save it use this class.

I wonder how?

what if I want to use based-function views to achieve it?

Using a function view you would need to implement everything, including creating a form for your model :

def create_object(request):
    if request.method == 'GET':
        form = ObjectForm()

    if request.method == 'POST':
        form = ObjectForm(request.POST)
        if form.is_valid():
            instance = form.save()  # instance created
            # now redirect user or render a success template
            return redirect(...)

    # if request method is GET or form is invalid return the form
    return render(request, 'path/template_name.html', {'form': form})

If you want to learn how the CreateView works, look at its source code. Or for easier overview of the structure, look at this site which lists all the Django CBVs.

You'll find that CreateView inherits from 9 other classes, has about 20 attributes (of which model and fields ) and 24 methods that you can override to customise its behaviour.

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