Reputation: 11062
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()
}
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
Upvotes: 1
Views: 688
Reputation: 18737
timezone = timezone.filter(user=user)
return timezone.timezone
timezone.filter(...)
will return you a queryset, and you can not call .timezone
on a queryset. You must get the related object by either using get
:
timezone = timezone.get(user=user)
or by list slicing:
timezone = timezone.filter(user=user)[0]
UPDATE: Ok, i just notice it.
Problem is, you can not pass a request object to a form's save
method. Best way to deal with the problem is doing it in your view layer.
In your view:
my_form = HostCreateForm(request.POST):
if my_form.is_valid(): #do the validation
my_inst = my_form.save(commit=False) #pass the form values to a new model instance without saving.
my_inst.timezone = request.user.username #set the user or do whhatever you want eith the form data.
my_inst.save() #that will call your save methhod that you override.
And you remove the parts that sets the user from your save
method.
Upvotes: 2