离开PHP之前的三个问题:Formsets,datasources和remote auth

时间:2010-04-13 11:03:25

标签: django cakephp migration django-forms

我一直在使用CakePHP很长一段时间,并且觉得用它开发网站很舒服。然而,我更喜欢Python而不是PHP,并希望转移到Django。

编辑:分成三个单独的问题

如何在一个表单中混合多个模型?我知道formsets用于此,但我找不到一个体面的教程(视图+模板)。在Cake中我可以在我的视图(模板)中简单地使用它:

echo $this->Form->input('User.title');
echo $this->Form->input('Profile.website');
echo $this->Form->input('Comment.0.title');
echo $this->Form->input('Comment.1.title');

这将混合用户模型,配置文件模型并在一个表单中添加两个注释。如何用Django做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:2)

关于第1部分,这比你想象的容易得多:

<强> forms.py

class UserForm(forms.ModelForm):
    pass ## Using pass so I don't have to write the whole thing.

class ProfileForm(forms.ModelForm):
    pass

class CommentForm(forms.ModelForm):
    pass

<强> views.py

def view_forms(request):
    userform = UserForm()
    profileform = ProfileForm()
    comment1 = CommentForm()
    comment2 = CommentForm()
    if request.method = "POST":
        ## Process forms here.  Yes, I'm lazy.
    return render_to_response("template.html",
                locals(),                       
                context_instance=RequestContext(request))

<强> template.html

<form method="POST">
    {{ userform.as_p }}
    {{ profileform.as_p }}
    {{ comment1.as_p }}
    {{ comment2.as_p }}
</form>