简体   繁体   English

如何将外键ID传递给表单? 或将表单链接到外键值 DJango

[英]How to pass foreign key id to form? or link form to a foriegn key value DJango

I am trying to auto populate my form Student field with the name Carl Park.我正在尝试使用名称 Carl Park 自动填充我的表单学生字段。 In short I want my form to use to automatically use the Object ID instead of having to manually select the name Carl Park from the student field drop down menu.简而言之,我希望我的表单用于自动使用 Object ID,而不必从学生字段下拉菜单中手动 select 名称 Carl Park。

How do I automatically link my Model Form to a foriegn key ID and have the form auto populate based on that value.如何自动将我的 Model 表单链接到外键 ID 并根据该值自动填充表单。

Here is my current form, my models.py forms.py views.py and HTML这是我目前的表格,我的 models.py forms.py views.py 和 HTML

在此处输入图像描述

 #models
class Teacher(models.Model):
    name = models.CharField(max_length=75)
    room = models.CharField(max_length=10)
    bio = models.TextField()
    

class Student(models.Model):
    teacher = models.ForeignKey('Teacher', on_delete=models.CASCADE)
    name = models.CharField(max_length=75)
  

class Student_Performance(models.Model):
    student = models.ForeignKey('Student', on_delete=models.CASCADE)
    behavior_grade = models.CharField(max_length=1)
    
    
    
#form
class StudentPerfromanceForm(ModelForm):
    
    class Meta:
        model = Student_Performance
        fields = ( "name", "behavior_grade")

        
#view
def student_details(request, id):
    obj  = get_object_or_404(Student,pk=id)
    
    form = StudentPerfromanceForm()
    if request.method == 'POST':
        form = StudentPerfromanceForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
            return all_students_list(request) #pass success message

    return render(request, 'class_roster/student_details.html', {'obj':obj, 'reviewForm':form})



#HTML
<form method="POST">
    {% csrf_token %}
    {{reviewForm.as_p}}
    <input type="submit" value="Submit Review">
</form>

I want to more code informations.我想要更多的代码信息。

anyway if you want set student automatically use object_id,无论如何,如果你想设置学生自动使用 object_id,

try尝试

objects.get(query)  

ex) ModelClassName.objects.get(pk=1)例如)ModelClassName.objects.get(pk=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM