如何根據我的模型在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'),
表單操作與Django無關,它只是表單提交的URL。 '「。」'是表示「當前路徑」的捷徑。 –
好吧,那麼這是否意味着我需要在我的urls.py中聲明指定哪種方法來處理這個問題? – Codejoy
嗯,當然是,但重點是顯示錶單並處理它的URL是相同的。 –