Django将URL参数传递给自定义FormMixin

时间:2015-07-22 01:51:49

标签: django django-forms django-views

我的网页应用中有一个页面可以通过URL访问,如下所示: http://localhost:8000/organizations/list_student/?school_id=19

我希望从上面的网址中访问其中一个名为school_id的表单mixin的PhoneNumberMixin(请参阅下文)。知道Django的人是否可以告诉我如何将该URL参数传递给自定义表单mixin,如PhoneNumberMixin?谢谢。

models.py

class Student(models.Model):
    school = models.ForeignKey(School)
    phone_number = models.CharField(max_length=15, blank=True)

urls.py

urlpatterns = patterns('',
    # There are more, but to save space, only relevant part is included
    url(r'^list_student/$', StudentListView.as_view(), name='list_student'),
)

在页面views.py中:

class StudentListView(LoginRequiredMixin, FormView):
    form_class = SchoolAddStudentForm
    template_name = 'organizations/list_student.html'

    def get_success_url(self):
        return reverse_lazy('organizations:list_student') + '?school_id=' + self.request.GET['school_id'] 

    def get_form(self, form_class):
        request = self.request
        return form_class(request, **self.get_form_kwargs())

    def get_context_data(self, **kwargs):
        # add stuff to data to pass to HTML page here
        return data

    def form_valid(self, form):
        data = form.cleaned_data
        # save cleaned data to DB here
        return HttpResponseRedirect(self.get_success_url())

forms.py

# Note PhoneNumberFormMixin below. It is used to clean phone numbers 
# such duplicate checking against the existing numbers in the DB
class SchoolAddStudentForm(PhoneNumberFormMixin, forms.Form):
    phone_numbers = forms.CharField(widget=forms.Textarea(attrs=form_attrs))

    def __init__(self, request, *args, **kwargs):
        super(SchoolAddStudentForm, self).__init__(*args, **kwargs)
        self.fields['phone_numbers'].label = 'Step 1 (required): Add comma-separated list of phone numbers [E.g., 5856261234, 8613910912345]:'

mixins.py

class PhoneNumberFormMixin(object):
    """
    Custom form mixin for validating phone numbers
    """
    def clean_phone_numbers(self):
        data = self.data
        numbers = []

        sid = #!!!! this is where I'd like to access school_id from the URL
        qs = Student.objects.filter(school_id=sid)
        # do something with the qs
        return ','.join(numbers)

2 个答案:

答案 0 :(得分:1)

我不确定我是否有完整的图片,因为你错过了views.py& urls.py.但通常,字段清理方法应仅检查输入是否格式正确,并且实际应用程序逻辑应位于视图的form_valid()方法中。 Form()方法无法准确访问HTTP请求信息,因为它超出了其功能范围。

在您看来,您可以通过以下方式访问网址参数:

self.request.GET.get('school_id', None)

阅读form_valid() - 在这里你应该添加代码来修改对象+字段值,然后保存它们,和/或在需要时创建相关对象。

答案 1 :(得分:0)

在我的用例中,我正在进行搜索,显示搜索结果列表。

我最终使用了这个:

class SearchView(FormMixin, ListView):

    def get_queryset(self):
        qs = super().get_queryset()
        # TODO implement filtering
        return qs

    def get_form_kwargs(self):
        # use GET parameters as the data
        kwargs = super().get_form_kwargs()
        if self.request.method in ('GET'):
            kwargs.update({
                'data': self.request.GET,
            })

        return kwargs