Extending Django's Generic Views

前端 未结 2 1705
梦谈多话
梦谈多话 2021-01-02 03:27

I\'m writing my first app in Django, and I have a problem with the create_object Generic View; In my urls.py, I have:

(r\'^new$\',          


        
相关标签:
2条回答
  • 2021-01-02 03:52

    You can do this by overriding the get_form method:

    from django.views.generic import CreateView
    
    class CustomCreateView(CreateView):
        def get_form(self, form_class):
            form = super(CustomCreateView, self).get_form(form_class)
            form.instance.user = self.request.user
            return form
    

    EDIT: Nowadays I would override form_valid as per Issac Kelly's answer:

    from django.views.generic import CreateView
    
    class CustomCreateView(CreateView):
        def form_valid(self, form):
            form.instance.user = self.request.user
            return super(CustomCreateView, self).form_valid(form)
    
    0 讨论(0)
  • 2021-01-02 04:09

    You want to override the form_valid method.

    0 讨论(0)
提交回复
热议问题