user2979885
user2979885

Reputation: 1

Using Django CreateView how can I access the request.session.user variable?

class ViewCreate(CreateView):
  model = view_C    
  author_name = self.request.user.username #this is the error
  author = get_user_model().objects.get(username=author_name).pk
  publish_date = datetime.date.today()

  initial={
'author':author,
'publish_date':publish_date,
}

author_name = self.request.user.username ...

NameError: name 'self' is not defined

How do I access the request.user variable from within a subclass of CreateView? I am trying to make use of a CreateView were the entries for author are automatically filled in using the session data and so don't have to be manaully entered.

Upvotes: 0

Views: 1293

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599788

You can't do this at that point. If you want to pass dynamic initial data based on the request, you need to do it by defining a get_initial method.

Note however the query you are doing is completely pointless. request.user is already an instance of the User model. There is no point getting the username from that object and then passing it into another query based on that username; you just get back the object you started with. Just use request.user.

class ViewCreate(CreateView):
    model = view_C    

    def get_initial(self):
        return {
             'author': self.request.user,
             'publish_date': datetime.date.today()
        }

Upvotes: 3

Related Questions