在Django view.py的modelformset工厂中获取FieldError

时间:2018-10-18 06:40:21

标签: python django python-2.7 django-forms django-1.9

我得到FieldError为:

  

为AssistantNotes指定的未知字段(记事本)

当我呼叫页面时。它引发此错误。我正在使用Django 1.9.5和python 2.7。 我在数据库的AssistantNotes表中记录了字段。如果我从视图中的modelformset_factory行中删除“ notedate”,则它可以正常工作。我无法解决为什么它虽然在数据库和模型中都没有显示出注释。并产生错误。该字段已经在模型中。

我的观点是:

def edit_assistant_notes(request):
    isassistantsuperadmin = getUserPermissions(request) #Yes if 1, no if 0
    list = getUserType(request)
    userisassistant = list[2]
    if userisassistant == "YES" or isassistantsuperadmin ==1: 
        list = getUserType(request)
        type = list[0]
        usertype = list[1] #"Nöbetçi Muavin":1 , "Yetkili":2
        if request.method == 'GET':
            if AssistantNotes.objects.filter(notedate=nicosia_date(datetime.today()).date()).count() == 0:
                AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('time', 'notedate', 'categories', 'type', 'dailynote',))
            else:
                AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('time', 'notedate', 'categories', 'type', 'dailynote',), can_delete=True)
            if usertype == 1:
                formset = AssistantNotesFormsetFactory(queryset=AssistantNotes.objects.filter(notedate=nicosia_date(datetime.today()).date(), type=type))
            elif usertype == 2:
                formset = AssistantNotesFormsetFactory(queryset=AssistantNotes.objects.all().order_by("notedate", "time"))
            helper = TableInlineHelper()
            return render(request, 'edit-assistant-notes.html', {'formset': formset, 'helper': helper})

我的模特是:

    class AssistantNotes(BaseModel):
    categories = models.CharField(choices=CATEGORIES, default="GENERAL", max_length=100, verbose_name=_("CAT"))
    time = models.CharField(choices=TIME, default="-------------", max_length=20, verbose_name=_("Time"))
    dailynote = models.TextField(null=True, blank=True, verbose_name=_("Add Note"))
    writer = models.TextField(null=True, blank=True, verbose_name=_("Adder"))
    notedate = models.DateField(auto_now_add=True, db_index=True, verbose_name=_("Date"))
    type = models.CharField(choices=SCHOOLTYPE, default="---", max_length=100, verbose_name=_("SchoolType"))

    def __unicode__(self):
        return "%s / %s" % (self.dailynote, self.categories)

    class Meta:
        ordering = ['dailynote']

1 个答案:

答案 0 :(得分:0)

  

如何强制此字段可编辑?

代替设置auto_now_add,您可以覆盖模型的save()方法,例如

class AssistantNotes(BaseModel):
    ....
    notedate = models.DateField(db_index=True, verbose_name=_("Date"))
    def save(self, *args, **kwargs):
        if not self.id:
            self.notedate = timezone.now()
        return super(AssistantNotes, self).save(*args, **kwargs)