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

◇◆丶佛笑我妖孽 提交于 2019-12-01 06:40:54

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

class UserProfileCreateView(CreateView):
    def form_valid(self, form):
         self.object = form.save(commit=False)
         self.object.user = self.request.user
         self.object.save()
         return super(ModelFormMixin, self).form_valid(form)

To avoid gottcha's like must be a “User” instance error you would want to try this.

 def form_valid(self, form):
        owner = self.request.user
        print("Bot owner1", owner)
        tenant = get_object_or_404(Tenant, user=owner)
        print("Bot owner2 ", tenant)
        form.instance.tenant = tenant

    return super().form_valid(form)

Turned out that

print("Bot owner1", owner)

and

print("Bot owner2 ", tenant)

have different results.

Any other approach besides the form_valid method could pose a security risk. i.e I could edit the initial value by inspecting element on your browser and put my new value. If your code does not validate my entry Bang!!!Bang!! you're hacked.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!