1

I might be a noob question but... is there a way of using request in models.py?

Something like:

class MyModel (models.Model): User = models.ForeignKey(default=request.user) ...other fields... 

Or maybe using the post_init method for doing this job.

Thanks.

1
  • The request should really only be used in the view; if you feel you need the request, there is probably an easier or better way. What specifically are you trying to do? Commented Sep 9, 2011 at 19:14

1 Answer 1

3

That specific example you gave it's not useful in Django. Request do have a context with them (the context where the HTTP happened) so it could or could not be available when you instantiate MyModel.

You can do in your view:

def index(request): myModel = MyModel(request.user) 

And in your model:

class MyModel (models.Model): user = models.ForeignKey(User) def __init__(self, pUserName): self.user = User.objects.get(userName=pUserName) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.