Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

Currently, I am writing up a bit of a product-based CMS as my first project.

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. 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

How can I do this all without using this existing django admin interface.

like image 662
Josh Hunt Avatar asked Aug 31 '08 12:08

Josh Hunt


People also ask

How do I add a field to an existing model in Django?

You need to make the new field nullable or provide a default value and just migrate as you would with a new model. You should set null=True param or default param. I think best choices of null=True param. Don't allow null without thought.

What is __ str __ in Django?

The __str__ method in Python represents the class objects as a string – it can be used for classes.

How does Django store data in models?

Creating objectsTo create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

Does Django Loaddata overwrite?

Each time you run loaddata , the data will be read from the fixture and reloaded into the database. Note this means that if you change one of the rows created by a fixture and then run loaddata again, you'll wipe out any changes you've made.


1 Answers

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). There are a number of other arguments you can also pass to override default behaviors.

Sample URLconf for the simplest case:

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. The simplest working template (by default should go in "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. Otherwise it won't know where to redirect to after save.

like image 115
Carl Meyer Avatar answered Sep 24 '22 11:09

Carl Meyer