Django: How to set a hidden field in a generic view of a creation?

I am running Django 1.6.x

To expand my user, I added another data storage model:

class UserProfile (models.Model):
    user = models.ForeignKey(User)
    height = models.IntegerField(blank=True, null=True)

Now I made a wand to add a view that allows the user to add their information to it. django.views.generic.edit.CreateViews django.views.generic.edit.CreateView, but you also want to provide at least django.views.generic.edit.CreateViewediting / updates.

So I added import and created a view:

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

I also added an entry inside urls.py:

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

But now I am fixated on how to assign a user ID correctly. I want this field to be set in the background. Any hints?

+4
source share
2 answers

You can do it as follows:

  • .
  • form_valid UserProfileCreateView,
  • .
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)

Python 2.7.x

+12
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)
+2

All Articles