没有初始数据的Django表单集

时间:2018-08-30 07:56:49

标签: python django django-forms modelform formset

我是Django新秀,我正在开发一个小应用程序,用于注册时间(持续时间)和每位用户每天的活动数量。有点像工作日志。我的问题是:我的“添加条目”视图显示和更新旧记录,而不是向数据库添加新记录。我需要一个视图来添加新记录,而不是替换旧记录。

从#django IRC频道中搜索和从中了解到,默认情况下,formset-way使用旧数据,而不是设置客户端来添加新数据。但是,我还没有找到任何有关如何避免这种行为的信息,而是让客户端为“添加新数据”而不是“编辑现有数据”提供空白表格。

我的截止日期已经接近尾声,我们将不胜感激。

以下是相关的代码段:

从models.py

class Activity(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField()

class Workday(models.Model):
    entrydate = models.DateField()
    worker = models.ForeignKey(User, on_delete=models.CASCADE)

class Entry(models.Model):
    duration = models.DurationField()
    quantity = models.PositiveIntegerField()
    activity = models.ForeignKey(Activity, on_delete=models.CASCADE)
    workday = models.ForeignKey(Workday, on_delete=models.CASCADE)

来自Forms.py

class EntryForm(ModelForm):
    activity = ModelChoiceField(queryset=Activity.objects.order_by('name'), initial=0)

    class Meta:
        model = Entry
        fields = ['activity',
                  'duration',
                  'quantity',
                  ]

class WorkdayForm(ModelForm):
    class Meta:
        model = Workday
        fields = ['entrydate']
        widgets = {'entrydate': SelectDateWidget}

来自views.py

def addentry(request):
    EntryFormSet = modelformset_factory(Entry, form=EntryForm, extra=0, fields=('activity', 'duration', 'quantity'))

    if request.method == 'POST':
        workdayform = WorkdayForm(request.POST, prefix='workday')
        formset = EntryFormSet(request.POST)

        if formset.is_valid() and workdayform.is_valid():
            # Generate a workday object
            workday = workdayform.save(commit=False)
            workday.entrydate = workdayform.cleaned_data['entrydate']
            workday.worker = request.user
            workday.save()

            # Generate entry objects for each form in the entry formset
            for form in formset:
                e = form.save(commit=False)
                e.workday = workday
                e.save()
                form.save_m2m()

                messages.add_message(request, messages.SUCCESS,
                                     "Registrert aktivitet " +
                                     e.workday.entrydate.strftime('%A %d. %B %Y') +
                                     ": " + e.activity.name + " (" + str(e.quantity) +") - " +
                                     str(e.duration)
                )

            return redirect('index')
        else:
            workdayform = WorkdayForm(request.POST, prefix='workday')
            formset = EntryFormSet(request.POST)

            for dict in formset.errors:
                messages.add_message(request, messages.ERROR, dict)

            context = {
                       'workdayform': workdayform,
                       'formset': formset,
                       }
            return render(request, 'register/addentry.html', context)

    else:
        workdayform = WorkdayForm(prefix='workday')
        formset = EntryFormSet()
        context = {
                   'workdayform': workdayform,
                   'formset': formset,
                   }
        return render(request, 'register/addentry.html', context)

从addentry.html

{% block content %}
    {% if user.is_authenticated %}

        <h1>Ny dag</h1>
        {% if formset and workdayform %}
            <form id="newdayform" method="POST" class="post-form">
                {% csrf_token %}

                {{ workdayform.as_p }}

                {{ formset.management_form }}

                <table>
                    <thead>
                        <tr>
                            <td>Aktivitet</td>
                            <td>Varighet<br/>(HH:MM:SS)</td>
                            <td>Antall</td>
                        </tr>
                    </thead>
                    <tbody>
                        {%  for form in formset %}
                            <tr>
                                <td>{{ form.activity }}</td>
                                <td>{{ form.duration }}</td>
                                <td>{{ form.quantity }}</td>
                                <td class="hidden">{{ form.id }}</td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
                <button type="submit">Registrer tid</button>
            </form>

               <script src="{% static 'register/jquery.formset.js' %}"></script>
    <script type="text/javascript">
        $(function() {
            $('#newdayform tbody tr').formset();
        })
    </script>

            {% if entryform.errors or workdayform.errors %}
                <h3>Feil i utfyllingen</h3>
                {{ entryform.errors }}
                {{ workdayform.errors }}
            {% endif %}

        {% else %}
            <p>No form!</p>
        {% endif %}

    {% endif %}
{% endblock %}

1 个答案:

答案 0 :(得分:1)

由于@ e4c5和this previous Q&A,通过将无对象的查询集传递给表单集来解决此问题,如下所示:

def addentry(request):
    (...)

    qs = Entry.objects.none()
    formset = EntryFormSet(queryset=qs)

   (...)