Django:将初始值分配给ModelAdmin子类中表单的字段

时间:2017-01-29 06:58:13

标签: django forms django-forms django-admin

我不确定如何通过Admin App向用户显示表单中的字段。我想要做的是向用户提供一个表单,其中已经分配了名为user的字段一个值,如果可能,则禁用(无法更改)。

以下是我的模特

class modelStudent(models.Model):
    class Meta:
        verbose_name_plural = "Enrolled Students"  #Name to display in admin interface
    user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True)
    school           = models.ForeignKey(modelSchool)
    first_name       = models.CharField(max_length=128, unique=False)
    student_email    = models.EmailField(unique=True, blank=False)

class modelStudentAdminForm(forms.ModelForm):
    class Meta:
        model = modelStudent
        exclude = ['student_email']

现在这是管理表格的管理类

class modelStudentAdmin(admin.ModelAdmin):
form = modelStudentAdminForm
#Only display students that belong to this user

def get_queryset(self, request):
    qs = super(modelStudentAdmin, self).get_queryset(request)

    if request.user.is_superuser:
        return qs
    else:
        # Get the school instance
        schoolInstance = modelSchool.objects.get(user=request.user)
        qs = modelStudent.objects.filter(school=schoolInstance)
        return qs

def get_form(self, request, obj=None, **kwargs):
    #modelStudentAdmin.form.initial={"first_name":"JoeJoe"}
    return modelStudentAdmin.form

 def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        if db_field.name == 'user':
            kwargs['queryset'] =  modelStudent.objects.filter(user=request.user)
        return super(modelStudentAdmin,self).formfield_for_foreignkey(db_field, request, **kwargs)

在这种情况下,它说

'NoneType' object does not support item assignment

我已尝试为表单字段分配值,但无法执行此操作。 所以我的问题是如何在表单中将字段标记为只读并分配初始值?我想对user下拉字段执行此操作,并为first_name

分配初始值

更新

我还实现了here所述的方法(为了限制外键选项)

def formfield_for_foreignkey(self, db_field, request=None, **kwargs):

但是没有被召唤。

0 个答案:

没有答案