繁体   English   中英

如何设置作为对象引用的初始值

[英]How to set initial value that is reference to an object

我们试图将对象设置为初始值(图像,它是图像的外键)。 我们只是不能让它工作,我们总是得到 NULL/空白值。 谢谢你的帮助!

来自views.py

    def create_comment(request, image_id):
        image = Image.objects.get(id = image_id)
        if request.method == 'POST':
            form = CreateComment(request.POST, initial={'image':image})
            if form.is_valid():
                form.save()
        else:
            form = CreateComment()
        return render(request, 'ImagePost/create_comment.html', {'form':form, 'image_id':image_id})

来自forms.py

    class CreateComment(forms.ModelForm):
        class Meta:
            model = Comment
            fields = ['user', 'text']

来自 create_comment.html

    <html>
    <body>
    <h1>Add comment</h1>
    <form action="{% url 'create_comment' image_id %}" method="POST">
    {% csrf_token %}
    <table>
    {{ form.as_table }}
    </table>
    <input type="submit" value="Add">
    </form>
    </body>
    </html>

从 Django 1.9 开始, disabled参数完全符合您的要求:

disabled 布尔参数设置为 True 时,会使用 disabled HTML 属性禁用表单字段,以便用户无法对其进行编辑。 即使用户篡改了提交给服务器的字段值,它也会被忽略,取而代之的是表单初始数据中的值。

简单的例子:

class CreateComment(forms.ModelForm):    
    image = forms.ModelChoiceField(queryset=Image.objects.all(), disabled=True)

    class Meta:
        model = Comment
        fields = ['user', 'text', 'image']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM