Have a form where user can change name on attribut Name and change which attribut a is connected to (attribut b).
Template:
"<form id="form1" name="form1" method="post" action="/define_a/{{c.id}}/edit/">
{% csrf_token %}
{% endblock %}
{% block buttons %}
<p><input type="submit" value="Save" /> Cancel
</p>
{% endblock %}
{% block a_rows %}
{% for a, a_form in a_list %}
<tr><td><img class="icon" src="{{images_dir}}/delete-icon.png"
onclick="javascript: return confirmDelete_name('Are you sure?
This will delete the stuff and all associated information.
The removal happens immediately and cannot be undone.', '{{a.id}}', 'delete');" />
</td><td>{{a_form.name}}</td>
<td>
<select name= "test">
<option value = "Null">None</option>
<option value = "{{a_form.id}}" selected>{{a.b}}</option>
{% for a, a_form in a_list %}
<option value = "{{a_form.id}}">{{a.name}}</option>
{% endfor %}"
View:
Checking that it is a post and that it is valid.
post = [myForm(request.POST, instance = test) for a in a's];
for p in post :
if not new_t.b == p:
if p == 'None':
new_t.b = None;
else:
new_t.b = p;
But i can't get all the values from the dropdown in the post.
I get all a.name in but only one value from the dropdown, sometimes I don't get any value at all.
Any ideas?
Related
I have created a checkbutton with Python (Django) like this:
in my views.py:
def list(response, list_id):
ls = ToDoList.objects.get(id=list_id)
if response.method == "POST": # If we are POST-ing something (saving, adding items, etc..)
print(response.POST)
if response.POST.get("save"): # SAVING CHECK-BUTTONS
for item in ls.listitem_set.all(): # Loop through all items
if response.POST.get("c" + str(item.id)) == "clicked": # Check if it has been clicked or not
item.complete = True
else:
item.complete = False
item.save()
elif response.POST.get("newItem"): # ADDING ITEM TO LIST
txt = response.POST.get("new") # Get text-input by name
if len(txt) > 2: # Check for valid input
ls.listitem_set.create(text=txt, complete=False)
else:
print("Invalid")
return render(response, "myapp/list.html", {"ls": ls})
and this is my list.html:
{% extends "myapp/base.html" %}
{% block title %}View List of Items{% endblock %}
{% block content %}
<h1>{{ls.name}}</h1>
<form method="POST" action="#">
{% csrf_token %}
<ul>
{% for item in ls.listitem_set.all %}
{% if item.complete == TRUE %}
<li><input type="checkbox" , value="clicked" , name="c{{item.id}}" checked>{{item.text}}</li>
{% else %}
<li><input type="checkbox" , value="clicked" , name="c{{item.id}}">{{item.text}}</li>
{% endif %}
{% endfor %}
</ul>
<button type="submit" , name="save" , value="save">Save</button> <!--Updates checked items -->
<input type="text" , name="new">
<button type="submit" , name="newItem" , value="newItem"> Add Item </button> <!--Adds new items -->
</form>
{% endblock %}
When I open 127.0.0.1:8000/list/1 in my broweser, it displays my 1st list with items and corresponding checkboxes. When I click on a checkbox it gets 'checked' but when I press save and reload, the box is unchecked again. What am I doing wrong here?
Hard to be certain without seeing the page in action, but I would try:
Changing your Django HTML tag if/else condition to 'True' rather than 'TRUE' as I believe in Python it's case sensitive.
Ensure you're ending up in the right path in your if/else statement.
I am currently doing a search using forms
This is my views.py
class HomeView(generic.ListView):
model = Consultant
template_name = 'sogeti/home.html'
def get_queryset(self):
query = self.request.GET.get('q')
if query:
return Consultant.objects.filter(
Q(first_name__icontains=query) |
Q(last_name__icontains=query) |
Q(group__title_techGroup__contains=query) |
Q(practices__title_practice__contains=query)
)
else:
return Consultant.objects.all()
and this is my home.html
<form action="" method="get" class="form-inline">
<input type="text" name="q" placeholder="Enter Keyword" value="{{ request.GET.q }}" class="form-control">
<select name="filter" class="form-control">
<option value="all">All</option>
<option value="people">People</option>
<option value="certification">Certification</option>
<option value="skillset">Skillset</option>
</select>
<input type="submit" value="Search" class="btn btn-default">
</form>
<ol style="padding-left: 15px">
{% for consultant in object_list %}
<li>
{{ consultant.first_name }}, {{ consultant.last_name }} </br>
Technology Group: {{ consultant.group }} </br>
Primary Practice: {{ consultant.practices }}
<hr style="margin-left: 0">
</li>
{% endfor %}
</ol>
My first problem is that when it tries to search something (Eg: bla) that is not in my database, it returns a blank screen. Nothing at all. Tried searching but could not get any answers.
My second problem is how am I able to specify my search using HTML select and options to filter. As you can see from my home.html I have the tag with option value but no idea how to utilize it for Django.
Thank you so much for your help! Really appriciate it.
About first issue, you actually can double check the object_list before iterate over it, e.g:
{% if object_list %}
<ul>
{% for item in object_list %}
<p>{{item.value}}</p>
{% endfor %}
</ul>
{% else %}
<p>Empty!</p>
{% endif %}
If you're unable to search, then double check your query by using some tools like django-debug-toolbar to take a look at the queries.
About the second question, I recommend you to use Django Form instead, like so:
Create forms.py:
from django.forms import Form, ChoiceField, CharField
class FilterForm(Form):
FILTER_CHOICES = (
('all', 'All'),
('people', 'People'),
('certification', 'Certification'),
('skillset', 'Skillset'),
)
search = CharField(required=False)
filter_field = ChoiceField(choices=FILTER_CHOICES)
Then your view (views.py):
class HomeView(ListView):
model = Consultant
template_name = 'home.html'
def get_queryset(self):
query = self.request.GET.get('search')
filter_field = self.request.GET.get('filter_field')
# Do your filter and search here
return Consultant.objects.all()
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['form'] = FilterForm(initial={
'search': self.request.GET.get('search', ''),
'filter_field': self.request.GET.get('filter_field', ''),
})
return context
and finally your template (templates/home.html):
<form class="row">
{{ form.search }}
{{ form.filter_field }}
<input type="submit" class="btn btn-default" value="Search">
</form>
Hope that would be helpful!
For the first issue, if there is nothing in the database it is returning an empty queryset so if you include
{% if object_list %}
do stuff
{% else %}
No results match your search
{% endif %}
For the second it depends on what you're trying to do, but let's suppose it is a
specific field you're searching.
search_choice = self.request.GET.get('filter')
choice_query = Q(search_field=search_choice)
Then simply add this to your query
views.py
class HomeView(generic.ListView):
model = Consultant
template_name = 'sogeti/home.html'
def get_queryset(self):
queryset = super().get_queryset()
q = self.request.GET.get('q')
if q:
queryset = queryset.filter(
Q(first_name__icontains=q) |
Q(last_name__icontains=q) |
Q(group__title_techGroup__contains=q) |
Q(practices__title_practice__contains=q)
)
filter = self.request.GET.get('filter')
if filter == 'people':
pass
elif filter == '...':
# do sth
return queryset
html
<form action="" method="get" class="form-inline">
<input type="text" name="q" placeholder="Enter Keyword" value="{{ request.GET.q }}" class="form-control">
<select name="filter" class="form-control">
<option value="all">All</option>
{% if request.GET.filter == 'people' %}
<option value="people" selected>People</option>
{% else %}
<option value="people">People</option>
{% endif %}
{% if request.GET.filter == 'certification' %}
<option value="certification" selected>Certification</option>
{% else %}
<option value="certification">Certification</option>
{% endif %}
{% if request.GET.filter == 'skillset' %}
<option value="skillset" selected>Skillset</option>
{% else %}
<option value="skillset">Skillset</option>
{% endif %}
</select>
<input type="submit" value="Search" class="btn btn-default">
</form>
<ol style="padding-left: 15px">
{% for consultant in object_list %}
<li>
{{ consultant.first_name }}, {{ consultant.last_name }} </br>
Technology Group: {{ consultant.group }} </br>
Primary Practice: {{ consultant.practices }}
<hr style="margin-left: 0">
</li>
{% empty %}
No result match q=`<b>{{ request.GET.q }}</b>` & filter=`{{ request.GET.filter }}`
{% endfor %}
</ol>
This is my code:
views.py:
def some_function(request):
form = MyForm(request.POST)
if request.method == 'GET':
return render_to_response('template.html', RequestContext(request, {'form': form}))
elif request.method == 'POST':
input_word = request.POST['input_word']
if 'word_choice' in request.POST:
word_choice = request.POST['word_choice']
else:
word_choice = ''
var1 = HelperClass(input_word).func1()
table1 = HelperClass(input_word).table_one()
table2 = HelperClass(input_word).table_two()
word_selected = word_choice
content = {
'form': form,
'input_word': input_word,
'var1': var1,
'table1' : table1,
'table2' : table2,
'word_selected': word_selected,
}
return render_to_response('result_template.html', RequestContext(request, content))
else:
raise Http404
This is result_template.html:
{% block content %}
<form action="/admin/find-word/" method="post">
{% csrf_token %}
<input id="input_word" type="text" name="input_word" maxlength="100"><br />
<input type="submit" value="Submit" />
<form />
<h1>{% trans "You entered" %} "{{ input_word }}" </h1>
<p>{{ var1 }}</p>
<form action="/admin/find-root/" method="post">
{% csrf_token %}
<h3>{% trans "Table2" %}</h3>
{% for word in table2 %}
# Get info from database and display it on the current template.
<input type="radio" name='word_choice' value="{{ word }}"> {{ word }}<br>
{% endfor %}
<h3>{% trans "Table3" %}</h3>
{% for word in table3 %}
{# Get info from database and display it on the current template. #}
<input type="radio" name='word_choice' value="{{ word }}"> {{ word }}<br>
{% endfor %}
<p>{% trans "You selected: " %}{{ word_selected }}</p>
{# Submit the word of choice.#}
<input type="submit" value="Search">
<form />
{% endblock %}
I need to add code to views.py, so that:
it shows result, that was rendered after submitting the first form
(when assining input_word)
new result shows, when resubmitting the first form
when submitting second form redirect to success_template.html (this part I can do myself)
I know, that I need to use sessions here. I've tried different things, but I'm lost now.
Create a session variable in django as follows.
request.session['key'] = value
Access it by
request.session['key'] # or
request.session.get('key')
remove it by
del request.session['key']
In django you can simply assign values to sessions with:
request.session['value']
In your case you'd have to replace the word_selected variable with request.session['word_selected']
I have different pages with items, each item has its own price which I would like to store in one variable and then send all of them to paypal payment form.
So question is,how can I store information about price from different pages? I tried sessions but nothing happens.
<article>
{% block content %}
<span>Kuriame mieste registruojiesi</span>
<select>
{% for item in upsell.skaidyti_miestus %}
<option value="{{item}}">{{ item }}</option>
{% endfor %}
</select>
{%if upsell.prideti_upsell_nr_2_taip%}
<button onclick="location.href='/upselliai/{{upsell.upsell_nr2_taip.id}}/pirkti/'">Taip, pridÄ—ti prie bendros sumos</button>
<!-- {#prideti kaina paimti ID} -->
{% else %}
<button onclick="location.href='/pirkejas/apmoketi'">Taip, pridÄ—ti prie bendros sumos</button>
{%endif%}
{%if upsell.prideti_upsell_nr_2_ne%}
{{ upsell.atsisakymo_tekstas }}
<!-- {#prideti kaina paimti ID} -->
{% else %}
{{ upsell.atsisakymo_tekstas }}
{%endif%}
{% endblock %}
</article>
my views.py
def pirkti_upsell(request, upsellis_id = 1):
#if 'pirkejas_id' in request.session:
session_pirkejas_id = request.session['pirkejas_id']
Upsellis.objects.get(id = upsellis_id).sum(session_pirkejas_id)
return render_to_response("upsell_template.html", {"upsell": Upsellis.objects.get(id = upsellis_id)})
I'm learning Python. I would like display results based on multiple selections from dropdowns.
The following code is working and returning the correct results for one dropdown. I would like to add at least one more dropdown, hopefully multiple, but I cannot fathom how to achieve passing and returning the multiple vars.
Form code
<p> <form method="get" action="">
<select name="search3">
{% for cs in course_list %}
<option value="{{ cs.pk }}">{{ cs.name }}</option>
{% endfor %}
</select>
<br/><br/>
<input type=submit value="Find staff" />
</form>
</p>
{% if employee_list %}
{{ employee_list.count }} employees matching : <strong>{{ course }}</strong><br/><br/>
{% for e in employee_list %}
{% if not e.img1 %}
<img src="/media/images/null_image.png" width="35" title="{{ e.first_name}} {{e.surname }}" />
{% else %}
<img src="{{ e.img1.url }}" width="50" title="{{ e.first_name}} {{e.surname }}"/>
{% endif %}
<a href="/employee/{{ e.slug }}" target="_blank" rel="popup" title="Details...<br />
{% for det in employee_list.employeedynamic_set.all %}
{{ det.mobile }}<br />
{{ det.depot }}<br />
{% endfor %}
"> {{ e.first_name }} {{ e.surname }}</a><br/>
{% endfor %}
{% else %}
<p>No employees matched: <strong>{{ course }}</strong></p>
{% endif %}
views.py code
# function to list training courses and participating uindividuals.
def CourseView(request):
course_list = Course.objects.all().order_by('name')
if 'search3' in request.GET:
search3 = request.GET['search3']
course = Course.objects.get(pk=search3)
else:
search3 = None
course = None
return render_to_response("course_display.html", {'course':course, 'course_list': course_list, 'search3': search3 })
Is it possible to add an another dropdown option or even multiple dropdown options and get a result. Or am I barking up the wrong tree?
UPDATE.
In order to pass one or multiple variables back to my function the code is simply the following
def CompetencyCheck(request):
course_list = Course.objects.all()
if 'search3' in request.GET:
search3 = request.GET.getlist('search3')
course = Course.objects.filter(id__in=search3).distinct().order_by()
.get() allows only the last variable passed from the web page form to be read/passed back to the function.
On the other hand, the .getlist() allows one or multiple vars to be passed back. Great, part the of problem solved.
The list of names being returned is unique in that if var1 returns 4 names and var2 returns 8 names and both vars have one common name, a list of 11 names in returned.
I want only the common names to both vars returned, i.e. 1 name to be returned.
Any ideas?
request.GET in your view is a dictionary; by doing request.GET['search3'] you're just accessing the value of its search3 key. So in your template, you should be able to just add other <select> elements with their own names and retrieve their submitted values from request.GET in the same way.
you can query using course_list only.
for example:
course_list = Course.objects.all().order_by('name')
var1 = request.POST.get('var1')
if var1:
course_list = course_list.objects.filter(some = var1)
var2 = request.POST.get('var2')
if var2:
course_list = course_list.objects.filter(some = var2)