Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

request.user in Django model

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?

like image 908
ng150716 Avatar asked Sep 08 '14 02:09

ng150716


1 Answers

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 ...
like image 82
ruddra Avatar answered Oct 13 '22 07:10

ruddra