如何在模板中设置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']
它不起作用(原始文本):
<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>
我的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
答案 0 :(得分:2)
在视图中实例化表单后,您需要设置表单字段的the initial
property。像这样:
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
答案 1 :(得分:1)
<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='{{ comment_form.who }}' %}
{% render_field comment_form.image class="form-control form-control-sm" value='{{ comment_form.image }}' %}
<input class="btn btn-primary btn-sm" type="submit" value="Add comment">
</form>
答案 2 :(得分:0)
这是一个古老的问题,但我会尽我所能来帮助那些有需要的人。 您可以在视图中动态设置初始值
Django文档中的链接:https://docs.djangoproject.com/en/3.1/ref/forms/api/#dynamic-initial-values
使用initial在运行时声明表单字段的初始值。例如,您可能想用当前会话的用户名填写用户名字段。
要实现此目的,请对Form使用初始参数。如果提供此参数,则应为将字段名称映射到初始值的字典。仅包括您要为其指定初始值的字段;不必在表单中包含每个字段
例如
comment_form = CommentForm(initial={'who ': request.user.profile.pk})
答案 3 :(得分:0)
您可以执行以下操作。这是一种纯HTML方法。 在from内添加
<input type="hidden" name="content" value="{{value}}">
将field
放在name
属性内,并将值设置为value
属性内所需的任何内容。