2012-07-08 81 views
3

所以我已經有一個數據庫設置,有幾列和幾行已經插入。我試圖創建一個視圖,你只需要輸入信息到一個表單,然後按提交,然後一行將被添加到MySQL數據庫與您剛輸入的信息。Django - 將行添加到MySQL數據庫

我相信你可以做到這一點與管理員,但我想嘗試沒有管理員,我不知道這是可能的嗎?我一直在使用MySQL命令行來添加行到現在爲止。

回答

10

這是可能的,這是數據驅動的網站的構建塊。您可以像Daniel建議的那樣使用ModelForm(它們提供免費的內置驗證和HTML標記),可以輕鬆將您的模型映射到前端表單。首先從django教程或文檔開始,可能會有所幫助。

在非常基本的,所有你需要做的就是實例化模型

new_entry = YourModel(name='me', age='222', about='stackoverflow') 

然後將其保存

new_entry.save() 

這增加了它作爲一個新行到你的數據庫。

https://docs.djangoproject.com/en/dev/topics/db/models/

0

試用通用視圖的這個例子:http://postneo.com/2005/08/17/django-generic-views-crud(假設名爲任務模型)

和您插入,更新和刪除免費,沒有任何實際工作通用視圖。試試看,讓我知道你的想法。

from django.conf.urls.defaults import * 

info_dict = { 
    'app_label': 'tasks', 
    'module_name': 'tasks', 
} 

urlpatterns = patterns('', 
    (r'^tasks/create/?$', 'django.views.generic.create_update.create_object', info_dict), 
    (r'^tasks/update/(?P<object_id>\d+)/?$', 'django.views.generic.create_update.update_object', info_dict), 
    (r'^tasks/delete/(?P<object_id>\d+)/?$', 'django.views.generic.create_update.delete_object', info_dict), 
) 

Django文檔:https://docs.djangoproject.com/en/1.2/ref/generic-views/#create-update-delete-generic-views