我正在尝试使用一个选择的结果作为另一个选择的输入。我已经为此工作了三周,但找不到简单的答案。
这是我的模型:
from django.db import models
# Create your models here.
class School(models.Model):
id = models.CharField(primary_key=True, max_length=10)
school_name = models.CharField(max_length=80)
def __str__(self):
return(f"{self.id} {self.school_name}")
return self.id
class Meta:
ordering = ['id']
indexes = [
models.Index(fields=['id', 'school_name']),
]
class Courses(models.Model):
id = models.CharField(primary_key=True, max_length=12)
created_at = models.DateTimeField(auto_now_add=True)
school = models.ForeignKey(School, on_delete=models.PROTECT, related_name='school')
name = models.CharField(max_length=150, null=True, blank=True)
cost = models.CharField(max_length=75, null=True, blank=True)
class Meta:
ordering = ['id']
indexes = [ models.Index(fields=['school']), models.Index(fields=['name', 'id'])]
def __str__(self):
return(f"{self.school} {self.name}")
return self.name
class Student(models.Model):
course = models.ForeignKey(Courses, on_delete=models.PROTECT)
created_at = models.DateTimeField(auto_now_add=True)
student_id = models.CharField(max_length=20, null=True, blank=True)
class Meta:
ordering = ['course']
indexes = [
models.Index(fields=['course']),
]
我的看法:
def choose_school3(request):
if request.user.is_authenticated:
aschool = Courses.objects.all()
form=SelectSchoolForm(request.POST)
if request.method == "POST":
if form.is_valid():
data = form.cleaned_data
choice = data['school']
selected_school = Courses.objects.filter(school=choice).values()
context = {'choice': choice}
return render(request, 'add_student2b.html', context)
context = {'form': form, 'aschool':aschool}
return render(request, 'choose_school3.html', context)
else:
messages.success(request, "You Must Be Logged In To View Records!")
return redirect('main')
def add_student2b(request, choice):
chosen_school = Courses.objects.filter(school=choice).values()
form = AddStudentForm(request.POST)
context = {'form':form, 'choice':choice, 'chosen_school':chosen_school}
return render(request, 'add_student2b.html', context)
def add_student5(request, pk):
if request.user.is_authenticated:
choice = School.objects.get(id=pk)
courses = Courses.objects.filter(school=choice)
form = modelformset_factory(Student, fields=['course','student_id'], formset=AddStudentForm2FormSet)
context = {'courses':courses, 'choice':choice, 'form':form}
return render(request, 'add_student5.html', context)
else:
messages.success(request, "You Must Be Logged In To View Records!")
return redirect('main')
表格:
类 SelectSchoolForm(forms.ModelForm):
class Meta:
model = Courses
fields = ('school', )
labels = {'school':'School', }
widgets = {'school': forms.Select(attrs={"placeholder":"School", "class":"form-select"}),
}
class AddStudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ( 'student_id', )
labels = {'student_id':'',}
widgets = {'student_id':forms.widgets.TextInput(attrs={"placeholder":"Student ID", "class":"form-control"}),
}
class AddStudentForm2FormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
super().__init__(self, *args, **kwargs)
self.fields['course'].queryset = Student.objects.filter(all)
和 HTML: 选择_school3.html:
<form class="row g-3" action="{% url 'choose_school3' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="col-md-6">
{{ form.as_p }}
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-secondary">Choose School</button>
<a href="{% url 'school' %}" class="btn btn-success">Back</a>
</div>
</form>
add_student2b.html:
<form class="row g-3" action="{% url 'choose_school' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="col-md-6">
{{ form.as_p }}
</div>
<div class="col-md-6">
<a class="btn btn-secondary btn-lg" href="{% url 'add_student5' choice.id %}" role="button">Add Student</a>
<a href="{% url 'school' %}" class="btn btn-success">Back</a>
</div>
</form>
和add_student5.html:
<form class="row g-3" action="{% url 'choose_school' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="col-md-6">
{{ form.as_p }}
</div>
<div class="col-md-6">
<a class="btn btn-secondary btn-lg" href="{% url 'add_student5' choice.id %}" role="button">Add Student</a>
<a href="{% url 'school' %}" class="btn btn-success">Back</a>
</div>
</form>
我尝试的一切都会出错。最近的化身给了我这个:
无法解压不可迭代的builtin_function_or_method对象
参考 {{ form.as_p }} 标签。我一直在兜圈子,掉进兔子洞。是否可以使用 Django 来做到这一点(并且没有 JS 或其他东西)?请帮忙。
警告:我不太清楚你想做什么。
简单的答案就是实现第一阶段和第二阶段的两个单独的视图。第一个验证会导致重定向到第二个表单,第二个表单可以通过 kwargs 接收第一个表单的数据,或者如果必须安全地确保无法直接访问第二个表单,则可以通过数据库接收数据。
更复杂的一种是带有隐藏字段的表单,一旦提供并验证了主要字段,您就可以将其动态转换为非隐藏字段。还可以将可见内容转换为隐藏内容以保留内容。
我总是使用基于类的视图,并建议每个人都这样做。它们极大地简化了逻辑。对于前一种情况,我们通过表单获取验证的初始值,但是
form_valid
然后取消隐藏隐藏字段并返回 form_invalid(self, form)
,直到提供额外信息。