Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.ForeignKey(User)
    height = models.IntegerField(blank=True, null=True)

Now I wand to add a view, which is allowing the user to add its own infos there. Started with django.views.generic.edit.CreateView, but want also to provide at least the edit/update one to.

So I've added the import and created a view:

from django.views.generic.edit import CreateView, UpdateView
# .... 
class UserProfileCreateView(CreateView):
    model = UserProfile
    fields = ['height']

Also I've added the entry inside urls.py:

    url(r'^userprofile/new/$', login_required(UserProfileCreateView.as_view()), name="add_userprofile")

But now I'm stuck on the point how to assign the user ID in the correct way. I want to have this field set in background. Any hints?

like image 950
frlan Avatar asked Feb 08 '14 21:02

frlan


2 Answers

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

like image 126
Lukas Kozlowski Avatar answered Sep 18 '22 01:09

Lukas Kozlowski


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)
like image 20
vadimchin Avatar answered Sep 18 '22 01:09

vadimchin