Django如何设置模板中隐藏输入的值

Bar*_*rka 8 python django

如何在模板中设置who和的值?image

class CommentForm(ModelForm):
    who = forms.CharField(widget=forms.HiddenInput())
    image = forms.ImageField(widget=forms.HiddenInput())

    class Meta:
        model = Comments
        fields = ['who', 'image', 'content']
Run Code Online (Sandbox Code Playgroud)

它不起作用(原始文本):

<form method='POST' action=''>
    {% csrf_token %}
    {% render_field comment_form.content class="form-control form-control-sm" placeholder='Comment..' %}
    {% render_field comment_form.who class="form-control form-control-sm" value='{{ request.user.profile.pk }}' %}
    {% render_field comment_form.image class="form-control form-control-sm" value='{{ image.pk }}' %}
    <input class="btn btn-primary btn-sm" type="submit" value="Add comment">
</form>
Run Code Online (Sandbox Code Playgroud)

我的views.py

class ProfileView(DetailView):
    comment_form = CommentForm()
    queryset = Profile.objects.all()
    context_object_name = 'me'
    template_name = 'profile.html'

    def get_context_data(self, **kwargs):
        context = super(ProfileView, self).get_context_data(**kwargs)
        context['comment_form'] = self.comment_form
        return context
Run Code Online (Sandbox Code Playgroud)

Yel*_*ark 6

在视图中实例化表单后,您需要设置表单字段的属性initial就像这样:

class ProfileView(DetailView):
    comment_form = CommentForm()
    queryset = Profile.objects.all()
    context_object_name = 'me'
    template_name = 'profile.html'

    def get_context_data(self, **kwargs):
        context = super(ProfileView, self).get_context_data(**kwargs)
        context['comment_form'] = self.comment_form
        # This sets the initial value for the field:
        context['comment_form'].fields['who'].initial = self.request.user.profile.pk
        return context
Run Code Online (Sandbox Code Playgroud)