2011-08-11 53 views
1

我已經做了一個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 

回答

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

謝謝你解決了我的問題:) –

2

要訪問在管理的要求,你需要重寫你的ModelAdmin的save_model方法:

例子:

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

欲瞭解更多信息,請查看文檔:https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#modeladmin-methods

+0

在我上面的代碼中,我試圖創建一個需要用戶ID的泛型關係字段。它很難重寫ModelAdmin中的代碼,有沒有我可以將請求傳遞給EventFormAdmin? –

+0

嗯。我不確定如何將請求傳遞給Django amdin中的ModelAdmin表單。在管理員之外很容易做到,但是我還沒有在管理員的內部完成這個用例。 – Brandon