我正在尝试使用ForeignKey字段中的值来显示CreateView中的清单。
models.py
class Structure(models.Model):
name = models.CharField(max_length = 30)
description =models.CharField(max_length = 300, null=True, blank=True)
def __str__(self):
return self.name
class SelectedFramework(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
structure = models.ForegignKey(Structure)
selected = models.BooleanField(default = False)
views.py
class FrameworkCreateView(generic.CreateView):
model = SelectedFramework
fields =['structure', 'selected']
template_name = 'catalogue/structure.html'
def form_valid(self, form):
form.instance.user = self.request.user
return super(FrameworkCreateView, self).form_valid(form)
structure.html
{% extends 'catalogue\base.html' %}
{% block container %}
<h2>{% block title %}Structures{% endblock title %}</h2>
<form action="" method="post">
{% csrf_token %}
{% for field in form %}
<div class="col-sm-10">{{form.structure}} {{form.selected}}</div><br>
{% endfor %}
</div>
</form>
{% endblock %}
上面的代码有效,但会显示ForeignKey&#39;结构&#39;作为下拉列表,其值为__str__
。有没有办法使用CreateView中structure.name
的复选框显示structure.description
和selected
的字符串?
答案 0 :(得分:0)
在您的模板中使用:
{{ form.structure.name }}
{{ form.structure.description}}
答案 1 :(得分:0)
您可以编写自定义表单,覆盖保存方法并在那里手动创建Structure
对象:
class FrameworkForm(forms.ModelForm):
structure_name = forms.CharField(required=True)
structure_description = forms.CharField(required=False)
class Meta:
model = SelectedFramework
fields = [
'structure_name', 'structure_description', 'selected'
]
def save(self, commit=False):
instance = super(FrameworkForm, self).save(commit=False)
structure = Structure(
name=self.cleaned_data.get('structure_name'),
description=self.cleaned_data.get('structure_description')
)
structure.save()
instance.structure = structure
instance.save()
return instance
同时将form_class = FrameworkForm
添加到您的视图中,而不是fields = ['structure', 'selected']
修改强>
也许你想要这样的东西:
<ul>
{% for structure in form.fields.structure.choices.queryset %}
<li>{{ structure.name }} - {{ structure.description }}</li>
{% endfor %}
</ul>
答案 2 :(得分:-1)
如果您想通过在模板中迭代来获取字段。你必须使用 -
{% for field in form %}
{{ field }}
{% endfor %}
不必使用任何点符号来获取字段。如果您想获取字段的标签,通常可以在{{ field.label}}
{{field}}