Django - Add rows to MySQL database

对着背影说爱祢 提交于 2019-12-07 06:20:01

问题


So I already have a database setup with a few columns and a few rows already inserted in. I'm trying to create a view that you would just input information into a form and press Submit, then a row would be added to the MySQL database with the information you just typed in.

I believe you can do this with admin, but I would like to try without admin and I'm not sure if this is possible? I've been using the MySQL commandline to add rows as of now..


回答1:


Of coures this is possible this is a building block for data driven websites. You can use a ModelForm as Daniel suggested (they offer built in validation and HTML markup for FREE) to easily map your model to a front end form. It would probably be beneficial to start with django tutorial or documentation first.

At the the very basic, all you have to do is instantiate your model

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

then save it

new_entry.save()

This adds it as a new row to your db.

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




回答2:


Why would it not be possible?

You probably want a modelform (but see the general form introduction first).




回答3:


Try out this example of Generic Views: http://postneo.com/2005/08/17/django-generic-views-crud (assumes a model named Task)

With Generic Views you get Insert, Update and Delete for free without any real work. give it a try and let me know what you think.

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 Docs: https://docs.djangoproject.com/en/1.2/ref/generic-views/#create-update-delete-generic-views



来源:https://stackoverflow.com/questions/11386751/django-add-rows-to-mysql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!