tags:

views:

73

answers:

3

i have a model ready with the various form fields. how do i make those form fields get saved into the database? i tried reading the form documentation but it is so confusing. i know if i get it working, i will understand. can anyone help define a views.py function?

+1  A: 

One of the best ways to learn this is to go through the great Django tutorial.

TM
i already did that. but tutorial #4 is where it all gets so confusing...
symbian.works
In that case, could you elaborate on what you have set up so far, and what specific problems you are running in to?
TM
A: 

It is automatically saved to the database. You can populate the database from the admin interface (that must explitly be turned on) or using Python.

From Python, to add an entry for a model named "ProgramVersion" that has 12 fields (the model is in an 'app' named "programRelease"):

python manage.py shell
from programRelease.models import ProgramVersion
p9 = ProgramVersion(
       shortDescription   = 'First public release for v2.0.',
       longerDescription  = 'This is the first public release on the road to v2.0 of MSQuant.',
       slug               = 'version1_alfa',
       entry_pub_date     = '2009-10-02 14:51:02',
       software_pub_date  = '2009-10-02',
       name               = 'MSQuant',
       version            = '2.0a78',
       downloadURL        = 'http://www.pil.sdu.dk/1/MSQuant/MSQ,2.0a78,2009-10-02c.7z',
       downloadSizeMBytes = '11.8',
       addedFeatures      = '<none>',
       changedFeatures    = '<p>Quantitation of isotopes has been disabled - it does not provide much value anyway.</p>',
       fixedBugs          = '&lt;none&gt;',
       )
p9.save()

(all but the first line happens interactively in Python (can be pasted) and the current directory must be the root of your Django project - where urls.py and manage.py is.)

Peter Mortensen
+3  A: 

Note that models and forms are seperate things...

The first thing you need to do is make a form for your model (from the django docs)

from django.forms import ModelForm

# Create the form class.
class ArticleForm(ModelForm):
    class Meta:
        model = Article

In your view you need to create an instance of the form and read the values back, which is done with a bit of code like this

def edit_article(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            form.save()
            # do something.
    else:
        form = ArticleForm()
    return render_to_response("edit_article.html", {"form": form,})

You then need to create your template edit_article.html. If you put this in it

<form method="POST">
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

Your form should display, and you should be able to submit it.

You'll need a suitable entry for urls.py too.

PS None of the above actually tested!

Nick Craig-Wood