Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ModelForm in Django to add to database

New to Django and I have exhausted every forum and tutorial I can and I am still having problems getting my form data to the database. I have a simple model that consists of a name and an email field that I will eventually reference in the program. I can load different pages after clicking submit, but my data will not post to the database. I have tried everything I can think of, so my code is probably jacked at this point, but in the current iteration this is what I have:

#models.py
    from django.db import models
from django.forms import ModelForm

class Patron(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField(max_length=75)


    def _unicode_(self):
        return self.name

class PatronForm(ModelForm):
    class Meta:
        model = Patron

#view.py

from django.shortcuts import render_to_response, get_object_or_404
from patrons.models import Patron 
from django.template import RequestContext
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.forms import ModelForm


def index(request):
    if request.method == 'POST':
        post = request.POST
        name = post['name']
        email = post['email']
        f = PatronForm(request.Post)
        new_patron = f.save()
    return render_to_response('patrons/index.html',
                               context_instance=RequestContext(request))

#html
 <body>
    <h1>/Picture Taker/</h1>



    <form aciton="." name="patron" method="post" >
    {% csrf_token %}

        <label>
            <div>name</div> <input type="text" name="name" id="name" value="{{name}}">
        </label>
        <label>
            <div>email</div> <input type="text" name="email" id="email" value="{{email}}">
        </label>

        <div class="error">{{error}}</div>
        <input type="submit" value="Submit">
    </form>

</body>

Any help would be greatly appreciated

like image 474
user808996 Avatar asked Oct 08 '22 16:10

user808996


1 Answers

All of

post = request.POST
name = post['name']
email = post['email']
f = PatronForm(request.Post)
new_patron = f.save()

can be re-written as (note the case of request.POST):

f = PatronForm(request.POST)
new_patron = f.save()

but you should be checking for errors in the form before saving, so:

f = PatronForm(request.POST)
if f.is_valid():
    new_patron = f.save()

You also have a typo in your form tag, it should be "action", not "aciton". The {{ error }} you have in your template doesn't refer to anything present in your view. While debugging, it might be helpful to let the form render itself, like:

{{ form.as_p }}

so you can see any errors in the form submission.

like image 88
Tom Avatar answered Oct 12 '22 11:10

Tom