本文介绍了在Django表单集中预填充部分初始数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在django表单集中实现初始数据很困难。

I’m having difficulty implementing initial data in my django formset.

对于上下文,我正在构建一个考勤应用,其中存在一个学生列表,需要

For context, I’m building an attendance app where a list of students exist and need to be assessed for attendance every day.

我要做的是让管理员点击上面列出日期的链接。然后将它们带到数据网格,其中每一行代表系统中的学生人数以及4列(学生姓名,日期,当前/缺席下拉列表,注释字段)。目的是用学生模型中的学生列表预先填充学生姓名字段,并用用户单击的链接上的日期预填充日期字段,并将出勤和备注字段作为用户输入。

What I’m trying to do is have an administrator click on a link which has a date listed on it. They will then be taken to data grid where each row represents the number of students in the system along with 4 columns (student name, date, present/absent drop down, a notes field). The goal is to have the student name field be pre-populated with the the list of students in the Student model, the date field be pre-populated with the date on the link the user clicked and the attendance and notes fields be user inputs.

任何帮助将不胜感激

谢谢!

Student model

class Student(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    GENDER_CHOICES = (
        ('male', 'male'),
        ('female', 'female'),
    )
    gender =  models.CharField(max_length=12, choices=GENDER_CHOICES, null=False, blank=False)
    date_of_birth = models.DateField(auto_now=False, auto_now_add=False)

    @property
    def full_name(self):
        return ''.join([self.first_name, '_', self.last_name])

    def __unicode__(self):
        return self.full_name

Attendance model

class Attendance(models.Model):
    student = models.ForeignKey('students.Student')
    attendance_date = models.DateField(auto_now=False, auto_now_add=False)
    STATUS_CHOICES = (
        ('present', ‘1’),
        ('absent', ‘0’),
    )
    status =  models.CharField(max_length=12, choices=STATUS_CHOICES, null=False, blank=False)
    notes = models.CharField(max_length=300, null=True, blank=True)

    class Meta:
        unique_together = ("student", "attendance_date")

    def __unicode__(self):
        return self.student

Attendance form

class AttendanceForm(forms.ModelForm):
    class Meta:
        model = Attendance
        fields = ["student","attendance_date", "status", "notes"]


View

def add_attendance(request):
    s = Student.objects.all().values()
    AttendanceFormSet = formset_factory(AttendanceForm, extra=0)
    formset = AttendanceFormSet(request.POST or None, initial=s)
    if formset.is_valid():
        try:
            instance = form.save(commit=False)
            instance.save()
            return HttpResponseRedirect('/')
        except:
            return HttpResponseRedirect('/')
    context = {
        "formset": formset,
    }
    return render(request, "group_attendance.html", context)


Template

 <table id="formset" class="form">
 {{ formset.management_form }}

{% for form in formset.forms %}
  {% if forloop.first %}
  <thead><tr>
    {% for field in form.visible_fields %}
    <th>{{ field.label|capfirst }}</th>
    {% endfor %}
  </tr></thead>
  {% endif %}
  <tr>
  {% for field in form.visible_fields %}
    <td>
    {# Include the hidden fields in the form #}
    {% if forloop.first %}
      {% for hidden in form.hidden_fields %}
      {{ hidden }}
      {% endfor %}
    {% endif %}
      {{ field.errors.as_ul }}
      {{ field }}
    </td>
  {% endfor %}
  </tr>
{% endfor %}
</table>


推荐答案

如果我理解您的意思,我不确定质疑预期的方式。我认为您正在寻找一种生成动态表单的方法,该表单已预先填充了数据库中的数据。

I'm not really sure, if I understood your question the intended way. I think you're looking for a way to generate dynamic forms, which were pre-filled with data from the db.

可以找到关于此的非常有用的文章此处

A really helpful article about that, can be found here https://jacobian.org/writing/dynamic-form-generation/

您没有固定数量的学生(表格中的字段为->),因此您必须生成所需数量的字段。因此,您必须遍历学生并为每个人创建一个表单字段。

You don't have a fixed numbers of students (-> fields in form), so you have to generate as many fields as needed. So you have to iterate over the students and create a form field for every single one.

您可以在上面的文章中找到它。下面是一个代码段及其解释:

You can find this in the article above. Just down below is a code snippet and an explanation of it:

class UserCreationForm(forms.Form):
    username = forms.CharField(max_length=30)
    password1 = forms.CharField(widget=forms.PasswordInput)
    password2 = forms.CharField(widget=forms.PasswordInput)

    def __init__(self, *args, **kwargs):
        extra = kwargs.pop('extra')
        super(UserCreationForm, self).__init__(*args, **kwargs)

        for i, question in enumerate(extra):
            self.fields['custom_%s' % i] = forms.CharField(label=question)

这篇关于在Django表单集中预填充部分初始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:46