简体   繁体   中英

How to set model field automatically in CreateView? (Django)

class PetAddView(CreateView):
    model = Pet
    fields = ['name','animal_type','breed','color','age','height','price','city','sex','photo']
    template_name = 'pets/pet-add.html'

There's my create view.

My goal is to provide view with functionality to create record in database. Bu I don't need my users to specify slug instead I need to set it automatically from specified "name" value.

Can I?

Yes, you can do absolutely anything in the form_valid method. The trick is

def form_valid( self, form):

    instance = form.save( commit = False)
    # define the slug and any other programmatically generated fields
    instance.slug = whatever
    instance.save()

    return HttpResponseRedirect( self.get_success_url())

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