我正在将一个项目放在一起,并尝试尽可能多地利用开源库,以最大限度地减少完成工作所涉及的“打字”。我正在使用 django、crispy-forms 和引导框架。
我编写了用于处理一个实体(添加/编辑/删除)的代码,并且感觉我一定做错了什么,因为似乎涉及的代码太多 - 有 20 多个不同的项目将以几乎相同的方式进行管理所以我想在我开始完成其余代码之前,我会询问社区我可以修复的错误。
所以我有一个模型:
class Link(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name=_(u'Название'))
url = models.URLField(blank=False, null=False, verbose_name=_(u'Ссылка'))
project = models.ForeignKey('Project')
display_on_main_project_page = models.BooleanField(default=False, verbose_name=_(u'Показывать ссылку на главной странице проекта'))
class Meta:
app_label = 'core'
verbose_name = _(u'Ссылка')
verbose_name_plural = _(u'Ссылки')
def __unicode__(self):
return self.name
并按照手册添加了一个带有脆片的表格:
class ProjectLinkForm(forms.Form):
id = forms.IntegerField(required=False, widget=forms.HiddenInput())
project = forms.ModelChoiceField(queryset=Project.objects.all(),required=True, widget=forms.HiddenInput())
name = forms.CharField(required=True, label=_(u'Имя ссылки'))
url = forms.URLField(required=True, label=_(u'URL ссылки'))
display_on_main_project_page = forms.BooleanField(label=_(u'Показывать на главной странице проекта'), required=False)
class Meta:
model = Link
fields = ('project','name','url','display_on_main_project_page')
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_class = 'horizontal-form'
self.helper.form_action = ''
self.helper.form_id = 'link_form'
self.helper.layout = Layout(
Field('name',css_class='input-block-level'),
Field('url', css_class='input-block-level')
)
super(ProjectLinkForm, self).__init__(*args, **kwargs)
和配置为提供操作的 url:
url(r'^forms/link/add/(?P<project_id>\d+)/$','core.views.forms.link.add'),
url(r'^forms/link/edit/(?P<link_id>\d+)/$','core.views.forms.link.edit'),
url(r'^forms/link/delete/(?P<link_id>\d+)/$','core.views.forms.link.delete'),
以及视图(以add为例):
@login_required
def add(request, project_id):
if request.method == 'GET':
form = ProjectLinkForm(initial={'project':project_id})
form.action = 'add'
form.submit_url = request.path
return render_to_response('core/forms/project_link.html',{'form':form,'links_form_title':_(u'Добавить ссылку')},context_instance=RequestContext(request))
elif request.method == 'POST':
form = ProjectLinkForm(request.POST)
form.action = 'add'
form.submit_url = request.path
if form.is_valid():
try:
new_link = Link()
new_link.name = form.cleaned_data['name']
new_link.url = form.cleaned_data['url']
new_link.project = form.cleaned_data['project']
new_link.display_on_main_project_page = form.cleaned_data['display_on_main_project_page']
new_link.save()
return HttpResponse(status=http_statuses.SAVED, content="saved")
except Exception as e:
return HttpResponse(status=http_statuses.SERVER_ERROR, content=e.message)
else:
return render_to_response('core/forms/project_link.html',{'form':form,'links_form_title':_(u'Добавить ссылку')},context_instance=RequestContext(request))
#not POST or GET
else:
return HttpResponse(status=http_statuses.METHOD_NOT_ALLOWED,content=_(u'Недопустимый тип запроса'))
所有操作都使用一个模板:
{% load crispy_forms_tags %}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>{{ links_form_title|default:"Ссылки на проект" }}</h3>
</div>
<div class="modal-body">
<p>
{% if form.action == "delete" %}
Уверены, что хотите удалить ссылку "{{ form.name.value }}"? Одно неосторожное движенье мышкой и все - не вернешь!
<div class="hide">
{% crispy form %}
</div>
{% else %}
{% crispy form %}
{% endif %}
</p>
</div>
<div class="modal-footer">
{% if form.action == "delete" %}
<a href="#" class="btn btn-danger" id="" onclick='SubmitModalForm($("#link_form"),"{{ form.submit_url }}")'>Удалить</a>
{% else %}
<a href="#" class="btn btn-primary" id="" onclick='SubmitModalForm($("#link_form"),"{{ form.submit_url }}")'>Сохранить</a>
{% endif %}
</div>
和一些 JavaScript 代码来处理所有带有表单的弹出窗口:
function LoadModalForm(url){
$("#dynamic_project_forms").html("").load(url).modal();
}
function SubmitModalForm(the_form,submit_url){
$.ajax({
type:'POST',
url:submit_url,
data: $(the_form).serialize(),
complete: function(e, xhr, settings){
if(e.status == 201){//HTTP.STATUS.SAVED
$("#dynamic_project_forms").modal('hide');
$(activeTab.hash).load('/api/get_project_tab/'+activeTab.hash.replace('#','')+'/{{ project.id }}/');
}
else{
$("#dynamic_project_forms").html(e.responseText);
alert('loaded fucking response');
}
}
});
}
它确实有效,但打字太多 - 我想我错过了一些东西或者只是没有得到正确的东西 - 请就正确的方法提出建议。