How do I create a simple user view web page to create/add mysql db entries?

144 views
Skip to first unread message

Bovine Devine

unread,
Oct 7, 2014, 1:32:29 AM10/7/14
to django...@googlegroups.com
I have gone through the django tutorial but seem to be lost on how to create a simple user view page that allows me to add/post/create data directly to the connected mysql database. I have the models view working and can access and add items in admin view but not sure how/what is the best way or method to have an external user view only webpage to create/add entries. I was searching in the django documentation https://docs.djangoproject.com/en/1.7/topics/db/queries/ but it seems to have examples on how to create/add entries from python command line.

Any examples of this type of form would be greatly appreciated. Thanks!

Collin Anderson

unread,
Oct 7, 2014, 12:19:59 PM10/7/14
to django...@googlegroups.com
Using a plan ModelForm in a few to create objects is surprisingly not well documented :)

Basically you do something like this:

from django import forms

class MyForm(forms.ModelForm):
   
class Meta:
        model
= MyModel
        fields
= ['field1', 'field2']

@login_required  # if you need it
def add_view(request):
    form
= MyForm()
   
if request.method == 'POST':
        form
= MyForm(request.POST)
       
if form.is_valid():
            the_new_entry
= form.save()
           
return redirect()  # wherever you want to go next
   
return render(request, 'add_template', {'form': form})


Bovine Devine

unread,
Oct 7, 2014, 5:20:26 PM10/7/14
to django...@googlegroups.com
Thanks for the help Collin...I need to read through more of the documentation it seems! Going through the chapter am I correct in understanding that using ModelForm example you listed as a view does not need to be added to urls then? What is the user access page then? Sorry this is all really still new to me and I do not understand why they are running. I went back to review the forms documentation here: https://docs.djangoproject.com/en/1.7/topics/forms/ so is this two different ways to do the same thing?

Collin Anderson

unread,
Oct 7, 2014, 7:49:04 PM10/7/14
to django...@googlegroups.com
> Am I correct in understanding that using ModelForm example you listed as a view does not need to be added to urls then? What is the user access page then?
The add_view would need to be added to your urls.

> So is this two different ways to do the same thing?
The main difference is that it's a ModelForm rather than a Form. The Model form has a "class Meta" and a form.save() method which automatically creates the row in the database for you.

Bovine Devine

unread,
Oct 7, 2014, 8:21:07 PM10/7/14
to django...@googlegroups.com


On Tuesday, October 7, 2014 4:49:04 PM UTC-7, Collin Anderson wrote:
> Am I correct in understanding that using ModelForm example you listed as a view does not need to be added to urls then? What is the user access page then?
The add_view would need to be added to your urls.

I added the add_view to teh urls.py

from django.conf.urls import patterns, url

from oneidentry import views

urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.add_view, name='add_view'),

But received an error that the view was not defined. I placed the code above into a new forms.py file:

from django import ModelForm
from oneidentry.models import Hardwareid

class HardwareidForm(forms.ModelForm):
     class Meta:
        model = Hardwareid
        fields = ['hardwareid_text']

def add_view(request):
    form = HardwareidForm()
    if request.method == 'POST':
        form = HardwareidForm(request.POST)
        if form.is_valid():
            the_new_entry = form.save()
            return redirect()  # wherever you want to go next
    return render(request, 'base_site.html', {'form': form})

Is that correct? Or does this belong in views.py?

Collin Anderson

unread,
Oct 7, 2014, 9:42:39 PM10/7/14
to django...@googlegroups.com
My bad. Put your add_view in views.py (cause it's a view :)

Then, you'll need to import your form into your view:
from oneidentry.forms import HardwareidForm

shmengie

unread,
Oct 8, 2014, 8:14:57 AM10/8/14
to django...@googlegroups.com


On Tuesday, October 7, 2014 5:20:26 PM UTC-4, Bovine Devine wrote:
Thanks for the help Collin...I need to read through more of the documentation it seems! Going through the chapter am I correct in understanding that using ModelForm example you listed as a view does not need to be added to urls then? What is the user access page then? Sorry this is all really still new to me and I do not understand why they are running. I went back to review the forms documentation here: https://docs.djangoproject.com/en/1.7/topics/forms/ so is this two different ways to do the same thing?

There are many ways... There are two separate methods, in the documentation, which have some overlap.

Collin has been pointing you in the direction of function based views.  FBV are a good starting point, easier to follow the logic.

The modern method is Class Based Views.  CBV has a lot of utility with a tougher learning curve.  Much redundancy is managed in the base classes, which hides logic.

CBVs minimize coding.  The cost is the learning curve.

views.py:
from django.views.generic import ListView, TemplateView, DetailView, CreateView, DeleteView, UpdateView
from oneidentry.models import Hardwareid

class MyView(CreateView):
    model = Hardwareid
    template_name = 'base_site.html'
    fields = ['hardwareid_text']

urls.py:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from oneidentry.views import MyView

urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="index.html"), name='index'),
url(r'^create/$', views.add_view, name='add_view'),
    )

Bovine Devine

unread,
Oct 15, 2014, 9:27:12 PM10/15/14
to django...@googlegroups.com
Thanks  Collin I made the switch but now cannot access the page at the new URL directly for some reason now and getting a 404 error:


Page not found (404)

Request Method:GET
Request URL:http://127.0.0.1:8000/hardwareid/get_barcode.html

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

  1. ^oneidentry/
  2. ^admin/

The current URL, hardwareid/get_barcode.html, didn't match any of these.


Bovine Devine

unread,
Oct 16, 2014, 4:51:09 PM10/16/14
to django...@googlegroups.com
Okay I figured that part out now by editing the correct URLS.py file as I was using the one in the app package as opposed to the root level sute url.py,

When I go to submit the text info in the form now I receive the following error. 

IntegrityError at /get_barcode.html

(1048, "Column 'pub_date' cannot be null")
Request Method:POST
Request URL:http://127.0.0.1:8000/get_barcode.html
Django Version:1.7
Exception Type:IntegrityError
Exception Value:
(1048, "Column 'pub_date' cannot be null")
Exception Location:c:\users\win7va~1\appdata\local\temp\easy_install-kwxg3e\MySQL_python-1.2.5-py2.7-win32.egg.tmp\MySQLdb\connections.py in defaulterrorhandler, line 36
Python Executable:C:\Python27\python.exe
Python Version:2.7.8
Python Path:
['C:\\hwdb\\mysite',
 'C:\\Python27\\lib\\site-packages\\setuptools-5.7-py2.7.egg',
 'C:\\Python27\\lib\\site-packages\\mysql_python-1.2.5-py2.7-win32.egg',
 'C:\\windows\\system32\\python27.zip',
 'C:\\Python27\\DLLs',
 'C:\\Python27\\lib',
 'C:\\Python27\\lib\\plat-win',
 'C:\\Python27\\lib\\lib-tk',
 'C:\\Python27',
 'C:\\Python27\\lib\\site-packages']
Server time:Thu, 16 Oct 2014 13:46:37 -0700

Traceback Switch to copy-and-paste view

  • C:\Python27\lib\site-packages\django\core\handlers\base.py in get_response
    1.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
      ...
  • C:\hwdb\mysite\oneidentry\views.py in get_barcode
    1. 			the_new_entry = form.save()
      ...
  • C:\Python27\lib\site-packages\django\forms\models.py in save
    1.                              construct=False)
      ...
  • C:\Python27\lib\site-packages\django\forms\models.py in save_instance
    1.         instance.save()
      ...
  • C:\Python27\lib\site-packages\django\db\models\base.py in save
    1.                        force_update=force_update, update_fields=update_fields)
      ...
  • C:\Python27\lib\site-packages\django\db\models\base.py in save_base
    1.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
      ...
  • C:\Python27\lib\site-packages\django\db\models\base.py in _save_table
    1.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
      ...
  • C:\Python27\lib\site-packages\django\db\models\base.py in _do_insert
    1.                                using=using, raw=raw)
      ...
  • C:\Python27\lib\site-packages\django\db\models\manager.py in manager_method
    1.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
      ...
  • C:\Python27\lib\site-packages\django\db\models\query.py in _insert
    1.         return query.get_compiler(using=using).execute_sql(return_id)
      ...
  • C:\Python27\lib\site-packages\django\db\models\sql\compiler.py in execute_sql
    1.                 cursor.execute(sql, params)
      ...
  • C:\Python27\lib\site-packages\django\db\backends\utils.py in execute
    1.             return super(CursorDebugWrapper, self).execute(sql, params)
      ...
  • C:\Python27\lib\site-packages\django\db\backends\utils.py in execute
    1.                 return self.cursor.execute(sql, params)
      ...
  • C:\Python27\lib\site-packages\django\db\backends\mysql\base.py in execute
    1.                 six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
      ...
  • C:\Python27\lib\site-packages\django\db\backends\mysql\base.py in execute
    1.             return self.cursor.execute(query, args)
      ...
  • c:\users\win7va~1\appdata\local\temp\easy_install-kwxg3e\MySQL_python-1.2.5-py2.7-win32.egg.tmp\MySQLdb\cursors.py in execute
    1.             self.errorhandler(self, exc, value)
      ...
  • c:\users\win7va~1\appdata\local\temp\easy_install-kwxg3e\MySQL_python-1.2.5-py2.7-win32.egg.tmp\MySQLdb\connections.py in defaulterrorhandler
    1.     raise errorclass, errorvalue
      ...


I do not remember adding this requirement so how can I add that as part of the form entry?

Collin Anderson

unread,
Oct 16, 2014, 5:28:38 PM10/16/14
to django...@googlegroups.com
Hi Bovine,

Your pub_date field needs a value. Maybe try this:

from django.utils import timezone

class MyModel(models.Model):
    pub_date
= models.DateField(default=timezone.now)

Collin

Bovine Devine

unread,
Oct 16, 2014, 7:32:16 PM10/16/14
to django...@googlegroups.com
Thanks Collin but does this belong in  my models.py, views.py or forms.py? I already had the following in my models.py:

from django.db import models
from django.utils import timezone


class Hardwareid(models.Model):
hardwareid_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date added')
def __unicode__(self):             
return self.hardwareid_text

Bovine Devine

unread,
Oct 16, 2014, 7:47:14 PM10/16/14
to django...@googlegroups.com
Hmm not sure what happened but I modified my models.py section:

class Hardwareid(models.Model):
hardwareid_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date added')
def __unicode__(self):             
return self.hardwareid_text

to match what you had recommended:

class Hardwareid(models.Model):
hardwareid_text = models.CharField(max_length=200)
pub_date = models.DateField('default=timezone.now)
def __unicode__(self):             
return self.hardwareid_text

and now it works! I can enter data to submit from that page and it ended up in my mysql db. Thanks for all your help Collin.
Reply all
Reply to author
Forward
0 new messages