Q:

How to pass user through form

views.py
def add_phone(request):
    phoneForm = PhoneForm()
    user = request.user
    phone = Phone_info.objects.get(user=2)
    phoneForm = PhoneForm(instance=phone)    
    phone.user=request.user
    if request.method=='POST':        
        phoneForm = PhoneForm(request.POST,request.user,instance=phone) 
        user=request.user       
        if phoneForm.is_valid():
            phone=phoneForm.save(commit=False)
            phone.user=request.user 
            phone.save()
        return redirect('/member/contact-list/')

models.py
class Phone_info(models.Model):
    user = models.ForeignKey(User, null=True)
    name1 = models.CharField('Name', max_length=100, null=True, blank=True)

forms.py
class PhoneForm(forms.ModelForm):

    class Meta:
        model = Phone_info

In views.py the form.is_valid() is not happening since the user is not pass in form.By what method i can pass the user through form.I am searching the same in google,not getting any idea.Please help me with this.

A:

You may do this when you initialize the form:
phoneForm = PhoneForm({'user':request.user.id})

That way you're passing the user who made the request to the form.
Here's the full method:
def add_phone(request):
    user = request.user
    phoneForm = PhoneForm({'user':user.id})
    if request.method=='POST':        
        phoneForm = PhoneForm(request.POST) 
        if phoneForm.is_valid():
            phone=phoneForm.save(commit=False)
            phone.save()
        return redirect('/member/contact-list/')

Hope it helps.

