So I already have a database setup with a few columns and a few rows already inserted in. I'm trying to create a view that you would just input information into a form and press Submit, then a row would be added to the MySQL database with the information you just typed in.
I believe you can do this with admin, but I would like to try without admin and I'm not sure if this is possible? I've been using the MySQL commandline to add rows as of now..
Of coures this is possible this is a building block for data driven websites. You can use a ModelForm as Daniel suggested (they offer built in validation and HTML markup for FREE) to easily map your model to a front end form. It would probably be beneficial to start with django tutorial or documentation first.
At the the very basic, all you have to do is instantiate your model
new_entry = YourModel(name='me', age='222', about='stackoverflow')
then save it
new_entry.save()
This adds it as a new row to your db.
https://docs.djangoproject.com/en/dev/topics/db/models/
Why would it not be possible?
You probably want a modelform (but see the general form introduction first).
Try out this example of Generic Views: http://postneo.com/2005/08/17/django-generic-views-crud (assumes a model named Task)
With Generic Views you get Insert, Update and Delete for free without any real work. give it a try and let me know what you think.
from django.conf.urls.defaults import *
info_dict = {
'app_label': 'tasks',
'module_name': 'tasks',
}
urlpatterns = patterns('',
(r'^tasks/create/?$', 'django.views.generic.create_update.create_object', info_dict ),
(r'^tasks/update/(?P<object_id>\d+)/?$', 'django.views.generic.create_update.update_object', info_dict),
(r'^tasks/delete/(?P<object_id>\d+)/?$', 'django.views.generic.create_update.delete_object', info_dict ),
)
Django Docs: https://docs.djangoproject.com/en/1.2/ref/generic-views/#create-update-delete-generic-views
Related
I am building an app in Django that allows users to build their own forms and in effect customise dynamic models.
After much research, I've decided to effect this through Django, PostgreSQL and JSONFields where one model holds the schema and another holds the record data:
class = Template(models.Model):
schema = JSONField(null=True) # Schema for the form/model
class = DynamicModel(models.Model):
data = JSONField(null=True) # Corresponding data for the form/model
template = models.ForeignKey(Template, null=True,
blank=False, on_delete=models.SET_NULL)
This means users can define their own model templates and I can hold different records using that template in another model.
The idea is to parse the template.schema JSONField to display editable forms using jQuery and to store the output as dynamicmodel.data JSONField. Validations are passed on the client side.
However, this comes with the drawback if I want to allow users to include ForeignKey lookups in their models. For example, say they wanted to add a choice box that offered selections from different customer.ids in a Customer(models.Model) class.
Without hardcoding the ForeignKey directly into the DynamicModel class (which would defeat the point of the exercise) can you think of a way I can achieve this?
I want to save multiple django forms into a database in a good way, because it takes very long time to save these forms on a server.
the forms is related to each other, so I am using a serial saving technique "one form by one".
How can I maintain my forms to save quickly to database.
Forms Code:
employee_main=EmployeesForm(request.POST)
employee_administrative=EmployeesAdminstrativeForm(request.POST)
employee_stay=EmployeesStayForm(request.POST,request.FILES)
employee_dependents=EmployeesDependentsForm(request.POST,request.FILES,prefix="u")
employee_insurance=EmployeesInssuranceForm(request.POST,request.FILES)
employee_security=EmployeesSecurityForm(request.POST,request.FILES)
if employee_main.is_valid() and employee_administrative.is_valid() and employee_stay.is_valid() and employee_dependents.is_valid() and employee_insurance.is_valid() and employee_security.is_valid():
emp=employee_main.save(commit=False)
emp.save()
emp_ad=employee_administrative.save(commit=False)
emp_ad.employee_id=emp.id
emp_ad.save()
jobtitle_code=JobTitle.objects.get(id=emp_ad.jobtitle_id).Code
Employees.objects.filter(id=emp.id).update(Code=jobtitle_code +"-"+ str(emp_ad.employee_id+25))
Employees.objects.filter(id=emp_ad.moder_id).update(ismodeer=True)
emp_s=employee_stay.save(commit=False)
emp_s.employee_id=emp.id
emp_s.save()
emp_dd=employee_dependents.save(commit=False)
emp_dd.employee_id=emp.id
emp_dd.save()
emp_ss=employee_insurance.save(commit=False)
emp_ss.employee_id=emp.id
emp_ss.save()
from authentication.models import users
user=users(employee_id=emp.id,UserName=request.POST["UserName"],Password=request.POST["Password"],isadmin=0)
user.save()
return HttpResponseRedirect("/employees/all_employees/")
Put all the above code in a transaction.
Make Employee inherit User. Read more about model inheritance in Django.
You create the Employee object, then you update it using Employees.objects.filter(id=emp.id).update(Code=...). Just modify the code before the first save
django-modelcluster may help you. It's worth a try.
I'm using Flask, SQLAlchemy and WTForms. I have a number of properties in my model object which are marked as unique and nullable=False. This works fine when creating a new row in the database but when I try to edit an existing object the validator on WTForms fails with
{'aproperty': [u'Already exists.']}
How can I make this validation pass without having to change my data model?
Update
Following the documentation was of no use to me.
You need to associate the existing record with the form. Otherwise the validator has no way of knowing that you're updating an existing record instead of creating a new one. Something like the following should do the trick:
current_obj = ...
form = MyForm(request.form, obj=current_obj)
form.validate_on_submit():
form.populate_obj(current_obj)
I have a django app that is evolving. The model often changes and I use Django South to apply schema migrations.
Sometimes my changes involve populating new values that are added based on sql logic.
For example, added a new boolean flag for currently paying users. I have added the field, applied the migration but now I want to populate the field based on the data from other table to show who is paying.
I know I can do this with a simple sql statement, but my environment is automated and uses CI. I want to push changes and have the flag populated automatically.
How can I accomplish this? With South? With Django?
There is a thing called data migration, this is a perfect use case for it:
Data migrations are used to change the data stored in your database to
match a new schema, or feature.
from south.v2 import DataMigration
from django.conf import settings
class Migration(DataMigration):
def forwards(self, orm):
# update your user's boolean flag here
See an example of a data migration here.
Or, alternatively, you can open your schema migration .py file and populate your field in forwards() method, like this:
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'User.paying'
db.add_column(u'user', 'paying',
self.gf('django.db.models.fields.BooleanField')(default=True),
keep_default=False)
# update your user's boolean flag here
def backwards(self, orm):
# Deleting field 'User.paying'
db.delete_column(u'user', 'paying')
You can add your code in migration script created by south.
If you have updated a model and done schemamigration with south, it will create a script to apply that migration. It will be in appname/migration/00N_some_name.py.
You can add your code in forwards() method in that script at the end after schema alteration is done.
I am absolute beginner to drupal.
I have added a contact form (using Webform module).
Now I want to save the data entered in the form. But I am lost. I have searched over internet, found db_query() is used to query database.
But I dont know where to write the php code. Please help me or if you know any link,please give me.
The tables you'll be most interested in are webform, webform_submissions, webform_submitted_data and webform_component. Have a look at those tables and it becomes very obvious how they're linked together.
You'll want to look at the Drupal 7 Database API to learn how to use the query system but here's an example to get you going:
/* Get a list of all submissions from webform for the node with ID (`nid`) of 1 */
$nid = 1;
$submissions = db_select('webform_submissions', 'ws')
->fields('ws')
->condition('nid', $nid)
->execute();
/* If you want to use db_query and a plain old SQL statement instead you'd do it like this:
$submissions = db_query('SELECT * FROM webform_submissions WHERE nid = :nid', array('nid' => $nid)); */
/* Loop through the submissions and load up the submitted data for each */
$submission_data = array();
foreach ($submissions as $submission) {
$query = db_select('webform_submitted_data', 'wsa')
->fields('wc', array('name'))
->fields('wsa', array('data'))
->condition('sid', $submission->sid);
/* Join in the component table to get the element label */
$query->join('webform_component', 'wc', 'wc.nid = wsa.nid AND wc.sid = wsa.cid');
$submission_data[] = $query->execute()->fetchAllKeyed();
}
At the end of that code you'll have an array ($submission_data), which contains a list of arrays of submission data for the provided node. Each of those arrays' items has a key of the component label, and a value of the submitted user value.
Hope that helps
It's worth noting that for most normal use cases you'll never need to look at the databases or do any kind of coding. The UI allows you to view submissions of a form (and see what was submitted). You can also configure the Webform to send you a copy of each submission (via email)... There is a lot you can do without "looking under the hood" or messing with the database in any way.
If you are really new to Drupal and Webforms, I just thought I'd point that out. There are a lot of tabs in the UI which might easily be overlooked.
Webform has Views support, so you probably don't really need to write database queries to generate the report you want.