2

我使用 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

4

1 回答 1

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)
于 2013-02-06T17:19:13.703 回答