Lode
Lode

Reputation: 41

Saving a Form to a Database (Django Python)

In my Django app I have a form with an email and a text area that needs to go into the database but am struggeling to do so. At the moment I have 2 different solutions in my code:

the code

Upvotes: 2

Views: 2612

Answers (1)

Zollie
Zollie

Reputation: 1211

OK, let me write this from the beginning. Maybe it is better if you do the below steps with me now for an exercise.

Now, the correct way to do the above task (I try to clear this subject a little more because I know that many other people will read this problem and they can learn from this too. And it is important to understand it for your future tasks.

If you want to create a Form and you know that you will want to save the submitted data from that Form to the database, then of course you should start the whole task with creating a Model, thus a table for that in the database.

So, first you create a Model (which you will call ie. “Questions” in this case, since you want to call your Form ie. QuestionForm, so it is better if your Model and table will be related to that with their names too).

So your Model will be in your models.py file:

from django.db import models
# Create your models here.

class Questions(models.Model):
    contact_email = models.EmailField(max_length=60)
    question = models.CharField(max_length=600)

Then you will create a ModelForm from this in your forms.py file the following way:

from django import forms
from django.forms import ModelForm, Textarea
from . import models

class QuestionForm(ModelForm):
    class Meta:
        model = models.Questions
        fields = ['contact_email', 'question'] 
        widgets = {
            'question': Textarea(attrs={'cols': 40, 'rows': 20}),
        }

Then you create your view function in your views.py file:

from django.shortcuts import render, redirect
from . import forms
from . import models
from django.http import HttpResponse

def get_question(request):
    form = forms.QuestionForm()

    if request.method == 'POST':
        form = forms.QuestionForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(‘success.html’) # or you redirect anywhere you want to
    else:
        form = forms.QuestionForm()

    return render(request, 'contact.html', {'form':form})

And at this point you will create your urlpattern in your urls.py to call the get_question view function. It will look like the following:

from django.conf.urls import url
from basic_app import views

# app_name = 'basic_app' # Important for referencing urls in HTML pages(use your own app_name here). But for this example task this is not important.

urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^questions/', views.get_question, name="questions_page"),
]

I hope I did not confuse you more. If you do the above steps, it should work for you. And you can create as many Forms as you want with the above steps and saving them easily in the Database.

The only other thing you have to have to run the above, is your 'contact.html' page which you already have and you already created.

(do not forget to run: python manage.py migrate)

So, I hope that you see, in the above example you do not mismatch fields and field names, and you do not get confused about what to save where. Since the Model and the Form is working together and created together with the same field names.

Upvotes: 2

Related Questions