django multiple form separated in the html, merge again with submit - html

there is a formmodel like:
class foo(forms.ModelForm):
a = forms.BooleanField(label='a', required=False)
b = forms.BooleanField(label='b', required=False)
c = forms.BooleanField(label='c', required=False)
d = forms.BooleanField(label='d', required=False)
e = forms.BooleanField(label='e', required=False)
f = forms.BooleanField(label='f', required=False)
g = forms.BooleanField(label='g', required=False)
h = forms.BooleanField(label='h', required=False)
#...
further there are multiple instances of foo in a list:
L = []
L.append(foo(instance=object_1))
L.append(foo(instance=object_2))
L.append(foo(instance=object_3))
#...
L.append(foo(instance=object_n))
this is shown on the html in different tables in different columns.
The problem now is to send the data back correctly with subbmit. I have to put the tables and lines back together correctly. I was thinking of something like this:
<form class="form-inline" action ="{% url 'bla:blo' %}" method="post">
Table #1
| ID of Form | Value #1 | Value #2 | Value #3 | Value #4 |
| ---------- | -------- | -------- | -------- | -------- |
<form id=1>| 1 | a1 | b1 | c1 | d1 |</form>
<form id=2>| 2 | a2 | b2 | c2 | d2 |</form>
<form id=3>| 3 | a3 | b3 | c3 | d3 |</form>
<form id=4>| 4 | a4 | b4 | c4 | d4 |</form>
Table #2
| ID of Form | Value #1 | Value #2 | Value #3 | Value #4 |
| ---------- | -------- | -------- | -------- | -------- |
<form id=1>| 1 | e1 | f1 | g1 | h1 |</form>
<form id=2>| 2 | e2 | f2 | g2 | h2 |</form>
<form id=3>| 3 | e3 | f3 | g3 | h3 |</form>
<form id=4>| 4 | e4 | f4 | g4 | h4 |</form>
{% csrf_token %}
<button type="submit" class="btn btn-dark">Save</button>
</form>
i.e. the rows of the table with the same form id must be converted back into the same django form.
the submit must then of course still be accepted in the view.py
kinda like that
def boo(request):
if request.method == 'POST':
if form.is_valid():
f = foo(request.POST):
# f[0] = form id 1
# f[1] = form id 2
# f[2] = form id 3
# ...
# f[n] = form id n

You can only send multiple forms via context, but getting all these form data using another wrapper form will not be possible. You can only see the list of forms, but you may not be able to get data using post requests for all forms.
def boo(request):
if request.method == 'GET':
form_list = []
object_list = [] # YOUR_OBJECT_LIST
for instance in object_list:
form_list.append(foo(instance=instance))
return render("footemplate.html", context={"forms": form_list})
if request.method == "POST":
<form>
{% csrf_token %}
{% for form in forms %}
{{ form }}
{% endfor %}
</form>
To send all forms data via post request, I will suggest using javascript and ajax. and for backend part, use RestfulAPI to handle this complex system

Related

Django Database transaction rollback in Loop

User may import a excel and I want to check if the data are correct.
# Excel Data
| id | item | qty |
|:---- |:------:| -----:|
| 1 | item A | 10 |
| 2 | item B | 20 |
| 3 | item C | 30 |
| 4 | item D | 40 | <-- For example, Not enough qty to minus (only have 1)
| 5 | item E | 50 |
# Database
| id | item | qty |
|:---- |:------:| -----:|
| 1 | item A | 100 |
| 2 | item B | 200 |
| 3 | item C | 300 |
| 4 | item D | 1 | <-- For example, Not enough qty to minus (Need 40)
| 5 | item E | 500 |
I need to check the Database is that item has qty to minus, if yes then save the changes, if not, then rollback all changed data in this excel data (rollback to before import this excel) and return errors details to user.
def myFunction(self, request):
try:
error_details = []
with transaction.atomic():
for data in excal_data:
result = checkIfVerify(data) # Here will be a function which will cause error 'You can't execute queries until the end of the 'atomic' block'
if result is True:
serializer = modelSerailizer(data)
serializer.save()
else:
error_details.append("some explanation...")
if len(error_details) > 0:
transaction.set_rollback(True)
raise CustomError
excpet CustomError:
pass
return Response(....)
# checkIfVerify(data)
def checkIfVerify(data):
# this sql will need to join many tables which is hard to use ORM
sql = ....
results = []
with connection.cursor() as cursor:
cursor.execute(sql)
results = cursor.fetchall()
cursor.close()
connection.close()
if results .....:
return True
else:
return False
But the problem seem to be I cannot able to use raw SQL execute inside the transaction.atomic() block, If I put transaction.atomic() inside the loop after the checking function, it not able to rollback all data.
How should I do?

When input type submit is clicked, generate a query

beginner here. I'm currently making a matching system where owners will register their entries. Once it is done, I will click the "match" button and it'll generate the match. The logic for matching depends on the weight.
For example, if owner 1 and owner 2 registered an entry/ies that has 1900 weight, they'll
automatically be matched. (As you can see at the 2nd table)
How can I achieve these goals of mine? Thank you guys in advance.
tbl_entry
|id| entryName| lightBand| weight |
|---| --------| ----- |---------|
| 1 | owner1 | 1 | 1900 |
| 2 | owner1 | 2 | 1920 |
| 3 | owner2 | 3 | 1900 |
| 4 | owner3 | 4 | 1910 |
| 5 | owner4 | 5 | 1910 |
tbl_matching
| id |fightID| entryName| lightBand| weight | entryName| lightband1| weight1|
|---- |--------| --------| ----- |---------|-------- |----------|--------|
| 1 | 1 | owner1 | 1 | 1900 | owner2 | 3 | 1900 |
| 2 | 2 | owner3 | 4 | 1910 | owner4 | 5 | 1910 |
| 3 | - | owner2 | - | - | - | - | - |
HTML:
<form action="transaction/match" method="POST">
<input type="submit" name="doMatch"> match
</form>
Controller:
public function match {
$formSubmit = $this->input->post('doMatch');
// do the matching query here
}
(hyphen/dash) <<<< means no correspondent player to match with.
Note: I'm using codeigniter3.
First of all, I never use <input type = "submit"> before, usually I use <input type="text"> and put the submit in button.
Let's say you have
<input type="text" name="entryName">
<input type="text" name="weight">
... etc
you can put this in your Controller (for later, you should use Control -> Model)
$weight = $this->input->post('weight'); //get your weight input
//get the opponent data based on weight input
$result = $this->db->get_where('tbl_entry', ['weight' => $weight])->row_array();
//check if the result is not null
if ($result != null) {
$submit = [
//I assume that your ID is autoincrement
'fightID' => 'fight ID', //you can make a function for fight ID and put the result like $fight_ID
'entryName' => $this->input->post('entryName'),
'lightBand' => $this->input->post('lightBand'),
'weight' => $weight,
];
$data[] = array_merge($submit, $result); //merge the entry and the result into 1 array
$this->db->insert('tbl_matching', $data); //insert it into your table matching
}
else {
//like above, but just change it to '-' instead of input->post
}

MS Access Update on specific SQL select same table

I'm currently trying to update an existing database (removing duplicates).
You can see the structure as follows :
I have a database on which specific entries are marked as "Main". These entries need to be updated with data from duplicate records, only having the same name.
(Updated table to reflect my question better)
It would look like this:
+----+------+-----------------+--------------+---------+
| ID | Name | Field-To-Update | Duplication | Source |
+----+------+-----------------+--------------+---------+
| . | A | xxx | Main | 1 |
| . | A | yyy | "" | 2 |
| . | A | zzz | "" | 3 |
| . | B | foo | "" | 1 |
| . | B | bar | Main | 2 |
+----+------+-----------------+--------------+---------+
Should result in
+----+------+-----------------+--------------+-----------------------------------------------+
| ID | Name | Field-To-Update | Duplication | Source |
+----+------+-----------------+--------------+-----------------------------------------------+
| . | A | yyy | Main | 1 |
| . | A | yyy | "" | 2 |
| . | A | zzz | "" | 3 (should be updated from a specific source) |
| . | B | bar | "" | 1 |
| . | B | bar | Main | 2 (should be updated from a specific source) |
+----+------+-----------------+--------------+-----------------------------------------------+
Do any of you have an idea how to tackle this? I've tried with multiple queries for a couple of days now without any success.
you could use a update with join
update t
set t.field_to_update = x.field_to_update
from your_table t
inner join ( select name, field_to_update
from your_table
where Duplication <> 'Main') x
) on t.name = x.name
where t.Duplication = 'Main'
Bizarre requirement. You say you are updating to remove duplicates, however, it looks to me like you are creating duplicates.
There are only 2 records for each Name? Try:
UPDATE Table INNER JOIN
(SELECT Name, [Field-To-Update]
FROM Table
WHERE Duplication Is Null) AS Query1 ON
Table.Name = Query1.Name SET Table.[Field-To-Update] = [Query1]![Field-To-Update] WHERE Duplication = "Main";
Name is a reserved word in Access. Should not use reserved words as name for anything.
Darn! Did not see #scaisEdge answer before posting.
I tried the <> "Main" criteria and it did not work which was surprising - no records returned. So I switched to the Is Null parameter.
If you want to pull value from the maximum Source for each Name, then need a query that does that. Review http://allenbrowne.com/subquery-01.html#TopN. Then use that query in the above example as Query1.

mapping Inheritance and native query in doctrine

I have next structure :
+------+
| |
| A1 | Class A1
| |
+--+---+ Class A2 - child
^ Class A3 - child
|
| A2->B1 (Class B1)
+--------+--------+ A3->B2 (Class B2)
| |
| |
+-----+ +--+---+ +--+--+ +-----+
| | | | | | | |
| B1 +---+ A2 | | A3 +---+ B2 |
| | | | | | | |
+-----+ +------+ +-----+ +-----+
It's single table inheritance so A1,A2,A3 are in single DB table (a1). I need to creative Native Query and mapping that will load all entities from single table with all associated entities (B1, B2) at once. Query looks like this :
SELECT a1.*, b1.id AS b1_id,...,b2.id AS b2_ID...
FROM a1
LEFT JOIN b1 ON (a1.b1 = b1.id)
LEFT JOIN b2 ON (a1.b2 = b2.id)
I have try something like this :
$mapping = new ResultSetMapping();
$mapping->addEntityResult(A1::class, 'a');
$mapping->addFieldResult('a', 'id', 'id');
...
$mapping->addMetaResult('a', 'a_type', 'a_type');
$mapping->setDiscriminatorColumn('a', 'a_type');
but how to map associated entities (B1,B2) ? I have try addJoinedEntityResult but it's require to use child class instead of base class. Is it possible to make such mapping? I didn't find any example of such case on DOCTRINE NATIVE QUERY

SSRS Page break every 1000 rows on group

I have the following table of data from an MDX query that resembles the following:
Account | Location | Type | Person | Amount
ABC | XYZ | AA | Tom | 10
ABC | XYZ | AA | Dick | 20
ABC | XYZ | AA | Harry | 30
ABC | XYZ | BB | Jane | 50
ABC | XYZ | BB | Ash | 100
DEF | SDQ | ZA | Bob | 20
DEF | SDQ | ZA | Kate | 10
DEF | LAO | PA | Olivia | 200
DEF | LAO | PA | Hugh | 120
And I need to add the Amount column for each Account, Location, and Type. If I was using SQL I would perform a query on this data as follows:
Select Account, Location, Type, Sum(Amount) as SumAmmount
From Table
Group By Account, Location, Type
but due to the way we store the data I need to roll-up this data using SSRS. To do that I created a tablix, created a parent group (Which I have called "RollUp") of the default detail group which grouped on Account, Location, and Type and then deleted the detail group so when running the report I get:
Account | Location | Type | Amount
ABC | XYZ | AA | 60
ABC | XYZ | BB | 150
DEF | SDQ | ZA | 30
DEF | LAO | PA | 320
What I need to do now is create a page break so that when I export this SSRS report to excel there are only 1000 rows on each sheet, but I am having trouble writing the expression to split this every 1000 rows. Because I have removed the details group I cannot use the typical expression I would use to page break on a specific row of a dataset (e.g. Group Expression = Floor(RowNumber(NOTHING) / 1000) )
I have tried a few different things like writing some custom code and some running value expressions but haven't been able to figure it out yet.
I did figure out how to do this.
First I created the following custom code in the report definition:
Dim GroupingDummy = "GroupDummy"
Dim RowNumberToReturn = -1
Function PopulateRowNumber(GroupString As String) As Integer
If (GroupString <> GroupingDummy ) Then
GroupingDummy = GroupString
RowNumberToReturn = RowNumberToReturn + 1
End If
Return RowNumberToReturn
End Function
Keeping in mind the grouping I applied to the dataset used the fields Account, Location, and Type, I added a calculated field to my dataset with the name RowNumberCalc and the expression:
=Code.RowNumberToReturn(Fields!Account.Value + Fields!Location.Value + Fields!Type.Value)
Now I could easily create the group that would create a page break at 1000 rows with the expression :
=Floor(Fields!RowNumberCalc.Value / 1000)