Django Formset未正确处理

时间:2014-07-10 11:25:59

标签: python django forms formset

我正在制作一个网络应用程序,用于在校际比赛中为不同的活动注册团队。

活动的注册将通过包含Django formset的网页进行。

我的问题是,尽管formset的所有元素都显示在网页上,但当我点击"提交"按钮就可以了,根本没有处理相关数据。

另外,正如BaseEventTeamFormset()中的forms.py所示,当mem3为测验时,表格中应该有一个名为event.label的第三个文字字段。但是,第3个字段无法显示在网页上。

我在这里包含了必要的文件。请帮我纠正这个错误。

models.py

from django.db import models
from django.contrib.auth.models import User


class School(models.Model):

    user = models.OneToOneField(User)
    name = models.CharField('Name of school', max_length=30)
    currCap = models.IntegerField('Current Capital')

    def __unicode__(self):
        return self.name


class Event(models.Model):

    EVENTS = (
    ('Quiz', 'Quizzing'),
    ('Design', 'Design'),
    ('Robot', 'Robotics'),
    ('Prog', 'Programming'),
    ('Photo', 'Photography'),
#   ('SurEven', 'Surprise Event'),
)

    memDict = {
    'Quiz': 3,
    'Design': 2,
    'Robot': 2,
    'Prog': 2,
    'Photo': 1,
#   'SurEven': 2,   
}

    name = models.CharField('Name of event', max_length = 20, choices = EVENTS)

    def __unicode__(self):
        return self.name.verbose_name


class EventTeam(models.Model):

    school = models.ForeignKey('School')
    event = models.ForeignKey('Event')

    def __unicode__(self):
        str = self.event + ': ' + self.school.name
        return str


class Member(models.Model):

    name = models.CharField('Name of member', max_length = 20)
    events = models.ManyToManyField('EventTeam')

    def __unicode(self):
        return self.name

forms.py

class EventTeamForm(forms.Form):

    event = forms.BooleanField()
    mem1 = forms.CharField(label="Member 1", max_length = 20)
    mem2 = forms.CharField(label="Member 2", max_length = 20, required = False)

    if event.label == 'Quizzing':
        mem3 = forms.CharField(label="Member 3", max_length = 20, required = False)

class BaseEventTeamFormSet(BaseFormSet):

    def __init__(self, *args, **kwargs):
        super(BaseEventTeamFormSet, self).__init__(*args, **kwargs)

    for i in range(0, len(Event.EVENTS)):
        self[i].fields['event'].label = Event.EVENTS[i][1]


class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ('name', 'descr', 'upForAcq'
    )

views.py

@login_required(login_url = '/xdashboard/login/')
def register(request):

    context = RequestContext(request)
    currSchool = School.objects.get(user = request.user)
    eventTuple = Event.EVENTS
    noOfEvents = len(eventTuple)
    EventTeamFormSet = formset_factory(EventTeamForm, extra = noOfEvents - 1, formset=BaseEventTeamFormSet)

    if request.method == 'POST':
        formset = EventTeamFormSet(request.POST, request.FILES)

        if formset.is_valid():  
            i = 0
            for form in formset:
                participating = form.cleaned_data['event']

                if participating == True:

                    event = Event.objects.get(pk = i+1)

                    mem1 = form.cleaned_data['mem1']
                    mem1 = Member(name = mem1)
                    mem1.save()
                    mem2 = form.cleaned_data['mem2']
                    mem2 = Member(name = mem2)
                    mem2.save()

                    if event == "Quiz":
                        mem3 = form.cleaned_data['mem3']
                        mem3 = Member(name = mem3)
                        mem3.save()

                    # creating database queries, many mistakes!

                    team = EventTeam(school = currSchool, event = event)
                    team.save()
                    mem1.events.add(team) # adding the members to the team
                    mem2.events.add(team)
                    try:
                        mem3.events.add(team)
                    except NameError:
                        pass

                    i += 1

    else:
        formset = EventTeamFormSet()

    context_dict = {
    'formset': formset,
    }

    return render_to_response('xdashboard/register.html', context_dict, context)

1 个答案:

答案 0 :(得分:0)

看起来你的for循环在你的forms.py中缺少适当的缩进,并且需要在__init__()方法中。查看模板代码会有所帮助。我最好的猜测是,您的formset.is_valid()方法返回false,并且您的提交数据处理都不会在POST上发生。

为了便于调试,请在模板中使用{{ field.errors }}{{ forms.non_field_errors }}