Django表单初始将列表传递给一个属性

时间:2018-09-17 22:54:04

标签: python django django-forms

当我想在初始表单期间将值列表传递给一个属性时遇到一个问题。

我正在做的整个过程是: 1.用户定义数字N。 2.我显示N个文本字段。 3.用户填写数据,然后将其存储在数据库中。 4.用户想要修改数据->这是我遇到的问题。我想用当前数据来初始化表格。

这是我的模特。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.FileField(upload_to=component_directory_path, null=True, blank=True, verbose_name="Video")

    def __str__(self):
        return self.componentName

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)

        # self.cleaned_data = {}
        for i in range(0, 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

    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):

        for seasonalText in self.cleaned_data["seasonTexts"]:
            PageComponent_SeasonalText.objects.create(pageStextComponent = PageComponent.pageStextComponent,seasonalText = seasonalText,)

这是我的观点。py

def edit_stext(request, page_id, id):
    page = get_object_or_404(CommunityPage, pk=page_id)
    component = PageComponent.objects.get(id=id)
    stext = PageComponent_SeasonalText.objects.filter(pageStextComponent=component)
    numOfSeasons = page.numSeasons
    if request.method == "POST":
        stextEditor = SeasonalTextForm(request.POST, instance=stext, extra=numOfSeasons)
        if stextEditor.is_valid():
            stextEditor.save()
            return HttpResponseRedirect(reverse('page', kwargs={'page_id' : page_id}))
    else:
        # stext1 = PageComponent_SeasonalText.objects.filter(pageStextComponent=component)
        initial = {}
        initial['componentName'] = component.componentName
        for i in range(0,numOfSeasons):
            st = stext[i].seasonalText
            print(st)
            initial['seasonalText_{}'.format(i)] = st
        stextEditor = SeasonalTextForm(initial=initial, extra=numOfSeasons)
    return render(request, 'editComponent_stext.html', {'stextEditor': stextEditor})

注意: 在view.py上,我具有打印功能,可以打印属性“ seasonalText”的实际值,并且成功。但是,当我想初始化表格时,似乎无法传递给初始字母。

感谢您花费所有时间来帮助我解决此问题。非常感谢。

用于理解的屏幕截图:

print function gets the correct value

initialed form doesn't get the seasonalText value

0 个答案:

没有答案