2015-01-20 6 views
4

나는 공식 장고 자습서에서 작성된 투표소 응용 프로그램에 더 많은 기능을 추가하려고합니다. 내가하고있는 일 중 하나는 로그인 한 사용자 (설문서가 우리를 떠나는 관리자 화면 대신)로 설문 조사/선택 사항을 생성 할 수 있도록하는 것입니다.하나의 장고보기에서 두 양식 결합하기

사용자가 설문 조사를 작성하고 설문 조사에 연결할 수있는 선택 사항을 포함 할 수있는보기를 만들려고합니다. 장고 관리자가 자동으로 그것을 수행하고, 나는 이것을보기에 쓰는 방법에 대해 확신 할 수 없다. ,

models.py

import datetime 

from django.db import models 
from django.utils import timezone 


class Poll(models.Model): 
    question_text = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published') 

    def __unicode__(self): 
     return self.question_text 

    def was_published_recently(self): 
     return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 

    was_published_recently.admin_order_field = 'pub_date' 
    was_published_recently.boolean = True 
    was_published_recently.short_description = 'Published recently?' 

class Choice(models.Model): 
    question = models.ForeignKey(Poll) 
    choice_text = models.CharField(max_length=200) 
    votes = models.IntegerField(default=0) 

    def __unicode__(self): 
     return self.choice_text 

forms.py 현재

from django import forms 
from .models import Poll, Choice 
from datetime import datetime 

class PollForm(forms.ModelForm): 
    question_text = forms.CharField(max_length=200, help_text="Please enter the question.") 
    pub_date = forms.DateTimeField(widget=forms.HiddenInput(), initial = datetime.now()) 

    class Meta: 
     model = Poll 
     fields = ("__all__") 

class ChoiceForm(forms.ModelForm): 
    choice_text = forms.CharField(max_length=200, help_text="Please enter choices.") 
    votes = forms.IntegerField(widget=forms.HiddenInput(),initial=0) 
    exclude = ('poll',) 

views.py

def add_poll(request): 
    # A HTTP POST? 
    if request.method == 'POST': 
     form = PollForm(request.POST) 

     # Have we been provided with a valid form? 
     if form.is_valid(): 
      # Save the new category to the database. 
      form.save(commit=True) 

      # Now call the index() view. 
      # The user will be shown the homepage. 
      return render(request, 'polls/index.html', {}) 
     else: 
      # The supplied form contained errors - just print them to the terminal. 
      print form.errors 
    else: 
     # If the request was not a POST, display the form to enter details. 
     form = PollForm() 

    # Bad form (or form details), no form supplied... 
    # Render the form with error messages (if any). 
    return render(request, 'polls/add_poll.html', {'form': form}) 

: 시작하기

이 내 관련 파일입니다 내보기를 사용하면 사용자가 설문 조사. 입력 된 텍스트를 Poll 모델의 question_text, Choice 모델 및 ChoiceForm으로 전달하는 방법에 대해서는 확신 할 수 없습니다.

모든 안내 및 권장 사항은 언제나 감사하겠습니다!

건배, 폴

+0

당신은 이것을 보았습니까? http://stackoverflow.com/questions/2770810/multiple-models-in-a-single-django-modelform –

답변

14

Formsets 장고에 그것을 할 수있는 방법입니다.

먼저 Poll.pub_date 필드 default 값을 추가

class PollForm(forms.ModelForm): 
    class Meta: 
     model = Poll 
     fields = ('question_text',) 

class ChoiceForm(forms.ModelForm): 
    class Meta: 
     model = Choice 
     fields = ('choice_text',) 

보기에 해당 formset 지원을 추가 : 마지막으로 당신의

from django.forms.formsets import formset_factory 

def add_poll(request): 
    ChoiceFormSet = formset_factory(ChoiceForm, extra=3, 
            min_num=2, validate_min=True) 
    if request.method == 'POST': 
     form = PollForm(request.POST) 
     formset = ChoiceFormSet(request.POST) 
     if all([form.is_valid(), formset.is_valid()]): 
      poll = form.save() 
      for inline_form in formset: 
       if inline_form.cleaned_data: 
        choice = inline_form.save(commit=False) 
        choice.question = poll 
        choice.save() 
      return render(request, 'polls/index.html', {}) 
    else: 
     form = PollForm() 
     formset = ChoiceFormSet() 

    return render(request, 'polls/add_poll.html', {'form': form, 
                'formset': formset}) 

class Poll(models.Model): 
    question_text = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published', default=timezone.now) 

는 그런 형태의 약간의 간단한을 만들 템플릿 :

<form method="post"> 

    {% csrf_token %} 

    <table> 
     {{ form }} 
     {{ formset }} 
    </table> 

    <button>Add</button> 

</form> 
+0

정말 catowaran 고맙습니다! 그것은 대단히 도움이되었습니다, 당신이 거기에 갔을 때 감사드립니다! 나는 formset_factory가 어떻게 사용되었는지 알지 못했지만 특히 그 값을 extra와 validate_min과 같은 속성을 가진 많은 로직을 다루는 방법으로 봅니다. inline_form에 대해 좀 더 연구해야한다고 생각합니다. 다시 한 번 감사드립니다! – ploo

+0

이 저장은 데이터베이스에있는 하나의 테이블에만 저장됩니까? 감사! – jned29

+0

@ jned29 각 양식은 연관된 모델의 관련 테이블에 저장됩니다. 그래서 Django 앱이 "quest"라고 불리면 PollForm은 데이터를'quest_poll' 테이블 (1 레코드 업데이트)에 저장하고'ChoiceForm'은 데이터를'quest_choice' 테이블 ('FormSet'으로 인해 업데이트 된 여러 레코드)에 저장합니다.). – interDist