2013-08-01 31 views
7

Tôi đang thực hiện một formset trong python/django và cần phải tự động thêm nhiều trường vào một formset như một nút được bấm. Hình thức tôi đang làm là cho trường học của tôi yêu cầu những sinh viên muốn tiết lộ thông tin học tập nhất định và nút ở đây cho phép họ thêm nhiều trường hơn để nhập thành viên gia đình/những người mà họ muốn tiết lộ.Tập hợp django có thể tự động thêm trường có dữ liệu liên tục không?

Tôi có nút hoạt động đến điểm mà các trường bổ sung hiển thị và bạn có thể thêm bao nhiêu tùy thích. Vấn đề là, dữ liệu đã được nhập trước đó vào các trường đã tồn tại sẽ bị xóa. Tuy nhiên, chỉ có những thứ trong formset bị xóa. Mọi thứ khác đã được điền trước đó trong biểu mẫu vẫn liên tục.

Có cách nào để làm cho biểu mẫu lưu giữ dữ liệu được nhập trước khi nhấn nút không?

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) 

và 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) 
    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') 

Cảm ơn bạn trước!

Trả lời

7

Tôi đã có rắc rối với động thêm lĩnh vực trong Django trước và câu hỏi stackoverflow này đã giúp tôi: dynamically add field to a form

Thành thật mà nói, tôi không hoàn toàn chắc chắn những gì bạn có ý nghĩa bởi "dai dẳng" trong trường hợp của bạn - giá trị của các biểu mẫu của bạn bị xóa khi bạn thêm đầu vào là gì? Bạn có chắc chắn nó không phải là một cái gì đó với JS của bạn?

+2

Ngoài ra, nhận xét thân thiện về phong cách: bạn có thể muốn làm cho tất cả các trường trong mô hình của bạn là lowercase_underscore. Bạn đang chuyển đổi giữa giá trị đó và viết hoa (ví dụ: "tên" và "Ngày" cho mẫu Biểu mẫu của bạn) – Temuz

+0

Các giá trị trong biểu mẫu đã bị xóa. Tất nhiên, bây giờ mà tôi bắt đầu một tiền thưởng một trong những đồng nghiệp của tôi con số nó ra cho tôi –

+0

Chỉ cần nhận ra tôi không bao giờ chấp nhận câu trả lời của bạn. Xin lỗi vì điều đó! –

3

Tôi đã từng cố gắng làm điều gì đó như thế này, và được một người đàn ông khôn ngoan hơn I. Tôi chưa bao giờ hoàn thành dự án nên tôi không thể giúp đỡ nhiều hơn thế, nhưng nó có thể là điểm khởi đầu .

+0

Đó là một nhảy lớn tắt điểm nếu tôi quyết định đi theo hướng đó, nhưng dưới hình thức là khá nhiều được thực hiện, và tất cả những gì còn thiếu là sự kiên trì ... Tôi đã hy vọng sẽ có một cái gì đó tôi chỉ có thể thực hiện, như trái ngược với viết lại toàn bộ hình thức –

+0

Chúc tôi có thể giúp đỡ nhiều hơn nữa. Tôi sẽ tự mình xem câu hỏi này, vì tôi chưa bao giờ vượt qua điểm này. – TylerLubeck

+0

chỉ cần ném nó một upvote và một yêu thích và chúng ta hãy xem nó đi! –

3

Đồng nghiệp của tôi cuối cùng đã tìm ra. Đây là views.py sửa đổi:

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

Cảm ơn bạn đã nhập vào của bạn, những người bạn của những người đã trả lời :)

Các vấn đề liên quan