django动态表单保存数据

时间:2018-09-13 08:53:42

标签: python django forms dynamic-forms

感谢您阅读这篇文章并为我提供帮助。

我是Django的新手,我正在一个土著地区的网站上记录他们的生活。用户可以创建页面并发布内容。在创建页面之前,他们需要指定要记录的季节数。该网站将根据季节数动态创建文本字段。

当前,我可以动态创建文本字段,但是在保存数据时遇到了问题。我花了很长时间尝试解决这个问题,但仍然停留在这里。我得到的错误是“ SeasonalTextForm”对象没有属性“ instance”。

当我实现动态表单时,我关注的是以下文章: 1 https://jacobian.org/writing/dynamic-form-generation/ [2] https://www.caktusgroup.com/blog/2018/05/07/creating-dynamic-forms-django/

这是错误消息(图像只能作为链接附加): Attribute Error: 'SeasonalTextForm' object has no attribute 'instance'

这是我的模特。py

class PageComponent(models.Model):
    componentName=models.CharField(max_length=50,null=True, verbose_name="Name")
    type = models.ForeignKey(Type, on_delete=models.CASCADE)
    user = models.ForeignKey(AS_User, on_delete=models.CASCADE, editable=False)
    page = models.ForeignKey(CommunityPage, on_delete=models.CASCADE, editable=False)
    STATUS = (
        ('a', 'Activated'),
        ('d', 'Deactivated'),
    )

    componentStatus=models.CharField(
        max_length=1,
        choices=STATUS,
        blank=False,
        default='d',
        help_text='the current status of the page component', editable=False
    )

    textContent=models.TextField(max_length=10000, help_text="Enter a description for your component", null=True, blank=True)
    photoContent=models.ImageField(upload_to=component_directory_path, null=True, blank=True, verbose_name="Photo")
    # videoContent=models.VideoField(upload_to=component_directory_path, null=True, blank=True, verbose_name="Video")

class PageComponent_SeasonalText(models.Model):
    pageStextComponent = models.ForeignKey(PageComponent, on_delete=models.CASCADE)
    seasonalText = models.CharField(max_length=10001)

这是我的表格。py:

class SeasonalTextForm(forms.Form):
    componentName = forms.CharField(label=_('Enter title'),max_length=40)

    def __init__(self, *args, **kwargs):
        seasonTexts = kwargs.pop('extra')
        # super(SeasonalTextForm, self).__init__(*args, **kwargs)
        super(SeasonalTextForm, self).__init__(*args, **kwargs)
        # seasonTexts = PageComponent_SeasonalText.objects.filter(pageStextComponent = pageStextComponent)

        for i in range(seasonTexts):
            field_name = 'seasonText_%s' % (i,)
            self.fields[field_name] = forms.CharField(widget=forms.Textarea(attrs={'rows':10, 'cols':51}))
        #set field label as placeholder for every field
        for field in self.fields.values():
            field.widget.attrs["placeholder"] = field.label
        # field_name = 'seasonText_%s' % (i+1,)
        # self.fields[field_name] = forms.CharField(widget=forms.Textarea(attrs={'rows':10, 'cols':51}))
        # self.fields[field_name]=""

    def clean(self):
        seasonTexts = set()
        i = 0
        field_name = 'seasonText_%s'% (i,)
        while self.cleaned_data.get(field_name):
            seasonText = self.cleaned_data[field_name]
            if seasonText in seasonTexts:
                self.add_error(field_name, 'Duplicate')
            else:
                seasonTexts.add(seasonText)
            i += 1
            field_name='seasonText_%s' % (i,)
        self.cleaned_data["seasonTexts"] = seasonTexts

    def save(self):
        PageComponent = self.instance
        PageComponent.save()
        PageComponent.componentName = self.cleaned_data["componentName"]
        # pageStextComponent.seasonText_set.all().delete()
        for seasonalText in self.cleaned_data["seasonTexts"]:
            PageComponent_SeasonalText.objects.create(
                pageStextComponent = PageComponent.pageStextComponent,
                seasonalText = seasonalText,
            )

    def get_seasonText_fields(self):
        for field_name in self.fields:
            if field_name.startswith('seasonText'):
                yield self[field_name]

这是我的view.py:

def SeasonalText(request, page_id, id):
    page = get_object_or_404(CommunityPage, pk=page_id)
    as_user = get_object_or_404(AS_User, pk=id)
    # s_component = get_object_or_404(PageComponent, pk=cid)
    numOfSeasons = page.numSeasons
    form = SeasonalTextForm(request.POST, extra=numOfSeasons)
    # sTexts = PageComponent_SeasonalText.objects.filter(pageComponent_id=s_component)
    # form = SeasonalTextForm(request.POST, extra=sTexts)
    if request.method == "POST":
        if form.is_valid():
            form.save()
            # my_user = AS_User.objects.get(id=request.user.id)
            # my_type = Type.objects.get(id=4)
            # PageComponent.user = my_user
            # PageComponent.page = page
            # PageComponent.type = my_type
            # PageComponent.save()
            return HttpResponseRedirect(reverse('page', kwargs={'page_id':page_id}))
    else:
        form = SeasonalTextForm(extra=numOfSeasons)
    return render(request, 'communityPages/Stext_component.html', {'form':form, 'page':page, 'id':as_user})

0 个答案:

没有答案