我有以下型号:
class Picture(models.Model):
title = models.CharField(max_length=255)
(etc)
和
class Report(models.Model):
complaint = models.TextField()
picture = models.ForeignKey('Picture')
我希望能做的是 a)在“图片”ModelView模板中包含报表ModelForm b)使用相关图片预先填充报表Modelform中的图片字段
我一直在搞乱上下文处理器,包含标签并试图通过查询字符串将变量传递给新页面,但它们看起来都非常复杂并且无法正常工作。
我想要帮助的是理解最“django”的方式,以及完成任务的任何指示。
解决方案
在Scott的帮助下,工作解决方案是:
views.py
def picture(request, slug):
picture = Picture.objects.get(slug=str(slug))
d = dict(picture=picture, form=ReportPicture())
d.update(csrf(request))
if request.method == 'POST':
form = ReportPicture(request.POST)
if form.is_valid():
report = form.save(commit=False)
report.picture = picture
report.save()
return redirect(picture.get_absolute_url())
return render_to_response("picture_detail.html", d)
答案 0 :(得分:0)
我相信你想要内联表单集(docs)。
# models.py
class Picture(models.Model):
title = models.CharField(max_length=255)
class Report(models.Model):
complaint = models.TextField()
picture = models.ForeignKey('Picture')
# views.py
from django.forms.models import inlineformset_factory
from .models import Picture, Report
def manage_picture(request, pk):
picture = Picture.objects.get(pk=pk)
ReportInlineFormSet = inlineformset_factory(Picture, Report)
if request.method == "POST":
formset = ReportInlineFormSet(request.POST, request.FILES, instance=picture)
if formset.is_valid():
formset.save()
return HttpResponseRedirect(picture.get_absolute_url())
else:
formset = ReportInlineFormSet(instance=picture)
return render_to_response("manage_picture.html", {"formset": formset})
如果您使用的是基于类的视图,Django本身不提供任何内联formset支持,但有一个excellent app that handles most of this for you called django-extra_views
.