要求用户填写由modelformset_factory创建的表单,在django admin之外创建一个新实例。问题是我不知道如何将request.user传递给表单,因此在保存表单时created_by字段无效。
models.py:
from django.db import models
from django.contrib.auth.models import User
class ezApp(models.Model):
name = models.SlugField(max_length=50, unique=True )
date_created = models.DateTimeField('date created', auto_now_add=True)
date_updated = models.DateTimeField('date updated', auto_now=True)
created_by = models.ForeignKey(User)
in_use = models.BooleanField()
views.py
from django.shortcuts import render_to_response
from ezmapping.models import *
from django.forms.models import modelformset_factory
def setName(request):
ezAppFormSet = modelformset_factory(ezApp, extra=1, fields=('name'))
formset = ezAppFormSet(queryset=ezApp.objects.none())
if request.method == 'POST':
formset = ezAppFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
return render_to_response("project/manage_new.html", {'formset': formset, 'title': "New"}, context_instance=RequestContext(request))
答案 0 :(得分:4)
您可以在保存实例之前自己设置created_by
字段。
做这样的事情:
if formset.is_valid():
instances = formset.save(commit=False)
for instance in instances:
instance.created_by = request.user
instance.save()
有关此功能的文档为here。