本文也是看了网络上的一些django文章后弄出,加上自己个人的一点心得和想法。
django-groundwork可以为一个app里面的model的添加 增删 的功能,以下是在django1.7的版本下部署,网络上也有一些是一些过去1.4之类的部署。
django1.7的部署,在github上下载后,把该文件夹放在项目下,和app,manage.py同级。然后在setting.py上的INSTALLED_APPS添加进去,很简单。
之后可以python manage.py help查看是否加入了新的命令 groundwork。
确定后运行python manage.py app modelname
其中modelname 就是你在app里面的需要添加功能的models名字。
运行命令后输出Y确定执行。会在app里面生成新的views,urls,forms文件,template会生成界面。
url.py里面会显示错误,记得加入from django.conf.urls import patterns。
app/urls.py
from django.conf.urls import patterns from models import * from views import * urlpatterns = patterns('', (r'product/create/$', create_product), (r'product/list/$', list_product ), (r'product/edit/(?P<id>[^/]+)/$', edit_product), (r'product/view/(?P<id>[^/]+)/$', view_product), )
最后两个url的里面后部分是正则表达式,意思是会接受id的,他会get来自网页的参数,参数会赋给id,之后会传递给views里面的对应的def,经过对应的函数后return回去给网页。
在setting.py的文件夹里面的url可以在里面加入app文件夹的url。
记得在setting里面加入
TEMPLATE_DIRS = (
'templates',
)
不然会显示读取不到template。
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'depot.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^prodect/',include('depotapp.urls')), )
app/views.py
def create_product(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() form = ProductForm() t = get_template('depotapp/create_product.html') c = RequestContext(request,locals()) return HttpResponse(t.render(c)) def list_product(request): list_items = Product.objects.all() paginator = Paginator(list_items ,10) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: list_items = paginator.page(page) except : list_items = paginator.page(paginator.num_pages) t = get_template('depotapp/list_product.html') c = RequestContext(request,locals()) return HttpResponse(t.render(c)) def view_product(request, id): product_instance = Product.objects.get(id = id) t=get_template('depotapp/view_product.html') c=RequestContext(request,locals()) return HttpResponse(t.render(c)) def edit_product(request, id): product_instance = Product.objects.get(id=id) form = ProductForm(request.POST or None, instance = product_instance) if form.is_valid(): form.save() t=get_template('depotapp/edit_product.html') c=RequestContext(request,locals()) return HttpResponse(t.render(c))
app/forms.py
class ProductForm(forms.ModelForm): class Meta: model = Product # exclude = [] # uncomment this line and specify any field to exclude it from the form def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs)
django-groundwork帮我们生成这么多打码,逻辑不难看懂,我是一个django入门级别的,可以学到很多。