How to save a multiple django forms into a database in a good way? Enhance Performance - mysql

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.

Related

Passing Variables Between Forms

Forgive me if this has already been asked- I can’t seem to find a well written answer.
I am developing a small application for personal use.
Essentially what I have is two forms. Form 1 is a master view of all my contacts listed on a data grid view. Form 2 will be loaded on the cell/row double click of a particular record in order to edit it’s details.
My question is, what is the best practice/method for achieving this? I have seen many different methods.
Should I:
Pass only the primary key of the selected row then populate the fields on form 2 load
Pass all fields as a variable within a class then populate form 2 from that
Maybe I’m headed in the complete wrong direction though.
I have tried both ways, but wondering what the best method is for scalability.
My personal preference would be to pass a datarow into the opening argument of the form (rather than the PK / all the variables). You can then use the datarow inside your Form2 to bind to your controls or set their values, whichever you think is appropriate.
There are some useful examples on working with a datarow if you're unsure, alternatively you can also check out Microsoft Docs.
Public Sub New(ByVal row As DataRow)
InitializeComponent()
' your code for working with row here
End Sub
Edit:
In terms of "Binding" vs "Setting", you can either have your controls linked to your data to be two way (as you edit the data in a control at run time you alter the data in your database) or you can just set the values of the controls.
E.G. TextBox1.Text = row(0)("ColumnName")
You can find more on data binding on the Microsoft Docs page

django insert table with form inputs manually

I need to have form input data as values sent to my table field. Problem is I can't do that the usual way, because the form is tied to another model. But I also need to populate this model with same form.
payment = SitePayment.objects.create(
user=request.user,
charge=charge.id,
site=psite,
# address=form.address,
# zipcode=form.zipcode,
# city=form.city,
# country=form.country,
)
This was to me the simpler and logical way to go about it, but it doesn't work. Is there a way to have form inputs inserted into this model when manually inserting a table?
I can provide more code, but I thought it would be really messy for you to understand, so I'm trying this way.
I found the solution, which was incredibly simple and I now feel incredibly stupid. I'm new to django/python, though, so please no anger.
payment = SitePayment.objects.create(
user=request.user,
charge=charge.id,
site=psite,
address=form.cleaned_data['address'],
zipcode=form.cleaned_data['zipcode'],
city=form.cleaned_data['city'],
country=form.cleaned_data['country'],
)
It should of course be "form.cleaned_data" and not just "form."

Django - Add rows to MySQL database

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

How to do php operations in drupal

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.

MS Access 2003/2007 - Passing data through a variable on unbound forms vs. a hidden text box

Ok so I hope the title of the question matches what I about to ask, but here is what I am trying to get at:
So I have an access database that uses a number of unbound forms, and the purpose of the forms are to collect data and save to various tables with VBA click events using SQL statements (INSERT or UPDATE based on whether the ID of the record is present on the form in a hidden text box). When entering a new record (via INSERT), I get the row number with
MyRow = db.openrecordset("SELECT ##Identity")(0) 'thanks David
So you maybe getting the picture. If I have another form that relates to the first form in terms of the record, I just open a recordset and pass that value to another hidden text box.
So my question is, is there a better way to do this regarding passing that value (or just using that value) using a variable instead of this awkward method. So I realize a lot of folks are going to go with the obvious answer of, "Why not just make your forms bound instead of all this code"...and I am sure that is a valid answer, however I inherited this database which was already put together like this, and re-structuring it would be a daunting task.
Any and all advice, or learning resources are greatly appreciated, as they always are!
I use unbound controls on forms for all these kinds of values. The current solution of using an unbound form is sounder than using global or form level variables. If I recall the details correctly while debugging code and you hit the stop button you lose all global or form level variables. Or if the user hits an unhandled error.
Have you looked at OpenArgs?
DoCmd.OpenForm "Form1", , , , , , "Hello"