Python 如何在Django中根据表单中的字段过滤模型表单中的数据
我正在尝试根据表单中选定的字段筛选数据。我已经创建了一个模型并将其导入forms.pyPython 如何在Django中根据表单中的字段过滤模型表单中的数据,python,django,Python,Django,我正在尝试根据表单中选定的字段筛选数据。我已经创建了一个模型并将其导入forms.py from django import forms from django.forms import ModelForm from .models import Student_Detail, Student_Education class StudentDetailForm(forms.ModelForm): class Meta: model = Student_Detail
from django import forms
from django.forms import ModelForm
from .models import Student_Detail, Student_Education
class StudentDetailForm(forms.ModelForm):
class Meta:
model = Student_Detail
fields = ['name', 'surname' , 'sex', 'birth_date', 'area',
'state' ,
'city' , 'pincode']
def to_python(self, value):
if not value:
return []
return value.split(',')
而我的模特们
`
现在,我想根据在同一表单中选择的州来筛选表单中的城市
我的观点是
from django.shortcuts import render
from .models import City, Student_Detail, State, Student_Education
from django.http import HttpResponseRedirect
from .forms import StudentDetailForm, StudentEducationForm
def get_student_data(request):
if request.method == 'POST':
form_detail = StudentDetailForm(request.POST)
if form_detail.is_valid():
form_detail.save()
return HttpResponseRedirect('/home/')
else:
form_detail = StudentDetailForm()
return render(request,'home/form.html/',
{'form_detail':form_detail, })
def thanks(request):
template_name = 'home/thanks.html/'
return render(request, template_name, {})
我还尝试使用表单在两个不同的模型中输入数据,但在视图层将数据保存在两个不同的模型中时出现了一些错误。
请提供帮助。像这样访问您的表单字段
myForm.fields['name']
并过滤学生详细信息
from django.shortcuts import render
from django.http import HttpResponse
def student_view(request):
# your business logic or whatever goes here
if form.is_valid():
students = Student_Detail.objects.filter(name=myForm.fields['name'],
surname=myForm.fields['surname'])
return render(request, 'student_view.html', {data=students})
from django.shortcuts import render
from django.http import HttpResponse
def student_view(request):
# your business logic or whatever goes here
if form.is_valid():
students = Student_Detail.objects.filter(name=myForm.fields['name'],
surname=myForm.fields['surname'])
return render(request, 'student_view.html', {data=students})