Django: How to set a hidden field on a generic create view?

前端 未结 3 1340
情深已故
情深已故 2021-01-06 09:31

I\'m running Django 1.6.x

To extend my user I\'ve added another model storing the data:

class UserProfile (models.Model):
    user = models.ForeignK         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-06 09:59

    You can do it that way:

    • get user from request object.
    • overwrite form_valid method on your UserProfileCreateView class,
    • attach user to form instance and save it.
    class UserProfileCreateView(CreateView):
        model = UserProfile
        fields = ['height']
    
         def form_valid(self, form):
             user = self.request.user
             form.instance.user = user
             return super(UserProfileCreateView, self).form_valid(form)
    

    This code is for Python 2.7.x

提交回复
热议问题