How to set a field of the model in view using generic views?

后端 未结 2 2042
余生分开走
余生分开走 2021-02-06 17:28

I have a model, which has an author ForeignKey, as such:

class Appointment(models.Model):
    # ...
    author = models.ForeignKey(User)
         


        
2条回答
  •  太阳男子
    2021-02-06 17:57

    The following seem slightly simpler. Note that self.request is set in View.as_view

    class AppointmentCreateView(CreateView):        
        model=Appointment
        form_class = AppointmentCreateForm
    
        def get_form(self, form_class):
            form = super(AppointmentCreateView, self).get_form(form_class)
            # the actual modification of the form
            form.instance.author = self.request.user
            return form
    

提交回复
热议问题