Django - 使用表单在 django admin 之外自动填充 created_by 字段 [英] Django - Auto populate created_by field outside django admin using form

查看:38
本文介绍了Django - 使用表单在 django admin 之外自动填充 created_by 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要求用户通过填写​​由 modelformset_factory 创建的表单,在 django 管理员之外创建一个新实例.问题是我不知道如何将 request.user 传递给表单,因此在保存表单时 created_by 字段无效.

The users are asked to create a new instance outside the django admin by filling a form created by the modelformset_factory. The problem is that I dont know how to pass request.user to the form so the created_by field is not valid when the form is saved.

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

推荐答案

您可以在保存实例之前自行设置 created_by 字段.

You can set the created_by field yourself before saving the instance.

做这样的事情:

if formset.is_valid():
    instances = formset.save(commit=False)
    for instance in instances:
        instance.created_by = request.user
        instance.save()

关于此功能的文档是 这里.

The documentation about this feature is here.

这篇关于Django - 使用表单在 django admin 之外自动填充 created_by 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆