2017-02-19 10 views
0

が、私は、フォーム以下の書いたのModelFormします移行フォームは

class VoteForm(forms.Form): 
    choice = forms.ModelChoiceField(queryset=None, widget=forms.RadioSelect) 

    def __init__(self, *args, **kwargs): 
     question = kwargs.pop('instance', None) 
     super().__init__(*args, **kwargs) 

     if question: 
      self.fields['choice'].queryset = question.choice_set 

class VoteView(generic.UpdateView): 
    template_name = 'polls/vote.html' 
    model = Question 
    form_class = VoteForm 

    def get_queryset(self): 
     return Question.objects.filter(pub_date__lte=timezone.now()).exclude(choice__isnull=True) 

    def get_context_data(self, **kwargs): 
     context = super().get_context_data(**kwargs) 
     # Check duplicate vote cookie 
     cookie = self.request.COOKIES.get(cookie_name) 
     if has_voted(cookie, self.object.id): 
      context['voted'] = True 
     return context 

    def get_success_url(self): 
     return reverse('polls:results', args=(self.object.id,)) 

    def form_valid(self, form): 
     redirect = super().form_valid(form) 

     # Set duplicate vote cookie. 
     cookie = self.request.COOKIES.get(cookie_name) 
     half_year = timedelta(weeks=26) 
     expires = datetime.utcnow() + half_year 
     if cookie and re.match(cookie_pattern, cookie): 
      redirect.set_cookie(cookie_name, "{}-{}".format(cookie, self.object.id), expires=expires) 
     else: 
      redirect.set_cookie(cookie_name, self.object.id, expires=expires) 

     return redirect 

問題は、通常のフォームはのModelFormのようにsave()メソッドを持たないオブジェクトを表していないということです。しかし、私はフォームを移行する方法を理解できません。選択の余地やchoice_setフィールドがありません:

class VoteForm(forms.ModelForm): 
    class Meta: 
     Model = Question 
     #throws exception 
     fields = ('choice',) 
     widgets = { 
      'choice': forms.RadioSelect() 
        } 

EDIT:ここ はモデルがある:

フォームは、上からのModelFormとして再生することができますどのように
class Question(models.Model): 
    question_text = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published') 

class Choice(models.Model): 
    question = models.ForeignKey(Question, on_delete=models.CASCADE) 
    choice_text = models.CharField(max_length=200) 
    votes = models.IntegerField(default=0) 

+0

モデルを示してください。 – knbk

+0

私はモデルを追加しました。 – R3turnz

答えて

1

ModelFormがあっても、必要に応じて追加のフィールドを定義することができます。あなたの場合、前の通常の形式のように選択フィールドになります。

メタでは、質問モデルの必須ではないすべてのフィールドを除外します。

その後、initで、選択肢のインスタンスに選択肢のセットを提供します。

class VoteForm(forms.ModelForm): 
    choice = forms.ModelChoiceField(queryset=None, widget=forms.RadioSelect) 

    class Meta: 
     model = Question 
     exclude = ['question_text','pub_date'] 

    def __init__(self, *args, **kwargs): 
     super(VoteForm, self).__init__(*args, **kwargs) 
     instance = getattr(self, 'instance', None) 
     if instance: 
      self.fields['choice'].queryset = instance.choice_set 

コードは、オンラインで書かれており、テストされていませんが、私はそれが動作するはずだと思います。

関連する問題