I have this form.py:
from shortcut import get_timezone
class HostCreateForm(forms.ModelForm):
def save(self, commit=True):
host1 = super(HostCreateForm, self).save(commit=False)
user = request.user.username
host1.timezone=get_timezone(user=user)
host1.save()
return host1
class Meta:
model = Host
widgets = {
'user': forms.HiddenInput(),
'timezone': forms.HiddenInput()
}
- timezone is an input hidden field from Host model defined in model.py.
- get_timezone method: (definition as following)
def get_timezone(user=None):
timezone = Userprofile.objects.all()
timezone = timezone.get(user=user)
return timezone.timezone
whereas UserProfile is another model also defined in models.py which is used to store the timezone , first name and last name of a user at the time of his/her registration. My main motive is to get this default timezone from Userprofile model and pass it to that hidden input field (timezone).
I tried with the above code (host1.timezone=get_timezone(user=user) written in save method which call the get_timezone method and it should return the timezone form Userprofile model for a loginned user but it didn’t work.
I think the main problem are coming with the passing the name of requesting user at the time of calling get_timezone methos from save method. I am not able to do that. From the current scenario i am getting the following error:
global name ‘request’ is not defined
Any help will be appreciable
timezone.filter(...)will return you a queryset, and you can not call.timezoneon a queryset. You must get the related object by either usingget:or by list slicing:
UPDATE: Ok, i just notice it.
Problem is, you can not pass a request object to a form’s
savemethod. Best way to deal with the problem is doing it in your view layer.In your view:
And you remove the parts that sets the user from your
savemethod.