django - 使用modelformset_factory在request.user中填充created_by字段

时间:2013-02-06 15:48:36

标签: django django-models django-forms django-views

我使用modelformset_factory创建一个空表单,但我不知道如何在视图中使用request.user填充created_by字段。我知道可以使用models.Manager来处理created_by的默认值,但我更愿意直接在当前登录用户的视图中填充它。我不关心管理界面。

这是我的models.py:

from django.db import models
from django.forms import ModelForm
from django.contrib.auth.models import User
import datetime

class ezApp(models.Model):
    name = models.SlugField(max_length=50, )
    date_created = models.DateTimeField('date created', editable=False)
    date_updated = models.DateTimeField('date updated', editable=False)
    created_by = models.ForeignKey(User)

def save(self):
    if not self.id:
        self.date_created = datetime.date.today()
    self.date_updated = datetime.datetime.today()
    super(ezApp, self).save()

class ezForm(ModelForm):
    class Meta:
        model = ezApp
        fields = ('name')

这是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))

错误讯息:

project_ezapp.created_by_id可能不是NULL

1 个答案:

答案 0 :(得分:1)

我想你可以试试:

class BaseEzAppFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(BaseEzAppFormSet, self).__init__(*args, **kwargs)

    def save_new(self, form, commit=True):
        obj = form.save(commit=False)
        obj.created_by = self.user
        if commit:
             obj.save()
        return obj
...
ezAppFormSet = modelformset_factory(ezApp, extra=1, fields=('name'), 
    formset=BaseEzAppFormSet)
...
formset = ezAppFormSet(request.POST, request.FILES, user=request.user)