2016-07-27 66 views
1

如何根據我的模型在django中構建表單。我有這個在我的views.py:如何在django中使用views.py中的類來創建表單

class GroupCreateView(CreateView): 
    model = Group 
    form_class = GroupForm 
    template_name = 'ipaswdb/group/group_form.html' 

模板是好看了一些很好的形式,CSS和一個日期選擇器等。我還創建了一個表格,以便我可以在我的forms.py添加小工具

class GroupForm(forms.ModelForm): 
    notes=forms.CharField(widget = forms.Textarea) 
    billing_address = forms.ModelChoiceField(queryset=Address.objects.all(), widget=forms.Select(attrs={'tabindex':'5'})) 
    start_date = forms.DateField(widget=forms.TextInput(attrs= 
           { 
            'class':'datepicker', 
            'tabindex' : '5', 
            'placeholder' : 'Groups start date' 
           })) 

    class Meta: 
     model=Group 
     exclude = ['created_at', 'updated_at'] 

這一切對我來說很有意義,我可以看到形式是如何構建基於關我的模型,並得到的東西填充在ModelChoiceField說等等。我只是不確定我的views.py中的def some_method是如何起作用的。所以在我的表單動作的表單模板,我有這個:

<h1> Add a new Group </h1> 
    <form action="." method="post"> 
    {% csrf_token %} 
    <div class="col-2"> 
    {{ form.group_name.errors }} 
    <label> 
     Group Name: 
     <input placeholder="Enter the groups name" id="id_group_name" name="group_name" tabindex="1"> 
    </label> 
    </div> 
    <div class="col-2"> 
     {{ form.group_contact.errors }} 

    <label> 
     Gorup Contact 
     <input placeholder="Enter the groups contact name" id="id_group_contact" name="group_contact" tabindex="2"> 
    </label> 
    </div> 

    <div class="col-2"> 
    {{ form.tin.errors }} 
    <label> 
     TIN Number 
     <input placeholder="Groups TIN#" id="id_tin" name="tin" tabindex="3"> 
    </label> 
    </div> 
    <div class="col-2"> 
    {{ form.npi.errors }} 
    <label> 
     NPI Number 
     <input placeholder="Groups NPI#" id="id_npi" name="npi" tabindex="4"> 
    </label> 
    etc etc etc 

我認爲在視圖中調用一些默認方法?我只是不確定那是什麼方法。這也是爲了添加一個新的組,我猜我需要另一個視圖或其他東西來處理他們正在編輯已經存在的組的情況?我使用的這個博客演示在views.py中用forms.py完成了這一切,我認爲這裏沒有類GroupCreateView(CreateView):在我使用views.py的例子中,esque方法是有效的方法(注意:不是我的方法):

def post_detail(request, year, month, day, post): 
    post = get_object_or_404(Post, slug=post, 
          status='published', 
          publish__year=year, 
          publish__month=month, 
          publish__day=day) 

    comments = post.comments.filter(active=True) 
    #their form stuff 
    if request.method == 'POST': 
     comment_form = CommentForm(data=request.POST) 
     if comment_form.is_valid(): 
      new_comment = comment_form.save(commit=False) 
      new_comment.post = post 
      new_comment.save() 
    else: 
      comment_form=CommentForm() 

    return render(request, 
        'blog/post/detail.html', 
        {'post': post, 'comments':comments, 'comment_form':comment_form}) 

我的問題是(我不記得什麼例子來引用它),但什麼是class GroupCreateView(CreateView):真的這樣做,我怎樣才能得到它引用/創建回來形式調用正確的行動最終讓我驗證並保存到數據庫?

另外第二種方式是,我怎樣才能擴展它(大致)來處理添加一個新組的情況,也可能是另一種情況,即它正在編輯現有的組? (我在這裏問第二個問題,因爲我確信它與第一個問題的答案有關)。

從我的urls.py

url(r'group/add/$', GroupCreateView.as_view(), name='group-add'), 
+0

表單操作與Django無關,它只是表單提交的URL。 '「。」'是表示「當前路徑」的捷徑。 –

+0

好吧,那麼這是否意味着我需要在我的urls.py中聲明指定哪種方法來處理這個問題? – Codejoy

+0

嗯,當然是,但重點是顯示錶單並處理它的URL是相同的。 –

回答

1

不要害怕閱讀Django的源代碼:P,通用類有兩個方法:「get」和「後」(與「放」過,但它調用「發佈」),如果需要,可以覆蓋其中的任何一個。

class BaseCreateView(ModelFormMixin, ProcessFormView): 
    """ 
    Base view for creating an new object instance. 

    Using this base class requires subclassing to provide a response mixin. 
    """ 
    def get(self, request, *args, **kwargs): 
     self.object = None 
     return super(BaseCreateView, self).get(request, *args, **kwargs) 

    def post(self, request, *args, **kwargs): 
     self.object = None 
     return super(BaseCreateView, self).post(request, *args, **kwargs) 

但它也繼承了它的父母的方法,所以它可能有點難以閱讀。我總是檢查docs for the generic views,它給出了你可以覆蓋每個泛型類的所有方法的列表。現在,您可以覆蓋你想不重複的代碼,所有的方法(這就是爲什麼我< 3 CBV)

我覺得你的情況,你可能要覆蓋form_valid()方法重定向到成功頁面

之前做一些事情希望這可以幫助

+2

你應該避免覆蓋get和post,幾乎總是有更具體的方法 - 比如form_valid,就像你提到的那樣。 –

+0

我試過包括一個success_url,並且在提交時沒有任何反應。我在想我的表單在某種程度上失敗了嗎?然而,奇怪的是,返回的錯誤是正確的。如果我把它留空白說空白錯誤,如果我給一個壞日期不好的日期。我敢打賭,我的模型認爲應該存在的所有內容都沒有form.field.errors,並且導致了糟糕的UI反饋。仔細檢查這一點。 – Codejoy

+1

謝謝你們這一切工作。我現在正在嘗試使用UpdateView模型,它會自動填充非常棒的字段。只要我使用{{form.group_name}}而不是直接的html方法: 我是猜測,儘管我現在可以將所有的東西都封裝起來以獲得這個功能 – Codejoy

相關問題