如何通过表单传递用户

时间:2013-05-06 14:58:12

标签: django django-models django-views

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

在views.py中,form.is_valid()没有发生,因为用户没有通过表单传递。通过表单我可以通过什么方法传递用户。我在谷歌中搜索相同,没有任何想法。请帮助我。

2 个答案:

答案 0 :(得分:1)

初始化表单时可以执行此操作:

phoneForm = PhoneForm({'user':request.user.id})

这样您就可以将提出请求的用户传递给表单。

这是完整的方法:

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/')

希望它有所帮助。

答案 1 :(得分:0)

切换一些可以解决您的问题

def add_phone(request):
    if request.method == 'POST':        
        phoneForm = PhoneForm(request.POST)
        phoneForm.user = request.user #if a phone has a user and a form has a     
        if phoneForm.is_valid():
            phone = phoneForm.save(commit=False)
            phone.save()
        return redirect('/member/contact-list/')

我重构了很多,因为你有一些冗余的代码。 我删除了对request.user

的大多数引用