admin auto从请求中填充用户字段

时间:2011-08-11 23:54:38

标签: django

我已经创建了一个django管理表单来向模型添加新字段并更新通用模型,我的代码如下。它的全部工作完全接受保存当前登录用户。在save()方法中,我无法访问request.user来填充created_by字段。

class EventAdminForm(forms.ModelForm):
    tag_it   = forms.CharField(max_length=100)

    class Meta:
        model = Event

    # Step 2: Override the constructor to manually set the form's latitude and
    # longitude fields if a Location instance is passed into the form
    def __init__(self,  *args, **kwargs):
        super(EventAdminForm, self).__init__(*args, **kwargs)

        # Set the form fields based on the model object
        if kwargs.has_key('instance'):
            instance = kwargs['instance']
            self.initial['tag_it'] = ', '.join([i.slug for i in instance.tags.all()])



    def set_request(self, request):
        self.request = request
    # Step 3: Override the save method to manually set the model's latitude and
    # longitude properties based on what was submitted from the form
    def save(self, commit=True):
        model = super(EventAdminForm, self).save(commit=False)

        for i in self.cleaned_data['tag_it'].split(','):
            model.tags.create(slug=i, created_by=User.objects.get(username='mazban'))


        if commit:
            model.save()

        return model

class EventForm(admin.ModelAdmin):
    exclude = ('published_by', 'published_at', 'updated_at', 'updated_by', )
    form = EventAdminForm

2 个答案:

答案 0 :(得分:3)

要在admin中访问请求,您需要覆盖ModelAdmin的save_model方法:

示例:

def save_model(self, request, obj, form, change):
    if not change:
        obj.author = request.user
    obj.save()

有关详细信息,请查看文档:{​​{3}}

答案 1 :(得分:3)

从@brandon回复和你的评论中,您可以将它们混合起来:

# admin.py

# don't override EventAdminForm's save(). Instead implement it here:         

class EventAdmin(admin.ModelAdmin):
    exclude = ('published_by', 'published_at', 'updated_at', 'updated_by', )
    form = EventAdminForm

    def save_model(self, request, obj, form, change):
        obj.save()
        obj.tags.all().delete()
        for i in form.cleaned_data['tag_it'].split(','):
            obj.tags.create(slug=i, created_by=request.user)