9

I am using Django models to create the fields for a form. I would like to have the user's username automatically detected in and be filled out, this way I can hide it in my form (instead of having them choose their username from a long list that has everyones username). To do this I am using:

current_user = request.user

and then setting the default to current_user. However, I keep getting this error:

NameError: name 'request' is not defined

I'm assuming you can't use requests in Django models, but is there anyway to get around this? Here is the relevant sections of my models.py file:

class StockTickerSymbol(models.Model):
    StockName = models.CharField(max_length=7, unique=True)
    current_user = request.user
    user = models.ForeignKey(User, default=current_user)

Anyone know how I can use requests in my models, or somehow call the variable current_user?

ng150716
  • 2,195
  • 5
  • 40
  • 61
  • Related or duplicate: [make the user in a model default to the current user](http://stackoverflow.com/questions/4670783/make-the-user-in-a-model-default-to-the-current-user). – alecxe Sep 08 '14 at 02:08
  • 2
    You can't use *anything*, anywhere in Python at all, unless it is somehow passed to it. – Daniel Roseman Sep 08 '14 at 06:32

1 Answers1

9

Here you haven't imported request in that model class scope. This is how you can get user:

# model

class StockTickerSymbol(models.Model):
    StockName = models.CharField(max_length=7, unique=True)
    user = models.ForeignKey(User)

    def save(self,**kwargs):
      if kwargs.has_key('request') and self.user is None:
            request = kwargs.pop('request')
            self.user= request.user
      super(StockTickerSymbol, self).save(**kwargs)

#views:

def post(self, request):
   if form.is_valid():                         
       sts=StockTickerSymbol()
       sts.StockName= form.cleaned_data['StockName']
       if form.cleaned_data['user'] is None: #null check
          sts.save(request=request)
       else:
          sts.user= form.cleaned_data['user']
          sts.save(request=request)

For modelform:

class SomeForm(forms.ModelForm):
    ...

    def save(self, commit=True ,*args, **kwargs):
        request = None
        if kwargs.has_key('request'):
            request = kwargs.pop('request')
        m = super(SomeForm, self).save(commit=False, *args, **kwargs)
        if m.user is None and request is not None:
            m.user= request.user
            m.save()

in views:

def post(self, request):
   if form.is_valid():  
      form.save(request=request)
      return ...
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Ok, I've added the `def save` bit to my models.py, but I'm not entirely sure where to add the views code. [Here](http://pastebin.com/4RJ4Adjc) is my relevant views.py file. Where exactly would the code go? – ng150716 Sep 08 '14 at 21:00
  • very helpful, thanks - needed requests to set a `message`.. though maybe I should be doing that in `post_save` anyway... – ptim Jul 15 '17 at 16:27