如何用Django形式的外键自动填充变量?

时间:2018-08-28 12:44:22

标签: django python-3.x forms django-2.0

简而言之:我要自动填充表单的外部变量:

TL; DR
这是项目link。 我有一个模型:

from django.db import models
from django.urls import reverse
# Create your models here.

class School(models.Model):
    name = models.CharField(max_length=256)
    principal = models.CharField(max_length=256)
    location = models.CharField(max_length=256)

    def __str__(self): return self.name

    def get_absolute_url(self):
        return reverse('basic:detail', kwargs={'pk': self.pk})

class Student(models.Model):
    name = models.CharField(max_length=256)
    age = models.PositiveIntegerField()
    school = models.ForeignKey(School, on_delete=models.CASCADE, related_name='students')

    def __str__(self): return self.name

    def get_absolute_url(self):
        return reverse('basic:detail', kwargs={'pk': self.school.pk})

和url.py:

urlpatterns = [
    path('', views.Index.as_view(), name='index'),
    path('list/', views.SchoolListView.as_view(), name='list'),
    path('<int:pk>/', views.SchoolDetailView.as_view(), name='detail'),
    path('create/', views.SchoolCreateView.as_view(), name='create'),
    path('update/<int:pk>/', views.SchoolUpdateView.as_view(), name='update'),
    path('delete/<int:pk>/', views.SchoolDeleteView.as_view(), name='delete'),

    path('student/create/', views.StudentCreateView.as_view(), name='creates'),
    path('student/create/<int:pk>', views.StudentCreateView.as_view(), name='createspk'),
    path('student/update/<int:pk>/', views.StudentUpdateView.as_view(), name='updates'),
    path('student/delete/<int:pk>/', views.StudentDeleteView.as_view(), name='deletes'),


]

我正在使用CBV:

class StudentCreateView(CreateView):
    try:
        print("*******")
        print(pk)
    except:
        pass
    model = Student
    fields = ["name", "age", 'school']

我添加了一个链接,用于在学校详细信息中创建学生,如下所示: screenshot

当我单击“用pk创建新内容”时,我正在传递School的pk,然后转到: scrreenshot2

如您所见,“学校”字段是下拉菜单,没有选择任何内容,我想将学校的默认值设置为该学校的默认名称,在这种情况下,是有天赋的孩子的高级学校

我创建的学生代码是:

{% extends "basic/base.html" %}

{% block content %}
<h1>
    {% if not form.instance.pk %}
    Create Student:
    {% else %}
    Update Student:
    {% endif %}
</h1>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" class="btn btn-primary">
</form>
{% endblock content %}

我该怎么做?预先感谢。

1 个答案:

答案 0 :(得分:1)

尝试像这样修改视图:

Declare @y1 as int =1; 
Declare @y2 as int =0;
 select (((@y2- @y1))/ @y1)*100

我还建议将url中的参数(然后在class StudentCreateView(CreateView): try: print("*******") print(pk) except: pass model = Student fields = ["name", "age", 'school'] def get_initial(self): initial = super(StudentCreateView, self).get_initial() initial['school'] = School.objects.get(pk=self.kwargs['pk']) return initial 方法中)重命名为类似get_initial的名称,以明确表示您不为该参数传递school_pk pk要创建。