请求未在Forms.py类(forms.Form)内部定义

时间:2019-01-21 17:41:25

标签: django python-3.x django-2.1

错误

NameError: name 'request' is not defined

我的forms.py

class PersonForm(forms.Form):
    name = forms.CharField(required=False)
    job_title = forms.CharField(required=False)
    status = forms.TypedChoiceField(choices=Person.STATUS_CHOICES)


    project = Project.objects.get(users=request.user, pk=self.kwargs.get('pk'))
    company = forms.ModelChoiceField(queryset=project.companies.all(),required=False)

    new_company = forms.CharField(required=False)
    note = forms.CharField(required=False)

    def __init__(self, *args, **kwargs):
        super(PersonForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'


    def clean(self):
        return self.cleaned_data

views.py

class PersonCreate(LoginRequiredMixin, FormView):
    template_name = 'person/person_form.html'
    form_class = PersonForm
    success_url = '/project/'

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        cleaned_data = form.clean()

        active_project = self.request.session['active_project']

        project = Project.objects.get(users=self.request.user, pk=self.request.session['active_project'])

        if cleaned_data['name']:
            person, created = Person.objects.get_or_create(
                name=cleaned_data['name'], 
                job_title=cleaned_data['job_title'], 
                created_by=self.request.user,
                status=cleaned_data['status'], 
                project=project
            )

            if cleaned_data['new_company']:

                company, created = Company.objects.get_or_create(name=cleaned_data['new_company'], project=project, created_by=self.request.user)
                company.persons.add(person)
                company.save()

            if cleaned_data['note']:
                person.note_set.create(content=cleaned_data['note'], created_by=self.request.user)
                person.save()

            if cleaned_data['company']:

                company = project.companies.get(name=cleaned_data['company'])
                company.persons.add(person)
                company.save()

        return super().form_valid(form)

    def get_success_url(self):
        return self.request.POST.get('next', '/project/' + str(self.request.session['active_project']))

我想过滤queryset字段forms.ModelChoiceField上的company。用户可以访问基于项目公司的信息。我该怎么做?我也可以在这里访问request.session数据吗?

2 个答案:

答案 0 :(得分:1)

您不能那样做,因为Django表单根本无法访问请求。

所以我能想到的最好的方法是将用户传递给表单,然后在初始化时使用数据。

首先,您必须在视图中传递用户和pk。

views.py:

# ...
form = PersonForm(user=request.user, pk=kwargs.get('pk'))

然后在表单中,您可以捕获两个kwarg并使用正确的值更新项目,

class PersonForm(forms.Form):
    # your form fields code ...

    def __init__(self, *args, **kwargs):
        # get the user and pk
        user = kwargs.pop('user', None)
        pk = kwargs.pop('pk', None)
        # update project field
        super(PersonForm, self).__init__(*args, **kwargs)
        self.fields['project'] = Project.objects.get(users=user, pk=pk)

        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

答案 1 :(得分:0)

在基于类的视图中更新Form kwargs:

def get_form_kwargs(self):
    kwargs = super().get_form_kwargs()
    kwargs.update({"request": self.request})
    return kwargs