简体   繁体   English

如何在Django中向现有模型添加数据?

[英]How do I add data to an existing model in Django?

Currently, I am writing up a bit of a product-based CMS as my first project. 目前,我正在编写一些基于产品的CMS作为我的第一个项目。

Here is my question. 这是我的问题。 How can I add additional data (products) to my Product model? 如何在产品型号中添加其他数据(产品)?

I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. 我在我的urls.py中添加了'/ admin / products / add',但我真的不知道从那里去哪里。 How would i build both my view and my template? 我如何构建我的视图和模板? Please keep in mind that I don't really know all that much Python, and i am very new to Django 请记住,我真的不太了解Python,我对Django很新

How can I do this all without using this existing django admin interface. 如何在不使用现有django管理界面的情况下完成所有操作。

You will want to wire your URL to the Django create_object generic view , and pass it either "model" (the model you want to create) or "form_class" (a customized ModelForm class). 您需要将URL连接到Django create_object泛型视图 ,并将其传递给“model”(您要创建的模型)或“form_class”(自定义的ModelForm类)。 There are a number of other arguments you can also pass to override default behaviors. 您还可以传递许多其他参数来覆盖默认行为。

Sample URLconf for the simplest case: 最简单案例的示例URLconf:

from django.conf.urls.defaults import *
from django.views.generic.create_update import create_object

from my_products_app.models import Product

urlpatterns = patterns('',
    url(r'^admin/products/add/$', create_object, {'model': Product}))

Your template will get the context variable "form", which you just need to wrap in a <form> tag and add a submit button. 您的模板将获得上下文变量“form”,您只需将其包装在<form>标记中并添加提交按钮即可。 The simplest working template (by default should go in "my_products_app/product_form.html"): 最简单的工作模板(默认情况下应该放在“my_products_app / product_form.html”中):

<form action="." method="POST">
  {{ form }}
  <input type="submit" name="submit" value="add">
</form>

Note that your Product model must have a get_absolute_url method, or else you must pass in the post_save_redirect parameter to the view. 请注意,您的Product模型必须具有get_absolute_url方法,否则您必须将post_save_redirect参数传递给视图。 Otherwise it won't know where to redirect to after save. 否则它将不知道保存后重定向到哪里。

Follow the Django tutorial for setting up the "admin" part of an application. 按照Django教程设置应用程序的“admin”部分。 This will allow you to modify your database. 这将允许您修改数据库。

Django Admin Setup Django管理员设置

Alternatively, you can just connect directly to the database using the standard tools for whatever database type you are using. 或者,您可以使用标准工具直接连接到数据库,无论您使用何种数据库类型。

Django教程中介绍了这个主题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM