Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 动态添加字段的django表单集能否具有持久数据?_Python_Database_Django_Django Forms - Fatal编程技术网

Python 动态添加字段的django表单集能否具有持久数据?

Python 动态添加字段的django表单集能否具有持久数据?,python,database,django,django-forms,Python,Database,Django,Django Forms,我正在用python/django制作一个表单集,需要在单击按钮时向表单集动态添加更多字段。我正在制作的表单是为我的学校询问学生他们想向谁披露某些学术信息,这里的按钮允许他们添加更多字段,以输入他们想向谁披露的家庭成员/人 我有一个按钮,可以显示额外的字段,您可以添加任意数量的字段。问题是,以前输入到现有字段中的数据会被删除。但是,只有表单集中的内容才会被删除。表单中先前填写的所有其他内容都保持不变 有没有办法让表单集保留按下按钮前输入的数据 form.py: from django impor

我正在用python/django制作一个表单集,需要在单击按钮时向表单集动态添加更多字段。我正在制作的表单是为我的学校询问学生他们想向谁披露某些学术信息,这里的按钮允许他们添加更多字段,以输入他们想向谁披露的家庭成员/人

我有一个按钮,可以显示额外的字段,您可以添加任意数量的字段。问题是,以前输入到现有字段中的数据会被删除。但是,只有表单集中的内容才会被删除。表单中先前填写的所有其他内容都保持不变

有没有办法让表单集保留按下按钮前输入的数据

form.py:

from django import forms
from models import Form, ParentForm, Contact
from django.core.exceptions import ValidationError

def fff (value):
    if value == "":
        raise ValidationError(message = 'Must choose a relation', code="a")

# Create your forms here.
class ModelForm(forms.ModelForm):   
    class Meta:
        model = Form
        exclude = ('name', 'Relation',)

class Parent(forms.Form):
    name = forms.CharField()

    CHOICES3 = (    
    ("", '-------'),
    ("MOM", 'Mother'),
    ("DAD", 'Father'),
    ("GRAN", 'Grandparent'),
    ("BRO", 'Brother'),
    ("SIS", 'Sister'),
    ("AUNT", 'Aunt'),
    ("UNC", 'Uncle'),
    ("HUSB", 'Husband'),
    ("FRIE", 'Friend'),
    ("OTHE", 'Other'),
    ("STEP", 'Stepparent'),
    )
    Relation = forms.ChoiceField(required = False, widget = forms.Select, choices = CHOICES3, validators = [fff])
models.py

from django.db import models
from django import forms
from content.validation import *
from django.forms.models import modelformset_factory

class Contact(models.Model):
    name = models.CharField(max_length=100)

class Form(models.Model):
    CHOICES1 = (
        ("ACCEPT", 'I agree with the previous statement.'),
        )
    CHOICES2 = (
        ("ACADEMIC", 'Academic Records'),
        ("FINANCIAL", 'Financial Records'),
        ("BOTH", 'I would like to share both'),
        ("NEITHER", 'I would like to share neither'),
        ("OLD", "I would like to keep my old sharing settings"),
        )

    Please_accept = models.CharField(choices=CHOICES1, max_length=200)
    Which_information_would_you_like_to_share = models.CharField(choices=CHOICES2, max_length=2000)
    Full_Name_of_Student = models.CharField(max_length=100)
    Carthage_ID_Number = models.IntegerField(max_length=7)
    I_agree_the_above_information_is_correct_and_valid = models.BooleanField(validators=[validate_boolean])
    Date = models.DateField(auto_now_add=True)
    name = models.ManyToManyField(Contact, through="ParentForm")

class ParentForm(models.Model):
    student_name = models.ForeignKey(Form)
    name = models.ForeignKey(Contact)

    CHOICES3 = (
    ("MOM", 'Mother'),
    ("DAD", 'Father'),
    ("GRAN", 'Grandparent'),
    ("BRO", 'Brother'),
    ("SIS", 'Sister'),
    ("AUNT", 'Aunt'),
    ("UNC", 'Uncle'),
    ("HUSB", 'Husband'),
    ("FRIE", 'Friend'),
    ("OTHE", 'Other'),
    ("STEP", 'Stepparent'),
    )
    Relation = models.CharField(choices=CHOICES3, max_length=200)
    def __unicode__(self):
        return 'name: %r, student_name: %r' % (self.name, self.student_name)
和视图.py

from django.shortcuts import render
from django.http import HttpResponse
from form import ModelForm, Parent
from models import Form, ParentForm, Contact
from django.http import HttpResponseRedirect
from django.forms.formsets import formset_factory

def create(request):
    ParentFormSet = formset_factory(Parent, extra=1)
    if request.POST:        
        Parent_formset = ParentFormSet(request.POST, prefix='Parent_or_Third_Party_Name')
        if 'add' in request.POST:
            list=[]
            for kitties in Parent_formset:
                list.append({'Parent_or_Third_Party_Name-0n-ame': kitties.data['Parent_or_Third_Party_Name-0-name'], 'Parent_or_Third_Party_Name-0-Relation': kitties.data['Parent_or_Third_Party_Name-0-Relation']})
            Parent_formset = ParentFormSet(prefix='Parent_or_Third_Party_Name', initial= list)
        form = ModelForm(request.POST)
        if form.is_valid() and Parent_formset.is_valid():
            form_instance = form.save()

            for f in Parent_formset:
                if f.clean():
                    (obj, created) = ParentForm.objects.get_or_create(name=f.cleaned_data['name'], Relation=f.cleaned_data['Relation'])

            return HttpResponseRedirect('http://Google.com')
    else:
        form = ModelForm()
        Parent_formset = ParentFormSet(prefix='Parent_or_Third_Party_Name')

    return render(request, 'content/design.html', {'form': form, 'Parent_formset': Parent_formset})
def submitted(request):
    return render(request, 'content/design.html')

提前谢谢你

我曾经试图做类似的事情,但被一个比我聪明得多的人指导。我从未完成过这个项目,所以我无法提供更多的帮助,但这可能是一个起点。

我以前在Django中动态添加字段时遇到过困难,这个堆栈溢出问题帮助了我:


老实说,我不完全确定在您的案例中“持久性”是什么意思——在您添加输入时是否删除了表单的值?你确定这与你的JS无关吗?

我的一位同事终于找到了答案。以下是修改后的views.py:

from django.shortcuts import render
from django.http import HttpResponse
from form import ModelForm, Parent
from models import Form, ParentForm, Contact
from django.http import HttpResponseRedirect
from django.forms.formsets import formset_factory

def create(request):
    ParentFormSet = formset_factory(Parent, extra=1)
    boolean = False
    if request.POST:        
        Parent_formset = ParentFormSet(request.POST, prefix='Parent_or_Third_Party_Name')
        if 'add' in request.POST:
            boolean = True
            list=[]
            for i in range(0,int(Parent_formset.data['Parent_or_Third_Party_Name-TOTAL_FORMS'])):
                list.append({'name': Parent_formset.data['Parent_or_Third_Party_Name-%s-name' % (i)], 'Relation': Parent_formset.data['Parent_or_Third_Party_Name-%s-Relation' % (i)]})
            Parent_formset = ParentFormSet(prefix='Parent_or_Third_Party_Name', initial= list)
        form = ModelForm(request.POST)
        if form.is_valid() and Parent_formset.is_valid():
            form_instance = form.save()                 

            for f in Parent_formset:
                if f.clean():
                    (contobj, created) = Contact.objects.get_or_create(name=f.cleaned_data['name'])
                    (obj, created) = ParentForm.objects.get_or_create(student_name=form_instance, name=contobj, Relation=f.cleaned_data['Relation'])

            return HttpResponseRedirect('http://Google.com')
    else:
        form = ModelForm()
        Parent_formset = ParentFormSet(prefix='Parent_or_Third_Party_Name')

    return render(request, 'content/design.html', {'form': form, 'Parent_formset': Parent_formset, 'boolean':boolean})
def submitted(request):
    return render(request, 'content/design.html')

感谢您的输入,回答的人:)

如果您的表单集没有显示您之前的输入,这意味着它没有看到模型的查询集。将queryset添加到formset参数以解决此问题。例如:

formset = SomeModelFormset(queryset=SomeModel.objects.filter(arg_x=x))

如果我决定朝这个方向走,这是一个很好的起点,但形式已经基本形成,唯一缺少的就是坚持。。。我希望我能实现一些东西,而不是重写整个表单,希望我能提供更多帮助。我会自己看这个问题,因为我从来没有超过这一点。只要投一张赞成票和一张最喜欢的票,让我们看它走吧!另外,对样式的友好评论:您可能希望模型中的所有字段都使用小写字母。当您在该值和大写值之间切换(例如,表单模型的“name”和“Date”)时,表单集中的值将被删除。当然,现在我开始悬赏了,我的一个同事帮我弄明白了,我才意识到我从来没有接受过你的回答。对不起!