如何在django泛型FormView中使表单字段只读或以其他方式不可编辑?

时间:2017-01-11 23:16:05

标签: python django django-forms django-views

我有一个表单,用于在页面加载时使用当前登录的用户预先填充用户字段。我想将此字段灰显,以便用户无法将其更改为未登录的用户。我希望用户能够更改其余字段。我尝试在模型表单上使用 init 函数,但视图无效。任何指针都会受到赞赏。

forms.py:

class PtoRequestForm(forms.ModelForm):
    class Meta:
        # Model to be used in the form.
        model = PtoHistory
        # Define which model fields to include in the form.
        fields = [
            'user',
            'start',
            'end',
            'leave_type',
        ]
        # Attach input widgets to fields for a friendlier user interface.
        widgets = {
            'start': DateTimeWidget(attrs={'id':'start'}, usel10n = True, bootstrap_version=3),
            'end': DateTimeWidget(attrs={'id':'end'}, usel10n = True, bootstrap_version=3),
    }

views.py:

class IndexView(FormView):
    template_name = 'accounts/index.html'
    form_class = PtoRequestForm
    success_url = '/accounts'
    # Pre-populates the form with the specified values on page load.
    def get_initial(self):
        return {'user': self.request.user}

    # Function runs when form is submitted. Do whatever needed to the form before it's saved to the db.
    def form_valid(self, form):
        form.save()
        return super(IndexView, self).form_valid(form)

    # Function runs on page load. Gather any information needed for the template.
    def get_context_data(self, **kwargs):
        # Initialize context
        context = super(IndexView, self).get_context_data(**kwargs)

        # Grab all ptoHistory records from the database, selecting only the values desired.
        pto_history = PtoHistory.objects.values('start', 'end', 'pk', 'user_id')
        # Convert the django queryset to json so that fullcalendar can work with it on the frontend.
        json_pto_history = json.dumps(list(pto_history), cls=DjangoJSONEncoder)
        # Save the converted json to the context to be returned to the front end.
        context['ptoHistory'] = json_pto_history
        return context

这是我表单的截图。用户不应该能够更改用户字段,但其他字段可以更改。

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以按照以下方式添加:

class PtoRequestForm(forms.ModelForm):
    class Meta:
        # Model to be used in the form.
        model = PtoHistory
        # Define which model fields to include in the form.
        fields = [
            'user',
            'start',
            'end',
            'leave_type',
        ]
        # Attach input widgets to fields for a friendlier user interface.
        widgets = {
            'start': DateTimeWidget(attrs={'id':'start'}, usel10n = True, bootstrap_version=3),
            'end': DateTimeWidget(attrs={'id':'end'}, usel10n = True, bootstrap_version=3),}

    def __init__(self, *args, **kwargs):
         super(PtoRequestForm, self).__init__(*args, **kwargs)
         self.fields['user'].widget.attrs['readonly'] = True

答案 1 :(得分:0)

在我的模型表单中,我没有包含'user'字段,如下所示:

forms.py:

class PtoRequestForm(forms.ModelForm):
    class Meta:
        # Model to be used in the form.
        model = PtoHistory
        # Define which model fields to include in the form.
        fields = [
            'start',
            'end',
            'leave_type',
        ]
        # Attach input widgets to fields for a friendlier user interface.
        widgets = {
            'start': DateTimeWidget(attrs={'id':'start'}, usel10n = True, bootstrap_version=3),
            'end': DateTimeWidget(attrs={'id':'end'}, usel10n = True, bootstrap_version=3),
        }

然后在我的form_valid函数中,我只是附加了当前登录的用户,然后将其保存到数据库中,如下所示:

views.py:

def form_valid(self, form):
        new_form = form.save(commit=False)
        new_form.user = self.request.user
        new_form.save()
        return super(IndexView, self).form_valid(form)