我在我的web應用程序的頁面可以通過URL這樣的訪問: http://localhost:8000/organizations/list_student/?school_id=19
Django的通過URL參數自定義FormMixin
我想從URL訪問school_id
人之一以上形成mixin,命名爲PhoneNumberMixin
(請參見下文)。能否熟悉Django的人告訴我應該如何將這個URL參數傳遞到像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)
謝謝你的答案。我想檢查數據庫中是否存在'phone_number'(PhoneNumberMixin的'clean_phone_numbers')的原因是我可以引發form.ValidationError讓用戶知道。有沒有辦法在視圖中提出這樣的錯誤?我想我上面粘貼了'views.py'。我現在要添加'urls.py'。再次感謝你。 – user1330974
啊,在這種情況下,您可以在您的模型字段中添加'unique = True',遷移數據庫,並且django應該處理剩下的事情。 –
明白了!這可能會訣竅。如果沒有人在幾天內提供更好的替代解決方案,我會接受你的答案。謝謝! – user1330974