如何在不传递外键值的情况下以Django形式过滤外键?

时间:2018-09-26 15:35:02

标签: django-models django-forms foreign-keys

我在django项目AddStudent和Fee Entry中创建了两个模型,如下所示。

models.py

class AddStudent(models.Model):
    enrollment_no = models.BigIntegerField(primary_key=True)
    student_name = models.CharField(max_length=500,null=True)
    gender = models.CharField(max_length=1,choices=GENDER_CHOICES)
    course = models.ForeignKey(CourseMaster, on_delete=models.DO_NOTHING, null=True)
    category= models.ForeignKey(CatMaster, on_delete=models.DO_NOTHING, null=True)
    admission_year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
    college = models.ForeignKey(CollegeMaster, on_delete=models.DO_NOTHING, null=True)
    branch = models.ForeignKey(BranchMaster,on_delete=models.DO_NOTHING, null=True)
    current_semester = models.IntegerField(null=True)
    address = models.CharField(max_length=1000,null=True)
    city = models.CharField(max_length=100,null=True)
    district = models.CharField(max_length=100,null=True)
    state = models.CharField(max_length=100,null=True)
    student_contact = models.BigIntegerField()
    parent_contact = models.BigIntegerField()

    def get_absolute_url(self):
        return reverse('add_student:index')

    def __str__(self):
        return str(self.enrollment_no) + ' - ' + self.student_name

class FeeEntry(models.Model):

    student = models.ForeignKey(AddStudent,on_delete=models.DO_NOTHING)
    fee_detail = models.ForeignKey(FeeMaster,on_delete=models.DO_NOTHING)
    fee_sem = models.IntegerField(null=True)
    payment_date = models.DateField(("Date"), default=datetime.date.today)
    pay_method = models.BooleanField(choices=BOOL_CHOICES)
    cheque_no = models.CharField(max_length = 100, null=True, blank=True)
    bank_name = models.CharField(max_length = 200, null=True, blank=True)

    def __str__(self):
        return str(self.id) + ' - ' + str(self.student) + ' - ' + self.student.student_name

现在,当用户搜索特定学生(例如,学生ID = 1)时,将打开学生资料页面,并且还有另一个按钮addfee。我的问题是,当用户单击添加费用时,所有500个学生列表都出现在下拉列表中。我只想为搜索到的学生创建费用。

forms.py

from django import forms
from .models import FeeEntry, AddStudent
from bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin

class FeeForm(PopRequestMixin, CreateUpdateAjaxMixin, forms.ModelForm):
    class Meta:
        model = FeeEntry
        fields = ['student', 'fee_detail', 'fee_sem', 'payment_date', 'pay_method','cheque_no','bank_name']

上面是我的forms.py文件,其中“学生”字段将生成所有500个学生列表。当用户位于enrollment_no 1的页面上时,我只希望选择学生,例如enrollment_no = 1。

views.py

class FeeCreateView(PassRequestMixin, SuccessMessageMixin,
                         generic.CreateView):
    template_name = 'add_student/create_fee.html'
    form_class = FeeForm
    success_message = 'Success: Book was created.'
    success_url = reverse_lazy('add_student:detail')

urls.py

path('create/<int:pk>', views.FeeCreateView.as_view(), name='create_fee'),

谁能告诉我此代码需要进行哪些更改?还是可以分享类似例子的链接?

1 个答案:

答案 0 :(得分:0)

该费用表不知道您想与之联系的学生。因此,它向您显示一个下拉列表,询问您要分配给FeeEntry实例的哪个学生。

从表单中删除“学生”并将表单发送到视图。当用户提交表单时,请使用form_valid(如果使用的是FBV,则使用form.is_valid)方法将学生分配给fee_entry实例。

def form_valid(self, form):
    fee_entry = form.save(commit=False)
    fee_entry.student = AddStudent.objects.get(id=self.kwargs['student_id'])
    fee_entry.save()

还要确保在URL中发送student_id。您甚至可以使用表单中的隐藏字段将其作为POST参数发送(查看如何从POST请求中检索参数)。