Django dynamic form with additional meta data - django

I want to make an form for purchasing tickets. The problem is that for every event there can be diferent types of ticket with diferent price.
For every kind of ticket I will have to create an edit box where user can select how much tickets he wants.
Then in view class I will just display the dynamicly created form ... the only problem that I see now is that I don't know where to save an information for each ticket price so I can easy display it in the the same row where the edit box is?
P.S. I'm also not sure how can I dynamicly create a form using Django ... but this have to be easy ;)
P.S. Form have to be something like this:
--------------------------------------------------------
| Tiket Type | Price | How much? | Price |
--------------------------------------------------------
| Tiket Type Name | Price $1.00 | [ ] | Price... | [tiketkind.id = 1]
| Tiket Type Name | Price $2.00 | [ ] | Price... | [tiketkind.id = 12]
| Tiket Type Name | Price $3.00 | [ ] | Price... | [tiketkind.id = 18]
| Tiket Type Name | Price $4.00 | [ ] | Price... | [tiketkind.id = 21]
--------------------------------------------------------
| TOTAL PRICE: | ... |
--------------------------------------------------------
| Email: [ ] |
--------------------------------------------------------

This is pretty easy. Instead of thinking about making dynamic forms, think about making dynamic fields.
You'll have one form. When you initialize it, you'll pass it information about the tickets available. In the init of your form you will dynamically add field objects to the form by appending to self.fields.
Example:
self.fields['this_field_I_just_made_up'] = forms.CharField()
Notes:
The first thing you'll need to do in your init is to pop off your custom values.
The second thing you'll need to do in your init is to call the init of the superclass with *args and **kwargs.
If you don't do those two things, in that order, you will get errors.
Shawn
Source: http://groups.google.com/group/django-users/browse_thread/thread/3629184ceb11aeef

First of all, you're thinking in PHP. Don't do that. There's no need for array-like HTML element names.
I'm not entirely sure I understand your requirements, but it sounds like a formset will do what you want.

Related

Optimize code of a function for a search filter in django with variable numbers of keywords - too much code, i'm a beginner

Hello great community,
i'm learning django/python development, i'm training myself with development of a web app for asset inventory.
i've made a search filter, to give result of (for example) assets belonging to a specific user, or belonging to a specific department, or belonging to a specific brand, model or category (computers, desks, ecc..) there are many fields that mostly are foreign tables, main table is "Cespiti" that mean Asset in italian
now (after a lot) i've done with multiple keyword search (for example) somebody type in the search box the department and the category and obtain the relative results (for example all desks in a specific department, or all computer of a specific model in a specific department).
i've made it in a "if" check form that split the keyword in single words, count it and apply progressive filtering on the results of the previous keys in sequence.
but i'm not satisfact of my code, i think it's too much "hardcoded" and instead of creating an IF condition for each number of keyword (from 1 to 3) i wish like to code something that is not so dependent in the number of keyword, but is free.
Here's the code of the view, i hope someone can give me the right direction.
def SearchResults(request):
query = request.GET.get('q')
chiave =query.split()
lunghezza = int((len(chiave)))
if lunghezza == 1:
object_list = Cespiti.objects.filter(
Q(proprietario__cognome__icontains=chiave[0]) |
Q(proprietario__nome__icontains=chiave[0]) |
Q(categoria__nome__icontains=chiave[0]) |
Q(marca__nome__icontains=chiave[0]) |
Q(modello__nome__icontains=chiave[0]) |
Q(reparto__nome__icontains=chiave[0]) |
Q(matricola__icontains=chiave[0])
).distinct
elif lunghezza == 2:
object_list = Cespiti.objects.filter(
Q(proprietario__cognome__icontains=chiave[0]) |
Q(proprietario__nome__icontains=chiave[0]) |
Q(categoria__nome__icontains=chiave[0]) |
Q(marca__nome__icontains=chiave[0]) |
Q(modello__nome__icontains=chiave[0]) |
Q(reparto__nome__icontains=chiave[0]) |
Q(matricola__icontains=chiave[0])
).filter(Q(proprietario__cognome__icontains=chiave[1]) |
Q(proprietario__nome__icontains=chiave[1]) |
Q(categoria__nome__icontains=chiave[1]) |
Q(marca__nome__icontains=chiave[1]) |
Q(modello__nome__icontains=chiave[1]) |
Q(reparto__nome__icontains=chiave[1]) |
Q(matricola__icontains=chiave[1])
).distinct
elif lunghezza == 3:
object_list = Cespiti.objects.filter(
Q(proprietario__cognome__icontains=chiave[0]) |
Q(proprietario__nome__icontains=chiave[0]) |
Q(categoria__nome__icontains=chiave[0]) |
Q(marca__nome__icontains=chiave[0]) |
Q(modello__nome__icontains=chiave[0]) |
Q(reparto__nome__icontains=chiave[0]) |
Q(matricola__icontains=chiave[0])
).filter(Q(proprietario__cognome__icontains=chiave[1]) |
Q(proprietario__nome__icontains=chiave[1]) |
Q(categoria__nome__icontains=chiave[1]) |
Q(marca__nome__icontains=chiave[1]) |
Q(modello__nome__icontains=chiave[1]) |
Q(reparto__nome__icontains=chiave[1]) |
Q(matricola__icontains=chiave[1])
).filter(Q(proprietario__cognome__icontains=chiave[2]) |
Q(proprietario__nome__icontains=chiave[2]) |
Q(categoria__nome__icontains=chiave[2]) |
Q(marca__nome__icontains=chiave[2]) |
Q(modello__nome__icontains=chiave[2]) |
Q(reparto__nome__icontains=chiave[2]) |
Q(matricola__icontains=chiave[2])).distinct
context = {
'object_list': object_list, 'query' : query,
}
return render(request, 'search_results.html', context=context)
One way you could do it would be to separate the step of building the Q objects from the view method. That way it could be performed in a loop:
def generate_search_query_params(word):
return (
Q(proprietario__cognome__icontains=word) |
Q(proprietario__nome__icontains=word) |
Q(categoria__nome__icontains=word) |
Q(marca__nome__icontains=word) |
Q(modello__nome__icontains=word) |
Q(reparto__nome__icontains=word) |
Q(matricola__icontains=word)
)
def SearchResults(request):
query = request.GET.get('q')
queryset = Cespiti.objects.all()
for word in query.split():
queryset = queryset.filter(
generate_search_query_params(word)
)
object_list = queryset.distinct()
context = {
'object_list': object_list, 'query' : query,
}
return render(request, 'search_results.html', context=context)
thanks, i really appreciate your suggestion,
i reach to insert in a loop, now number of keywords is unlimited and it's not hardcode ( thanks a lot), i've thinked about Abdul idea and Damon solution, i wish to avoid the initial ".object.all() so i've arranged in this way: the first "level" is fixed, so i can avoid the .all() and all sublevels of filtering are looped, what do you think about?
def SearchResults(request):
query = request.GET.get('q')
chiave =query.split()
lunghezza = int((len(chiave)))
object_list = Cespiti.objects.filter(
Q(proprietario__cognome__icontains=chiave[0]) |
Q(proprietario__nome__icontains=chiave[0]) |
Q(categoria__nome__icontains=chiave[0]) |
Q(marca__nome__icontains=chiave[0]) |
Q(modello__nome__icontains=chiave[0]) |
Q(reparto__nome__icontains=chiave[0]) |
Q(matricola__icontains=chiave[0])
)
for I in range(1,lunghezza):
print(I)
object_list = object_list.filter(
Q(proprietario__cognome__icontains=chiave[I]) |
Q(proprietario__nome__icontains=chiave[I]) |
Q(categoria__nome__icontains=chiave[I]) |
Q(marca__nome__icontains=chiave[I]) |
Q(modello__nome__icontains=chiave[I]) |
Q(reparto__nome__icontains=chiave[I]) |
Q(matricola__icontains=chiave[I])
)
context = {
'object_list': object_list, 'query' : query,
}
return render(request, 'search_results.html', context=context)

Django display related objects inside related objects in the admin

According to my assignment admin must be able to create Polls with Questions (create, delete, update) and Choices related to this questions. All of this should be displayed and changable on the same admin page.
Poll
|
|_question_1
| |
| |_choice_1(text)
| |
| |_choice_2
| |
| |_choice_3
|
|_question_2
| |
| |_choice_1
| |
| |_choice_2
| |
| |_choice_3
|
|_question_3
|
|_choice_1
|
|_choice_2
|
|_choice_3
Ok, it's not a problem to display one level of nesting like so on
class QuestionInline(admin.StackedInline):
model = Question
class PollAdmin(ModelAdmin):
inlines = [
QuestionInline,
]
But how to do to get the required poll design structure?
Check out this library it should provide the functionality.

How do I find change point in a timeseries in PoweBi

I have a group of people who started receiving a specific type of social benefit called benefitA, I am interested in knowing what(if any) social benefits the people in the group might have received immediately before they started receiving BenefitA.
My optimal result would be a table with the number people who was receiving respectively BenefitB, BenefitC and not receiving any benefit “BenefitNon” immediately before they started receiving BenefitA.
My data is organized as a relation database with a Facttabel containing an ID for each person in my data and several dimension tables connected to the facttabel. The important ones here at DimDreamYdelse(showing type of benefit received), DimDreamTid(showing week and year). Here is an example of the raw data.
Data Example
I'm not sure how to approach this in PowerBi as I am fairly new to this program. Any advice is most welcome.
I have tried to solve the problem in SQL but as I need this as part of a running report i need to do it in PowerBi. This bit of code might however give some context to what I want to do.
USE FLISDATA_Beskaeftigelse;
SELECT dbo.FactDream.DimDreamTid , dbo.FactDream.DimDreamBenefit , dbo.DimDreamTid.Aar, dbo.DimDreamTid.UgeIAar, dbo.DimDreamBenefit.Benefit,
FROM dbo.FactDream INNER JOIN
dbo.DimDreamTid ON dbo.FactDream.DimDreamTid = dbo.DimDreamTid.DimDreamTidID INNER JOIN
dbo.DimDreamYdelse ON dbo.FactDream.DimDreamBenefit = dbo.DimDreamYdelse.DimDreamBenefitID
WHERE (dbo.DimDreamYdelse.Ydelse LIKE 'Benefit%') AND (dbo.DimDreamTid.Aar = '2019')
ORDER BY dbo.DimDreamTid.Aar, dbo.DimDreamTid.UgeIAar
I suggest to use PowerQuery to transform your table into more suitable form for your analysis. Things would be much easier if each row of the table represents the "change" of benefit plan like this.
| Person ID | Benefit From | Benefit To | Date |
|-----------|--------------|------------|------------|
| 15 | BenefitNon | BenefitA | 2019-07-01 |
| 15 | BenefitA | BenefitNon | 2019-12-01 |
| 17 | BenefitC | BenefitA | 2019-06-01 |
| 17 | BenefitA | BenefitB | 2019-08-01 |
| 17 | BenefitB | BenefitA | 2019-09-01 |
| ...
Then you can simply count the numbers by COUNTROWS(BenefitChanges) filtering/slicing with both Benefit From and Benefit To.

Create a new column using computed values in query set in Django?

I am working on top of an existing project, I am not allowed to make migrations to the current model. Suppose I have a model like this:
class Things(models.Model):
name = models.CharField(max_length=255)
objs = Things.objects.values('name')
will give me the following result
|objs|
|----|
|apple|
|orange|
|banana|
|fruits|
|car|
|bus|
|motorcycle|
|autombiles|
so if i do : somequery = objs.some_function(), how do i get the following result, assuming its possible.
|cats | objs |
|------------------ |
|automobiles|car |
|automobiles|bus |
|automobiles|motorcycle|
|fruits |apple |
|fruits |orange |
|fruits |banana |
-------------------------
from what I read about this so far, there isn't a straightforward way of solving this without altering the models.py. Any help/suggestion will help me tremendously.

cucumber Repeat steps

I am learing cucumber and trying to write a feature file.
Following is my feature file.
Feature: Doctors handover Notes Module
Scenario: Search for patients on the bases of filter criteria
Given I am on website login page
When I put username, password and select database:
| Field | Value |
| username | test |
| password | pass |
| database | test|
Then I login to eoasis
Then I click on doctors hand over notes link
And I am on doctors handover notes page
Then I select sites, wards, onCallTeam, grades,potential Discharge, outstanding task,High priority:
| siteList | wardsList | onCallTeamList | gradesList | potentialDischargeCB | outstandingTasksCB | highPriorityCB |
| THE INFIRMARY | INFIRMARY WARD 9 - ASSESSMENT | null | null | null | null | null |
| THE INFIRMARY | INFIRMARY WARD 9 - ASSESSMENT | GENERAL MEDICINE | null | null | null | null |
| THE INFIRMARY | INFIRMARY WARD 9 - ASSESSMENT | GENERAL MEDICINE | CONSULTANT | null | null | null |
| THE INFIRMARY | INFIRMARY WARD 9 - ASSESSMENT | GENERAL MEDICINE | CONSULTANT | true | null | null |
| THE INFIRMARY | INFIRMARY WARD 9 - ASSESSMENT | GENERAL MEDICINE | CONSULTANT | true | true | null |
| THE INFIRMARY | INFIRMARY WARD 9 - ASSESSMENT | GENERAL MEDICINE | CONSULTANT | true | true | true |
Then I click on search button
Then I should see search results
I want to repeat last three steps like I select the search criteria then click on search button and then check search result. So how should I break this feature file. if I use scenario outline then there would be two different scenarios One for login and one for search criteria. Is that fine? Will the session will maintain in that case? Whats the best way to write such feature file.
Or is this a right way to write?
I don't think we can have multiple example sets in a Scenario Outline.
Most of the scenario steps in the example is too procedural to have its own step.
The first three steps could be reduced to something like.
Given I am logged into eoasis as a <user>
Code in the step definition, which could make calls to a separate login method that could take care of updating entering the username, password and selecting database.
Another rule is to avoid statements like "When I click the doctor's handover link". The keyword to avoid here being click. Today its a click, tomorrow it could be drop down or a button. So the focus should be on the functional expectation of the user, which is viewing the handover notes. So we modify this to
When I view the doctor's handover notes link
To summarize, this is how I would write this test.
Scenario Outline: Search for patients on the basis of filter criteria
Given I am logged into eoasis as a <user>
When I view the doctor's handover notes link
And I select sites, wards, onCallTeam, grades, potential Discharge, outstanding task, High priority
And perform a search
Then I should see the search results
Examples:
|sites |wards |onCallTeam |grades |potential Discharge |outstanding task |High priority|
| THE INFIRMARY | INFIRMARY WARD 9 - ASSESSMENT | null | null | null | null | null |
This really is the wrong way to write features. This feature is very declarative, its all about HOW you do something. What a feature should do is explain WHY you are doing something.
Another bad thing this feature does is mix up the details of two different operations, signing in, and searching for patients. Write a feature for each one e.g.
Feature: Signing in
As a doctor
I want my patients data to only be available if I sign in
So I ensure their confidentiality
Scenario: Sign in
Given I am a doctor
When I sign in
Then I should be signed in
Feature: Search for patients
Explain why searching for patients gives value to the doctor
...
You should focus on the name of the feature and the bit at the top that explains why this has value first. If you do that well then the scenarios are much easier to write (look how simple my sign in scenario is).
The art of writing features is doing this bit well, so that you end up with simple scenarios.