简体   繁体   中英

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:

编码

If I understand you correctly, then you should create a Model first (with an email field and text field(CharField), (which then automatically creates the table in the database when you run django migrate), then you should create a ModelForm from that created Model. That is the easiest, fastest, basic solution for this. It automatically saves your Form in database(with .save() method) then and you will not confuse Form and Model fields during saving.

Reference about ModelForms is here: https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/

So, it is better to create your Forms from Models directly.

In your particular example (you mismatched the fields for saving and that's why it was not working):

as I see you created a "get_question" function in your views.py file. In that function you should change the saving part of your code and include something like this:

# from .models import Contact

saving_all = Contact.objects.create(contact_email = form_email, contact_question = form_question )

This part of the code will save your Form data in your Contact table in the database.

It does the same saving as this code with your original approach in views.py(where you mismatched the fields). It should look like this if corrected:

# from .models import Contact

contact = Contact(contact_email=form_email, contact_question=form_question)
contact.save()

More clearly: This code below is working in views.py and saving the data from a Form to the database in the Contact Model(table) (use your own app_name in the code of course if needed):

from django.shortcuts import render
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_email = form.cleaned_data['your_email']
            form_question = form.cleaned_data['your_question']
            saving_all = models.Contact.objects.create(contact_email=form_email, contact_question=form_question)
            return HttpResponse('Success')
    else:
        form = forms.QuestionForm()

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

And your Model looks like this in models.py:

from django.db import models

# Create your models here.

class Contact(models.Model):
    contact_email = models.EmailField(max_length=80)
    contact_question = models.CharField(max_length=600) 

And your Form in forms.py looks like this:

from django import forms

class QuestionForm(forms.Form):
    your_email = forms.EmailField()
    your_question = forms.CharField(widget = forms.Textarea)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM