【问题标题】:Django comments framework, set default form valuesDjango 评论框架,设置默认表单值
【发布时间】:2011-11-21 15:10:14
【问题描述】:

我在 forms.py 中定义了一个自定义评论表单作为休闲方式

类 CommentFormWithReply(CommentForm): reply_to = forms.ModelChoiceField(queryset=CommentWithReply.objects.all(), 小部件=forms.HiddenInput(),必需=假) def get_comment_model(self): # 使用我们的自定义评论模型而不是内置的。 返回 CommentWithReply def get_comment_create_data(self): # 使用超类的数据,并在title字段中添加 data = super(CommentFormWithReply, self).get_comment_create_data() 返回数据

如何以当前用户信息作为默认值(姓名、电子邮件、网页)呈现此表单。

【问题讨论】:

    标签: django forms comments


    【解决方案1】:

    可能是这样的:

    https://docs.djangoproject.com/en/dev/ref/forms/fields/#initial

    if request.method == 'POST':
        form = CommentFormWithReply(request.POST)
        .........................................
    
    
    if request.method == 'GET':
        default_data = {'name': 'Alexey', 'email': 'smt@email.smt', 'webpage': 'http://example.com'}
        form = CommentFormWithReply(default_data)
    

    【讨论】:

    • 我第一次渲染表单时需要这样做,并且我想使用来自经过身份验证的用户的数据
    • 如果 request.method == 'GET': default_data = {'name': request.user.first_name, 'email': request.user.email, 'webpage': your.custom_field.from .userprofile} 表单 = CommentFormWithReply(default_data)
    • 或者你可以在 CommentFormWithReply 中完成
    猜你喜欢
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    相关资源
    最近更新 更多