用只读的foreignKey值填充Django CreateView表单

时间:2017-11-10 15:05:59

标签: django django-class-based-views

当显示CreateView表单时,我想使用登录用户的数据填充foreignKey值。我希望这只是阅读。

我的模特是:

# User profile info
class Profile(models.Model):

    # Relationship Fields
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    school = models.ForeignKey('eduly.School', default=1)

    notes = models.TextField(max_length=500, blank=True)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()


class School(models.Model):

    # Fields
    name = models.CharField(max_length=255)
    address = models.TextField(max_length=500, blank=True)
    email = models.CharField(max_length=30)
    phone = models.CharField(max_length=15)
    contactName = models.CharField(max_length=30)
    slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
    created = models.DateTimeField(auto_now_add=True, editable=False)
    last_updated = models.DateTimeField(auto_now=True, editable=False)


    class Meta:
        ordering = ('-created',)

    def __unicode__(self):
        return u'%s' % self.slug

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('eduly_school_detail', args=(self.slug,))


    def get_update_url(self):
        return reverse('eduly_school_update', args=(self.slug,))


class Teacher(models.Model):

    SCHOOL_ADMIN = 0
    CLASS_ADMIN = 1
    TASK_ADMIN = 2

    ROLES = {
        (SCHOOL_ADMIN, "School administrator"),
        (CLASS_ADMIN, "Class administrator"),
        (TASK_ADMIN, "Task administrator")
    }

    # Fields
    name = models.CharField(max_length=255)
    slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
    created = models.DateTimeField(auto_now_add=True, editable=False)
    last_updated = models.DateTimeField(auto_now=True, editable=False)
    email = models.CharField(max_length=30)
    roles = models.IntegerField("Role", choices=ROLES, default=1)

    # Relationship Fields
    school = models.ForeignKey('eduly.School', )

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return self.name

    def __unicode__(self):
        return u'%s' % self.slug

    def get_absolute_url(self):
        return reverse('eduly_teacher_detail', args=(self.slug,))


    def get_update_url(self):
        return reverse('eduly_teacher_update', args=(self.slug,))

我的观点是:

@method_decorator(login_required, name='dispatch')
class TeacherListView(ListView):
    model = Teacher

    def get_queryset(self):
        return Teacher.objects.filter(school=self.request.user.profile.school)


@method_decorator(login_required, name='dispatch')
class TeacherCreateView(CreateView):
    model = Teacher
    form_class = TeacherForm

对于TeacherCreateView,我想将Teacher.school foreignKey字段设置为self.request.user.profile.school,字段为只读。

1 个答案:

答案 0 :(得分:0)

在您的表单中,您可以执行以下操作。神奇的是字段属性disabled

class TeacherForm(forms.modelForm):
    def __init__(self, *args, **kwargs):
        super(TeacherForm, self).__init__(*args, **kwargs)
        self.fields['school'].disabled = True

    class Meta:
       fields = '__all__'

你可以读它django docs。参考:https://docs.djangoproject.com/en/1.11/ref/forms/fields/#disabled