Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Save Form Data to Database

I'm using a form in my Django project to get people's name and number for later contact. Followed several guides including the Django docs but it doesn't seem to work. My test POST doesn't appear in admin and it can't be accessed via the manage.py shell either. I left in the multi-line comment in my code to show another method I was trying just in case. Getting no errors thrown in my manage.py runserver logs either.

Form:

from django import forms

class SubscribeForm(forms.Form):
  name = forms.CharField(label='Your Name', max_length=100)
  phone_number = forms.CharField(label='Phone Number', max_length=12, min_length=10)

Template:

<form action="/success/" method="post">
  {% csrf_token %}
  {{ form }}
  <input type="submit" value="Submit" />
</form>

View:

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from datetime import datetime

from .models import Person
from .forms import SubscribeForm

def home(request):
  # if this is a POST request we need to process the form data
  if request.method == 'POST':
    # create a form instance and populate it with data from the request:
    form = SubscribeForm(request.POST)
    # check whether it's valid:
    if form.is_valid():
        # process the data in form.cleaned_data as required
        p = form.save()
        '''
        name = form.cleaned_data['name']
        number = form.cleaned_date['phone_number']
        p = Person(name=name, phone_number=number, date_subscribed=datetime.now(), messages_recieved=0)
        p.save()
        '''
        # redirect to a new URL:
        return HttpResponseRedirect('/success/')
  # if a GET (or any other method) we'll create a blank form    
  else: 
    form = SubscribeForm()

  return render(request, 'texting/index.html', {'form': form})

I've watched several videos and read many SO pages, but still doesn't seem to work.

like image 378
Aaron Chamberlain Avatar asked Mar 10 '23 20:03

Aaron Chamberlain


2 Answers

Try this:

...
if form.is_valid():
    name = form.cleaned_data['name']
    number = form.cleaned_data['phone_number']
    p = Person(name=name, phone_number=number, date_subscribed=datetime.now(), messages_received=0)
    p.save()
...

The form.save() step is unnecessary.

ETA:

You could also try using a ModelForm and some defaults or a custom save method, like so:

class Person(models.Model):
    name = models.CharField(max_length=96)
    phone_number = models.CharField(max_length=12)
    date_subscribed = models.DateTimeField(default=datetime.now())
    messages_received = models.IntegerField(default=0)

from django.forms import ModelForm

class SubscribeForm(ModelForm):
    class Meta:
        model = Person
        exclude = ('date_subscribed','messages_received')

If you use a ModelForm, the form.save() is all you'll have to do.

like image 71
slink Avatar answered Mar 19 '23 15:03

slink


p = Person(name=name, 
           phone_number=number, 
           date_subscribed=datetime.now(), 
           messages_received=0)
p.save()

Delete these two lines. Add as follows:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','YourProjectName.settings')

import django
django.setup()

Person.objects.get_or_create()
like image 21
Rahul Bhaskar Avatar answered Mar 19 '23 16:03

Rahul Bhaskar