简体   繁体   中英

Django - What CBV should I use for my case?

First of all, I want to say that I'm really a novice with Django, and looking for some architectural advice for my project.

I have a front-end template that looks like this: 在此处输入图片说明

When a user clicked "save" button, data in the input fields needs to be saved into a database. The users will be constantly updating these input fields with new values, and there will be a case where none of these data is present in the database, because the user hasn't filled them out yet. The problem is, I am not sure what view method to use.

views.py

class BhaCreateView(CreateView):
    model = models.bha
    fields = '__all__'
    context_object_name = 'bha'
    template_name = 'base/bha.html'

This just a really rough code that I made just ask a question here. I'm aware that there are many kind of class-based-views, such as DetailView, ListView, CreateView, UpdateView... and many more. Which one, or ones should I use for my purpose? I'm thinking that I need some combination of CreateView and UpdateView, since the users will be updating new information to BHA section, but there still are chances that information was not inserted in the first place at all.

How should I do this?

Usually you should have both a CreateView and an UpdateView .

So if the user initially wants to create a BHA by clicking the link Add new BHA he should be directed to a url yourDomain.com/bha/create that will be handled by a CreateView . When he saves that he should be re-directed to another url yourDomain.com/bha/1/edit that will be handled by an UpdateView where the 1 in the url is the primary key of the newly created database entry. Updates to that instance can only be made through that url.

Both views can usually use about the same template but the UpdateView will initially fill the form with data from the model instance identified by the id in the url.

So your url config could look like this:

urlpatterns = [
    url(r'^bha/', include([
        url(r'^create/$', BHACreateView.as_view(), name='create'),
        url(r'^(?P<pk>\d+)/edit/$', BHAUpdateView.as_view(), name='update'),
    ], namespace='bha')),

    # other urls ...
]

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