9

I used Django's generic createview for my model

from myproject.app.forms import PersonForm
class PersonMixin(object):
    model = Person
    form_class = PersontForm

class PersonCreateView(PersonMixin, CreateView):
    pass

This works perfectly for displaying a create view of Person with my custom form. However, I have a field in the form that I want to pre-populate with a value. I found this answer: Set initial value to modelform in class based generic views

However, my pre-populated value comes from the profile for request.user. How do I access the request in PersonCreateView and pass that to the form?

Community
  • 1
  • 1
rsp
  • 811
  • 2
  • 12
  • 32

2 Answers2

40

In any of the class methods you can access the request using self.request. So your user profile will be accessible with self.request.user.

Building on the link you provided you will be able to use self.request.user in your get_initial method to set the value.

ie.

def get_initial(self):
    return { 'value1': self.request.user }
jondykeman
  • 6,172
  • 3
  • 23
  • 22
3

First off, you don't need to use a mixin there. Just specify the form_class in PersonCreateView; model is not needed either, since you are already specifying it in the form_class (assuming is a subclass of ModelForm).

About where to get the request from, class based views save it in the object, so you can do self.request.user inside get_initial or get_form_kwargs.

Facundo Olano
  • 2,492
  • 2
  • 26
  • 32
  • I actually use this PersonMixin in other generic views which is why its separated, but I appreciate the advice and I didn't know i could forgo model since i'm specifying form_class. – rsp Nov 01 '12 at 15:39
  • Yes, I figured that out after posting, but still I'd advice against using Mixins like that unless totally necessary (with class based views is not uncommon to need them, but if it's just to reuse a couple of attribute definitions then it's not worth it). – Facundo Olano Nov 01 '12 at 15:54
  • why do you say that? i never gave much though to the downside but maybe i'm missing something? – rsp Nov 01 '12 at 16:24
  • 1
    Multiple inheritance is generally not a good idea (although very useful in particular cases): it adds complexity to the code, making it less readable, and sometimes producing non intuitive behavior. So as rule of thumb, I prefer not to use it unless I have a good reason to do so. – Facundo Olano Nov 01 '12 at 16:42