i need some help with Django, i keep encounter the MultiValueDictKeyError when i click the download button. And it shows MultiValueDictKeyError at /upload/
'my_file' but not sure how to solve it after several attempts. Below are my codes for models, view, and the template page. For your advice please.
files_ul_dl.html
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="file" name="my_file">
<button class="btn btn-secondary" type="submit">Upload</button>
</form>
</div>
<hr>
<h4>File Type Count</h4>
<table class="table">
<thead>
<tr>
{% for file_type in file_types %}
<th scope="col">{{ file_type }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<tr>
{% for file_type_count in file_type_counts %}
<td>{{ file_type_count }}</td>
{% endfor %}
</tr>
</tbody>
</table>
<br/>
<h4>Files</h4>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">file name</th>
<th scope="col">size</th>
<th scope="col">file type</th>
<th scope="col">upload date</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{% for file in files %}
{% url 'files_upload:download_file' as download_file_url%}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td>{{ file.upload.name }}</td>
<td>{{ file.size }}</td>
<td>{{ file.file_type }}</td>
<td>{{ file.upload_datetime }}</td>
<td>
<form action="{{ download_file_url }}" method="post">
{% csrf_token %}
{{ form }}
<input type="hidden" name="path" value="{{ file.upload.name }}">
<input type="submit" class="btn btn-primary label-success" value="Download" />
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table><hr>
views.py
def files_upload(request):
context = {}
if request.method == 'POST':
uploaded_file = request.FILES['my_file']
if uploaded_file.content_type not in file_content_types:
print("INVALID CONTENT TYPE")
else:
new_file = File(upload=uploaded_file, file_type=uploaded_file.content_type)
new_file.save()
print(uploaded_file.content_type)
qs = File.objects.all().order_by('-upload_datetime')
context['files'] = qs
context["file_types"] = file_content_types
file_type_counts = []
for file_type in file_content_types:
count = File.objects.filter(file_type=file_type).count()
file_type_counts.append(count)
context["file_type_counts"] = file_type_counts
return render(request, "files_ul_dl.html", context)
def download_view(request):
if request.method == 'POST':
path = request.POST.get('path')
print(path)
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/force-download")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
Related
I'm trying to add a delete button on my users admin page in a flask app.
But I already have this error when I click on button :
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.str' is not mapped
This is my adminusers.html file :
{% extends 'base.html' %}
{% block main %}
<main>
<table class="table table-striped users">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Roles</th>
<th scope="col" class="text-center">Delete</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<th scope="row">{{ user.id }}</th>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>
{% for role in user.roles %}
{{role.name}};
{% endfor %}
</td>
<td style="text-align: center;"></i></td>
</tr>
{% endfor %}
</tbody>
</table>
</main>
{% endblock main %}
And my app.py file :
#app.route('/adminusers')
def list_users():
users= User.query.all()
return render_template('adminusers.html', users=users)
#app.route('/delete_user/<user>')
def delete_user(user):
user_datastore.delete_user(user=user)
db.session.commit()
return redirect(url_for('adminusers'))
I'm trying to use the 'email' or 'name' but it already return an error
Thanks #pjcunningham, like that it works :
#app.route('/delete_user/<id>')
def delete_user(id):
user = user_datastore.get_user(id)
user_datastore.delete_user(user)
db.session.commit()
return redirect(url_for('adminusers'))
I am trying to delete severals rows at the same time in django.
How can I simply change the state of the booleanfield 'to_delete', just by clicking on the checkbox?
I am using datatables. The way how I am doing it is to create a boolean to_delete in my model, when the checkbox is selected, I am calling the function delete_multiple_company in my view. However, this doesn`t work. Any idea, what I am doing wrong please. Many Thanks,
I`ve created my view:
views.py
def delete_multiple_company(request, company_id):
company = get_object_or_404(Company, pk=company_id)
company = Company.objects.get(pk=company_id)
company.objects.filter(to_delete=True).delete()
return HttpResponseRedirect(reverse("company:index_company"))
urls.py
url(r'^(?P<company_id>[0-9]+)/delete_multiple_company/$', views.delete_multiple_company, name='delete_multiple_company'),
models.py
class Company(models.Model):
to_delete = models.BooleanField(default=False)
index.html
<span class="fa fa-plus"></span>Delete Companies
<table id="dtBasicExample" class="table table-striped table-hover">
<thead>
<tr>
<th>Select</th>
<th>#</th>
<th>Checked ?</th>
</tr>
</thead>
<tbody>
{% for company in companys.all %}
<tr>
<td id="{{ company.id }}"><input type="checkbox" class="companyCheckbox" name="checkedbox" id="{{ company.id }}" value="{{ company.id }}"></td>
<td>{{ company.id }}</td>
<td>{{ company.to_delete }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I experienced a similar issue as you, what I did was put in a form.
index.py
<form method="POST" class="post-form">{% csrf_token %}
<button type="submit" class="save btn btn-default">Delete</button>
<span class="fa fa-plus"></span>Delete Companies</a>
<table id="dtBasicExample" class="table table-striped table-hover">
<thead>
<tr>
<th>Select</th>
<th>#</th>
<th>Checked ?</th>
</tr>
</thead>
<tbody>
{% for company in companys.all %}
<tr>
<td id="{{ company.id }}"><input type="checkbox" class="companyCheckbox" name="checkedbox" id="{{ company.id }}" value="{{ company.id }}"></td>
<td>{{ company.id }}</td>
<td>{{ company.to_delete }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<button type="submit" class="save btn btn-default">Delete</button>
</form>
Clicking on the button then triggered the POST method in my view.
views.py
def index(request):
if request.method == 'POST':
print('I made it here')
# Put your code here, note you will return a dict, so some trial and error should be expected
html file
<form method="post">
{% csrf_token %}
<table border="2" bordercolor="black" width="500" height="100" cellspacing="0" cellpadding="5">
<thead>
<tr>
<th>selection</th>
<th>student name</th>
<th>e-mail</th>
<th>CV</th>
</tr>
</thead>
<tbody>
{% for ta in tas %}
<tr>
<td><input type="checkbox" name="checkbox_list" value="{{ ta.id }}"></td>
<td>{{ ta.user.first_name }} {{ ta.user.last_name }}</td>
<td>{{ ta.user.email }}</td>
<td>view cv</td>
</tr>
{% endfor %}
</tbody>
</table>
<button type="submit">next</button>
</form>
views.py
def ta_ranking(request, id):
print('hello word!')
check_box_list = request.POST.getlist('checkbox_list')
if check_box_list:
print(check_box_list)
potential_ta = TA.objects.filter(id__in=check_box_list)
return render(request, 'ta_ranking.html', {'potential_ta': potential_ta, 'course_id': id})
return redirect('ta_list', id=id)
my question is that the ta_ranking class in views.py didn't be called when I click the submit button in html. How can I fix this problem?
Thanks for any help!
You didn't include the path to the view in your form:
<form method="POST" action="/path/to/ta_ranking">
...
</form>
You also need to add it to your urls.py if you haven't already:
from django.urls import path
from myapp.views import ta_ranking
urlpatterns = [
path('/path/to/ta_ranking', ta_ranking),
]
This question already has an answer here:
NoReverseMatch at /kitty_view Reverse for 'kitty' with arguments '(5,)' not found. 1 pattern(s) tried: ['kitty$']
(1 answer)
Closed 3 years ago.
// While rendering this kitty_view I am getting this error. Exactly the same thing I have copied from another app that is working properly. Kindly help. Exactly same thing is working for some other app.
view.py
------------------
def kitty_view(request):
kitty_list = kitty.objects.all().order_by('-cretime')
code1 = str(request.GET.get('Code'))
name1 = str(request.GET.get('nam'))
status1 = str(request.GET.get('stat'))
if (name1 is not None and name1 != ''):
kitty_list = kitty_list.filter(name=name1)
if (code1 is not None and code1 != ''):
kitty_list = kitty_list.filter(code='K00001')
if (status1 is not None and status1 != ''):
kitty_list = kitty_list.filter(status = 'A')
ctx = {'kitty': kitty_list}
return render(request, 'kitty/kitty_view.html', ctx)
Url.py
-----
urlpatterns = [
path('',views.index,name='index'),
path('kitty_view',views.kitty_view,name='kitty_view')
]
template
---------
<form class="form-signin" action="{% url 'kitty_view' %}" method="get">
{% csrf_token %}
<div class="form-row">
<div class="mb-3">
<select class="custom-select center-block" name="code" id="code">
<option value="">Choose Kitty...</option>
<!-- <option>{{ kitty1.code }}</option>
{% for i in kitty1 %}
<option value="{{ i.code }}"> {{ i.code|add:' - '|add:i.name }} </option>
{% endfor %} -->
<option>K00004</option>
<option>K00005</option>
</select>
</div>
<div class="mb-3">
<input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Name" autofocus>
</div>
<div class="mb-3">
<select class="custom-select center-block" name="stat" id="stat" placeholder="Status">
<option value="">Choose Status...</option>
<option>A</option>
<option>I</option>
</select>
</div>
<div class="mb-3">
<!-- Search -->
<button type="submit" class=" btn btn-info " role="button">Search</button>
</div>
</div>
</form>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Kitty Code</th>
<th scope="col">Name</th>
<th scope="col">Type</th>
<th scope="col">Start Date</th>
<th scope="col">Total Months</th>
<th scope="col">End Date</th>
<th scope="col">Total Members</th>
<th scope="col">Amount</th>
<th scope="col">Installment</th>
<th scope="col">Status</th>
<th scope="col">Details</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
{% if kitty %}
<h1>Biswajit1</h1>
{% for i in kitty %}
<h1>Biswajit</h1>
<tbody>
<tr>
<td>{{ i.id }} </td>
<td>{{ i.code }} </td>
<td>{{ i.name }} </td>
<td>{{ i.type }} </td>
<td>{{ i.startdate }} </td>
<td>{{ i.noofmonths }} </td>
<td>{{ i.enddate }} </td>
<td>{{ i.totalmembers }} </td>
<td>{{ i.totalamount }} </td>
<td>{{ i.noofinstallments }} </td>
<td>{% if i.status == 'A' %}
{{ 'Active' }}
{% else %}
{{ 'Inactive' }}
{% endif %}
</td>
</tr>
</tbody>
{% endfor %}
{% endif %}
</table>
{% endblock %}
I am scraping several sites and I show the data obtained in 6 tables within a django template.
My intention is to persist the data of the tables in postgresql, but I can not realize how to perform that task.
In principle I am trying to save the data from the second table.
For this I have created the models that I show below, as well as a view that is called: registroDivisaArgentina ().
The template is called quotes.html and within it, there are 6 tables.
I have tried to work with a class called: RegisterArgentineValues () within a forms.py file
models.py
class DivisasArgentina(models.Model):
class Meta:
ordering = ['CodigoDA']
CodigoDA = models.CharField(max_length=50, primary_key = True)
Texto_para_Reporte = models.CharField(max_length=70)
def __str__(self):
return '{}'.format(self.Texto_para_Reporte)
class ValoresDivisasArgentina(models.Model):
class Meta:
ordering = ['Dia']
DivisasArgentina = models.ForeignKey(DivisasArgentina, on_delete=models.PROTECT)
Dia = models.DateField(default=date.today)
Hora = models.DateTimeField(default=timezone.now)
Compra = models.FloatField()
Venta = models.FloatField()
Variacion_dia_anterior = models.FloatField()
ClaveComparacion = models.CharField(max_length=1)
def __str__(self):
return '{} - {} - {}'.format(self.DivisasArgentina, self.Dia, self.ClaveComparacion)
cotizaciones.html
{% extends 'base.html' %}
{% block contenido %}
<form method="POST" class="post-form">{% csrf_token %}
<div class="container">
<table class="table table-striped table-bordered" id="tab1">
<thead>
<tr>
<th>Divisas en el Mundo</th>
<th>Valor</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_mun%}
<tr>
{% for key,value in element.items %}
<td> {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
</table>
</div>
<div class="container">
<table class="table table-striped table-bordered" id="tab2">
<thead>
<tr>
<th>Divisas en Argentina</th>
<th>Compra</th>
<th>Venta</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_arg%}
<tr>
{% for key,value in element.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
<thead>
{{ form.as_table }}
</table>
</div>
<div class="container">
<table class="table table-striped table-bordered" id="tab3">
<thead>
<tr>
<th>Dolar Banco Nacion Argentina (Divisas)</th>
<th>Compra</th>
<th>Venta</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_exp%}
<tr>
{% for key,value in element.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab4">
<thead>
<tr>
<th colspan="4">Dolar Futuro en Argentina</th>
</tr>
<tr>
<th>Mes 1</th>
<th>Mes 2</th>
<th>Mes 3</th>
<th>Mes 4</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_dol%}
<td>
{{ element.Valores}}
</td>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab5">
<thead>
<tr>
<th colspan="3">Indicadores Varios - Tasa Libor</th>
</tr>
<tr>
<th>Libor a 1 Mes</th>
<th>Libor a 2 Mes</th>
<th>Libor a 3 Mes</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_lib%}
<td>
{{ element.Valores }}
</td>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab6">
<thead>
<tr>
<th>Indicadores Varios - Indice Merval y Oro</th>
<th>Valores</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_ind%}
<tr>
{% for key,value in element.items %}
<td> {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tr>
</tbody>
</table>
</div>
<div class="container" id="saveData">
<br></br>
<button type="submit" class="btn btn-primary pull-right">Guardar Datos</button>
</div>
</form>
{% endblock %}
views.py
def mostrar_cotizaciones(request):
cotiz_arg = json.loads(j_cotizaciones_argentina)
cotiz_mun = json.loads(j_cotizaciones_mundiales)
cotiz_exp = json.loads(j_cotizacion_export)
cotiz_dol = json.loads(j_dolar_futuro)
cotiz_ind = json.loads(j_indicadores)
cotiz_lib = json.loads(j_libor)
context = {'cotiz_mun': cotiz_mun,
'cotiz_arg': cotiz_arg,
'cotiz_exp': cotiz_exp,
'cotiz_dol': cotiz_dol,
'cotiz_ind': cotiz_ind,
'cotiz_lib': cotiz_lib,
}
return render(request, 'cotizaciones.html', context)
def registrarDivisaArgentina(request):
if request.method == 'POST':
formulario = RegistrarValoresDivisasArgentinas(request.POST)
if formulario.is_valid():
formulario.save()
return HttpResponseRedirect('/listadoValores')
else:
formulario = RegistrarValoresDivisasArgentinas()
formulario.setup('Registrar', css_class="btn btn-success")
return render(request, 'cotizaciones.html', {'formulario':formulario})
forms.py
from django import fla
from django.forms import ModelForm
from django import forms
from fla.models import *
class RegistrarValoresDivisasArgentinas(forms.ModelForm):
class Meta:
model = ValoresDivisasArgentina
fields= [Compra, Venta]
I have done some tests, but none has given a favorable result. Someone can tell me how to process the data (in the views and forms) that are in the tables, to be able to store them in my postgres tables ?
I do this kind of task very often, and I've found out that the combination of ScraPy with scrapy-djangoitem is a very good combo to use here.
Good luck!