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?
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With