我想使用formset来编辑模型中的所有记录'类别'。我想知道如何解决两个问题:
models.py
class Category(models.Model):
ORDER = (
('1', '1'),
('2', '2'),
('3', '3'))
id = models.AutoField(primary_key=True)
language = models.ForeignKey(Language, null=False, blank=False)
name = models.CharField(max_length=256, null=False, blank=False)
parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
slug = models.SlugField(unique=True, blank=False, null=False)
order = models.SmallIntegerField(null=True, blank=True, choices=ORDER)
allow_replies = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now=True)
# Forms
class CategoryForm(ModelForm):
class Meta:
model = Category
fields = ['language', 'name', 'parent', 'allow_replies', 'order']
views.py
def category_formset(request):
if is_admin_user(request):
CategoryFormSet = formset_factory(CategoryForm)
if request.method == 'POST':
formset = CategoryFormSet(request.POST)
if formset.is_valid():
formset.save()
else:
formset = CategoryFormSet(initial=Category.objects.values())
return render_to_response("pages/category_formset.html",
{"formset": formset, 'is_logged_in': is_logged_in(request)},
context_instance=RequestContext(request))
else:
return redirect('/', False)
html模板
<form action="/category/edit/" method="post">
{% csrf_token %}
<table>
<tr>
<td>Language</td>
<td>Name</td>
<td>Parent</td>
<td>Allow Replies</td>
<td>Order</td>
</tr>
{% for form in formset %}
<tr>
{% for item in form %}
<td>{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" value="Submit" />
</form>
提前致谢。
答案 0 :(得分:0)
解
<强> MODEL 强>
# ...
def category_formset(request):
if is_admin_user(request):
CategoryFormSet = modelformset_factory(Category, exclude="slug", extra=0)
if request.POST:
formset = CategoryFormSet(request.POST)
if formset.is_valid():
formset.save()
return redirect('/categories/')
else:
formset = CategoryFormSet(initial=Category.objects.values())
return render_to_response("pages/category_formset.html",
{"formset": formset, 'is_logged_in': is_logged_in(request)},
context_instance=RequestContext(request))
else:
return redirect('/', False)
<强> TEMPLATE 强>
<form action="/category/edit/" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ formset.management_form }}
{{ formset.errors }}
<table>
<tr>
<td>Language</td>
<td>Name</td>
<td>Parent</td>
<td>Allow Replies</td>
<td>Order</td>
</tr>
{% for form in formset %}
<tr>
{% for item in form %}
<td>{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" value="Submit" />
</form>