【问题标题】:Django adding to database with foreign key while still showing the informations from the other modelDjango 使用外键添加到数据库,同时仍显示来自其他模型的信息
【发布时间】:2019-04-12 11:15:37
【问题描述】:

我想将元素添加到我的数据库(用于模型 Student),同时将来自另一个模型(School)的内容显示在 Student 的表单旁边。\

这是models.py

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

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

    def __str__(self):
        return self.name


class Student(models.Model):
    name = models.CharField(max_length=256)
    age = models.PositiveIntegerField(validators= [validators.MinValueValidator(1),validators.MaxValueValidator(20)],default=1)
    school = models.ForeignKey(School, related_name='students')

def __str__(self):
    return self.name

在我的views.py中我有这个:

class SchoolDetailedView(DetailView):
    context_object_name = 'school_detail'
    model = models.School
    template_name = 'basiccbv/school_detail.html'
    # What i want is when I visit the link in the description I want to
    # to see the school stuff and the form to add the student in this new 
    # view

class StudentCreateView(CreateView):
    model = models.School
    # I tried using the Student but that I don't know how to display the 
    # school information, I tried with related_name = 'students' but it 
    # didn't work(I don't know if that can be done the way that intended it 
    # or I just don't have the knowledge )  
    fields = ['name', 'age']
    # If I use School I could get the name of the school in the title and 
    # its primary key, but than I don't know how to display the form and 
    # vise versa 
    template_name = 'basiccbv/student_update.html'

这是 .html 文件,可让我进入需要表单的页面。 该链接是调用“basiccbv:studentupdate”的链接 这里使用了related_name学生,但我仍然不知道它是否可以 以我想要的方式添加东西完成

<h1>Welcome to the school details page</h1>
<h2>School details:</h2>
<p>Name: {{ school_detail.name }}</p>
<p>Principal: {{ school_detail.principal }}</p>
<p>Location: {{ school_detail.location }}</p>
<h3>Students:</h3>
{% for student in school_detail.students.all %}
<p>{{ student.name }} who is {{ student.age }} years old.</p>
{% endfor %}
<div class="container">
<p><a href="{% url 'basiccbv:studentupdate' pk=school_detail.pk %}">Add a 
student</a></p>

这是带有表单的 .html 文件

              ## I changed this part bellow but nothing worked
<h1>Student coming to {{ student.school.name }}</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
    <input type="submit" class="btn btn-primary" value="Add student">
</form>

我真的被困住了,找不到任何有关此的信息,但如果您能帮助我或提供任何建议,谢谢。

我过去添加学生的方式是使用 admin,而对于学校,我使用 admin,直到我创建了用于创建没有问题的学校的视图(可能是因为没有外键)。

【问题讨论】:

    标签: python django database model foreign-keys


    【解决方案1】:

    我认为你可以采用这种方法

    表格:

    # We need to define a new form first
    class StudentForm(forms.ModelForm):
         class Meta:
             model = Student
             fields = ['name', 'age']
    

    观看次数:

    # we are using form view for using the form mentioned above
    class StudentCreateView(FormView):
         form_class = StudentForm
         success_url = "/"
    
         def get(self, request, school_id, **kwargs):
             context = self.get_context_data(**kwargs)  # getting context, ie: the form
             context[school] = School.objects.get(pk=school_id)  # updating the context with school object using the PK provided with the url
             return self.render_to_response(context)
    
         def post(self, request, school_id, **kwargs):
            # overriding default implementation
            form = self.get_form()  
            if form.is_valid():
                return self.form_valid(form, school_id)  # passing the pk value to form valid function to override
            else:
                return self.form_invalid(form)
    
        def form_valid(self, form, school_id):
            # overriding default implementation
            self.object = form.save(commit=False)
            self.object.school = School.objects.get(id=school_id)  # saving the school information to the object
            self.object.save()
            return super(StudentCreateView, self).form_valid(form)
    

    模板

    # template
        <h1>Student coming to {{ school.name }}</h1>
        <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
            <input type="submit" class="btn btn-primary" value="Add student">
        </form>
    

    网址

    path('school/student-update/<int:school_id>/', StudentCreateView.as_view(), name='studentupdate'),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-21
      • 2013-06-25
      • 2017-09-07
      • 1970-01-01
      • 2020-03-03
      • 2021-09-20
      • 2015-08-30
      • 1970-01-01
      相关资源
      最近更新 更多