How to insert a button in a dropdown selected option in Django? - html

I would like to insert a dropdown in Django that will return me to a page, and I am inserting a button that will lead to that page, but when I do this I return to the page I am currently in.
index.html
{% if lista_de_provas %}
<form method='post' action=''>
{% csrf_token %}
<select class="form-control" name="prova_selecionada" id="prova_selecionada">
{% for prova in lista_de_provas %}
<option id="{{prova.idProva}}" name="listaProvas" value='{{prova.idProva}}' disabled>{{prova.tipoProva}} {{prova.anoProva}}</option>
{% endfor %}
</select>
<input id="selProva" type="button" value="Confirma" onclick = "location.href ='{{prova.idProva}}';" />
</form>
{% endif %}
views.py
def index(request):
lista_de_provas = Prova.objects.all()
cprova = request.POST.get('idProva')
if request.method == 'POST':
sprova = Prova.objects.get(cprova = cprova)
sprova.select()
return redirect('polls/detalhes.html')
else:
form = ProvaForm()
return render(request, 'polls/index.html',{'form':form,'lista_de_provas': lista_de_provas})

There are two ways you can do this.
First, you can specify explicitly what object you want. If you are looking for the second element you can do something like this:
{% if lista_de_provas %}
<form method='post' action=''>
{% csrf_token %}
<select class="form-control" name="prova_selecionada" id="prova_selecionada">
<option id="{{prova.1.idProva}}" name="listaProvas" value='{{prova.1.idProva}}' desabled>{{prova.1.tipoProva}} {{prova.1.anoProva}}</option>Mdjss.199
</select>
<input id="selProva" type="button" value="Confirma" onclick = "location.href ='{{prova.1.idProva}}';" />
</form>
{% endif %}
Or to make it a bit more "Dynamic" and fail-safe, you can go in your view and use a .filter() on your object. So instead of lista_de_provas = Prova.objects.all() you can do something like:
lista_de_provas = Prova.objects.filter(id=2)
Sorry if I missed something. English is my first language.

Related

Django custom selection HTML page for django admin form

I have created a custom html template with basic checkboxes to select a value and return the value to the Django admin page.
I have done a 100 times before, but now the value of the selected superprofile does not get captured by the variable "selected_value" in the admin.py
The if statement "if request.method == 'POST':" is getting triggered but i keep getting the value of "selected_value" as none
Driving me crazy, I cannot find anything wrong in the code
The Html template
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static admin_modify %}
{% block extrahead %}
{{ media }}
{% endblock %}
{% block content %}
<form class="change_superprofile_parent_form" method="POST" class="change_superprofile_parent_form">{% csrf_token %}
{% for superprofile in superprofiles %}
<input type="checkbox" name="superprofile_selected" {{ superprofile.checked }} value="{{ superprofile }}"> {{ superprofile }}<br>
{% endfor %}
<input type="submit" value="Submit">
</form>
{% endblock %}
Django admin.py
def change_superprofile_parent(self, request, queryset):
"""
Action to change the superprofile of the selected
"""
queryset = queryset.values_list("id", flat=True)
if request.method == 'POST':
selected_value = request.POST.getlist('superprofile_selected')
eligible_superprofiles = SuperProfile.objects.filter(status='Active')
return render(
request, 'admin/auth/user/change_superprofile_parent.html', context={
'superprofiles': eligible_superprofiles,
}
)

How to handle await self.request.post()['users'] with multiple variables from HTML select tag for the same parameter in Aiohttp?

I want to receive users that a user has chosen to create a group chat. In an Aiohttp to get variable from HTML select tag, I use self.request.post()['variablename']:
#login_required
async def post(self):
data = await self.request.post()
chat_topic = data.get('chat_topic', '').lower()
users = data['users']
await Chat.create(topic=chat_topic, users=group_users)
This is my rooms.html:
{% extends 'base.html' %}
{% block content %}
<form class="form-signin" method="POST" action="{{ app.router['create_chat'].url_for() }}">
<h2 class="form-signin-heading">Create new chat</h2>
<label for="chat_topic" class="sr-only">chat topic</label>
<input name="chat_topic" type="text" id="chat_topic" class="form-control" maxlength="32" placeholder="chat topic" required autofocus>
<label for="users"> Choose users: </label>
<select name="users" id="users" multiple="multiple">
{% for user in users %}
<option value="{{ user.id }}">
{{ user.username }}
</option>
{% endfor %}
</select>
<button class="btn btn-lg btn-primary btn-block" type="submit">create chat</button>
</form>
{% endblock %}
Unfortunately, I receive only the last selected user as a string, not all of selected users. How can I get an array of selected users in aiohttp from an HTML select tag?
I know that in Django, I could do something like this:
users = request.POST.getlist('users')
I will appreciate any help!

Action attribute in html form tag is not sending the data in django

I want to send song.id from each song in an album model but every time I send it, I get A KeyError
This is what I wrote in details.html
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="{% url 'music:favorite' album.id %}">
{% csrf_token %}
{% for song in album.song_set.all %}
<input type="radio" id="song{{ song.id }}" name="song" value="{{ song.id }}">
<label for="song{{ song.id }}">
{{ song.song_title }}
{% if song.is_favorite %}
<img src="https://png.pngtree.com/png-vector/20190726/ourmid/pngtree-cute-light-star-with-black-frame-png-image_1633374.jpg">
{% endif %}
</label>
<br>
{% endfor %}
<input type="submit" value="Favorite">
</form>
This is my views.py
def favorite(request, album_id):
album = get_object_or_404(Album, pk=album_id)
try:
selected_song = album.song_set.get(pk=request.POST['song'])
except (KeyError, Song.DoesNotExist):
return render(request, 'music/detail.html', {
'album':album,
'error_message':"You did not select a valid song",
})
else:
selected_song.is_favorite = True
selected_song.save()
return render(request, 'music/detail.html', {'album':album})
I am answering my own question. So in the form tag, I had to include the method attribute and set it to POST.
Change
<form action="{% url 'music:favorite' album.id %}">
To
<form action="{% url 'music:favorite' album.id %}" method="POST">

pass data from one view to another django

I have two views in my app
Views.py
def selectwarehouse(request):
z = Warehouse.objects.all()
return render(request, 'packsapp/employee/selectwarehouse.html', {'z': z})
def warehouse_details(request):
queryset = AllotmentDocket.objects.filter(send_from_warehouse = #dynamic(from the selectwarehouse.html))
return render(request, 'packsapp/employee/allotwarehousedetails.html', {'query': queryset})
selectwarehouse.html
{% block content %}
<label>Select Warehouse<label>
<select id="the-id">
{% for i in z %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
<form method="post" novalidate>
{% csrf_token %}
Proceed
Nevermind
</form>
</select>
{% endblock %}
URLS.py
path('select-warehouse/', selectwarehouse, name='select_warehouse'),
path('warehouse-details/', warehouse_details, name='warehouse_details'),
I want that when a person selects the "Warehouse" from the dropdown and clicks on Proceed, it should pass that value to def warehouse_details and pass the value to Allotment queryset. How Can I do that ?
MAKE Proceed as a hidden input
Template
{% block content %}
<label>Select Warehouse<label>
<select id="the-id">
{% for i in z %}
<option value="{{ i }}">{{ i }}</option>
<form method="post" novalidate>
{% csrf_token %}
<input type="hidden" name="object_id" value="{{ i.id }}">
<input class="btn btn-outline-secondary" name="Proceed" type="submit"
value="Proceed">
<a href="{% url 'employee:products_table' %}" class="btn btn-outline-
secondary" role="button">Nevermind</a>
</form>
{% endfor %}
</select>
{% endblock %}
views.py
def selectwarehouse(request):
z = Warehouse.objects.all()
return render(request, 'packsapp/employee/selectwarehouse.html', {'z': z})
def warehouse_details(request):
queryset = AllotmentDocket.objects.get(id=request.POST.get('object_id'))
//Now to access the element in queryset write (queryset.'attribute name')
return render(request, 'packsapp/employee/allotwarehousedetails.html', {'query':
queryset}
Check if this works
Try printing the queryset and see what is the output.

How to call a function from a html button - Django

What I'm trying to do is execute a function when the user clicks the "add to cart" button, the product displayed on the screen will be added to the cart model. So far i've figured out how to add objects to the cart from the shell. What i don't know is how to call a python function with html and how to pass the object to it. Thank you in advance.
my template.html:
{% extends 'templates/header.html' %}
<title>{% block head_title %}{{ object.name }} - {{ block.super }}{% endblock head_title %}</title>
{% block head %}
{{ block.super }}
{% load staticfiles %}
<link rel = "stylesheet" href = "{% static 'css/products_detail.style.css' %}" type = "text/css"/>
{% endblock head %}
{% block content %}
<div id='Product-Page'>
<p>{{ object.name }}</p>
<hr>
<div id='Product-Image'>
<img src='{{ object.image.url }}' alt='{{ object.image.name }}'/>
</div>
<div id='Product-Details'>
<p id='Product-Name'>{{ object.name }}</p>
<p id='Product-Description'><small>{{ object.description }}</small></p>
</div>
<div id='Product-Buy'>
<p id='Product-Price'>{{ object.price }} лв.</p>
<p id='Product-Quantity'>{{ object.quantity }} </p>
<form class='Product-Form' method='post' action='#'>
{% csrf_token %}
<input class='Product-Button' type='submit' value='Buy Now'>
</form>
<form class='Product-Form' method='get' action=''>
{% csrf_token %}
<input class='Product-Button' type='submit' value='Add to cart'>
</form>
</div>
<hr>
</div>
{% endblock content%}
my view:
class ProductDetailView(DetailView):
template_name = 'products/products_detail.html'
def get_object(self, *args, **kwargs):
slug = self.kwargs.get('slug')
return get_object_or_404(Product, slug=slug)
You can add hidden inputs to each form (both of which should be POST methods, not GET) then add a post method to your view. Something like:
<form class='Product-Form' method='post'>
{% csrf_token %}
<input name="buy-now" hidden>
<input name="pk" value="{{ object.pk }}" hidden>
<button type="submit" class="btn">Buy Now</button>
</form>
<form class='Product-Form' method='post'>
{% csrf_token %}
<input name="add-to-cart" hidden>
<input name="pk" value="{{ object.pk }}" hidden>
<button type="submit" class="btn">Add to cart</button>
</form>
Then in your view:
class ProductDetailView(DetailView):
template_name = 'products/products_detail.html'
def get_object(self, *args, **kwargs):
slug = self.kwargs.get('slug')
return get_object_or_404(Product, slug=slug)
def post(self, request, *args, **kwargs):
name = request.POST.get("pk")
product = Product.objects.get(pk=pk)
if "buy-now" in request.POST:
#Do something to buy.
print('buy now ' + product.name)
elif "add-to-cart" in request.POST:
#Add to cart.
print('add to cart ' + product.name)
return redirect('home')
Or you can do it via AJAX if you don't want to reload the page.