Saving a Form to a Database (Django Python) -


in django app have form email , text area needs go database struggeling so. @ moment have 2 different solutions in code:

the code

if understand correctly, should create model first (with email field , text field(charfield), (which automatically creates table in database when run django migrate), should create modelform created model. easiest, fastest, basic solution this. automatically saves form in database(with .save() method) , not confuse form , model fields during saving.

reference modelforms here: https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/

so, better create forms models directly.

in particular example (you mismatched fields saving , that's why not working):

as see created "get_question" function in views.py file. in function should change saving part of code , include this:

# .models import contact  saving_all = contact.objects.create(contact_email = form_email, contact_question = form_question ) 

this part of code save form data in contact table in database.

it same saving code original approach in views.py(where mismatched fields). should if corrected:

# .models import contact  contact = contact(contact_email=form_email, contact_question=form_question) contact.save() 

more clearly: code below working in views.py , saving data form database in contact model(table) (use own app_name in code of course if needed):

from django.shortcuts import render . import forms . import models 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 model looks in models.py:

from django.db import models  # create models here.  class contact(models.model):     contact_email = models.emailfield(max_length=80)     contact_question = models.charfield(max_length=600)  

and form in forms.py looks this:

from django import forms  class questionform(forms.form):     your_email = forms.emailfield()     your_question = forms.charfield(widget = forms.textarea) 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -