我如何自动填写我的字段并使其在 django 管理站点中不可编辑

How can i auto fill my field and make it non editable in django admin site

我需要在管理站点中自动填充一个字段,并使用 current_user 使外键字段不可编辑: views.py:

def my_view(request):
 obj = model.objects.first()
    response = HttpResponse(file, content_type=' 
  application/vnd.ms-excel',
                                )
    return response

urls.py:

path('temo/fill',views.my_view,name = 'my-view')

models.py

class Model(BaseModel, SingletonModel):
    file = models.FileField(
        upload_to='',
        validators=[FileExtensionValidator([''])]
    )
    person_uploaded = models.ForeignKey(
        'somemodel',
        related_name='s',
        null=True,
        on_delete=models.SET_NULL,
        )

admin.py:

@admin.register(tTemplate)
class TemplateAdmin(admin.ModelAdmin):
    list_display = ('file','person_uploaded',)
    readonly_fields = ('person_uploaded',)

    def save(self, request):
        if not self.id:
            self.person_uploaded = request.user
        super().save()

好吧,在 django 管理中预填充一个字段,它直接做这样的事情:


@admin.register(tTemplate)
class TemplateAdmin(admin.ModelAdmin):
    list_display = ('file','person_uploaded',)
    readonly_fields = ('person_uploaded',)
    

    def save_model(self, request, obj, form, change):
        obj.user = request.user
        super().save_model(request, obj, form, change)