I am newbie to Python and Django.
I'm using DAL on a form inside a Bootstrap modal. Clicking the dropdown list appears behind the modal. The autocomplete function works correctly if I do it outside of the modal.
I'm using:
Django: 4.0.5
django-autocomplete-light: 3.9.4
Bootstrap 5.2.2
Python 3.10.4
To try to fix it, I have created a style.css file with the following code, as indicated in:
bootstrap modal with select2 z-index
.select2-container {
z-index: 9999 !important;
}
Now the list appears in front of the modal, but it doesn't allow typing in the search box. I've tried doing the following, but it doesn't work:
https://select2.org/troubleshooting/common-problems
$(document).ready(function() {
$("#codigo_emplazamiento").select2({
dropdownParent: $("#FormularioCrear")
});
});
I've tried removing tabindex="-1" from the modal, but it doesn't work.
It seems to be related to this, but I can't get it to work:
https://lightrun.com/answers/yourlabs-django-autocomplete-light-search-input-not-receiving-focus
This is my code:
forms.py
class FormularioTarea(forms.ModelForm):
class Meta:
model = Tarea
fields = ['referencia_interna', 'codigo_emplazamiento', 'estado', 'fecha_fin', 'tipo_documento']
autocomplete.ModelSelect2(url='emplazamientoautocompletar')})
widgets = {
'codigo_emplazamiento': autocomplete.Select2(
url='emplazamientoautocompletar',
)
}
models.py
class Emplazamiento(models.Model):
TIPO_ELECCION = (('URB', 'Urbano'), ('RUR', 'Rural'))
codigo_emplazamiento = models.CharField(unique=True, max_length=10)
direccion = models.CharField(max_length=254)
municipio = models.ForeignKey(Municipio, on_delete=models.PROTECT)
ref_catastral = models.CharField(max_length=14, blank=True)
tipo_emplazamiento = models.CharField(max_length=15, choices=TIPO_ELECCION)
latitud = models.DecimalField( blank=True, null=True, decimal_places=10, max_digits=13)
longitud = models.DecimalField( blank=True, null=True, decimal_places=10, max_digits=13)
def save(self, *args, **kwargs):
self.codigo_emplazamiento = self.codigo_emplazamiento.upper()
return super(Emplazamiento, self).save(*args, **kwargs)
class Meta:
ordering =('-id',)
def __str__(self):
return (self.codigo_emplazamiento)
class Tarea(models.Model):
referencia_interna = models.CharField(max_length=20, unique=True)
codigo_comparticion = models.CharField(max_length=20, unique=True, blank=True, null=True)
ESTADOS_DE_TAREA = (('PENDIENTE', 'Pendiente'), ('EN_CURSO', 'En Curso'), ('FINALIZADO', 'Finalizado'))
codigo_emplazamiento = models.ForeignKey(Emplazamiento, on_delete=models.PROTECT)
estado = models.CharField(max_length=15, choices=ESTADOS_DE_TAREA)
SELECCION_DE_DOCUMENTOS = (('PROYECTO', 'Proyecto'), ('ANEXO', 'Anexo'), ('PEP', 'Pep'))
tipo_documento = models.CharField(max_length=15, choices=SELECCION_DE_DOCUMENTOS)
fecha_entrada = models.DateField(auto_now_add=True)
fecha_fin = models.DateField(blank=True, null=True)
class Meta:
ordering =('-id',)
def __str__(self):
return (self.referencia_interna + ' - ' + str(self.id))
urls.py
urlpatterns = [
path('emplazamientos/autocompletar', EmplazamientoAutocomplete.as_view(), name = 'emplazamientoautocompletar'),
]
views.py
class EmplazamientoAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
#if not self.request.user.is_authenticated:
# return Country.objects.none()
qs = Emplazamiento.objects.all()
if self.q:
qs = qs.filter(codigo_emplazamiento__icontains=self.q)
return qs
Modal in Template:
<div class="modal fade" id="FormularioCrear" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">{{ titulocreador }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" id="CuerpoModal">
<form method="POST" enctype="multipart/form-data" action=" {% url 'creatarea' %}">
{% csrf_token %}
{{ formulario.as_p }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">Crear</button>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#codigo_emplazamiento").select2({
dropdownParent: $("#FormularioCrear")
});
});
</script>
Modal in rendered template:
<div class="modal fade" id="FormularioCrear" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Crea nueva Tarea</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" id="CuerpoModal">
<form method="POST" enctype="multipart/form-data" action=" /proyectos/tareas/crear/">
<input type="hidden" name="csrfmiddlewaretoken" value="kWogOGY57TUQv49PCR5CroMbEmpMiM5qNUC17gTI6gPZjrq3riiuiXrhm2STNuTk">
<p>
<label for="id_referencia_interna">Referencia interna:</label>
<input type="text" name="referencia_interna" maxlength="20" required id="id_referencia_interna">
</p>
<p>
<label for="id_codigo_emplazamiento">Codigo emplazamiento:</label>
<select name="codigo_emplazamiento" required id="id_codigo_emplazamiento" data-autocomplete-light-url="/proyectos/emplazamientos/autocompletar" data-autocomplete-light-function="select2" data-autocomplete-light-language="es">
</select>
</p>
<p>
<label for="id_estado">Estado:</label>
<select name="estado" required id="id_estado">
<option value="" selected>---------</option>
<option value="PENDIENTE">Pendiente</option>
<option value="EN_CURSO">En Curso</option>
<option value="FINALIZADO">Finalizado</option>
</select>
</p>
<p>
<label for="id_fecha_fin">Fecha fin:</label>
<input type="text" name="fecha_fin" id="id_fecha_fin">
</p>
<p>
<label for="id_tipo_documento">Tipo documento:</label>
<select name="tipo_documento" required id="id_tipo_documento">
<option value="" selected>---------</option>
<option value="PROYECTO">Proyecto</option>
<option value="ANEXO">Anexo</option>
<option value="PEP">Pep</option>
</select>
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">Crear</button>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#codigo_emplazamiento").select2({
dropdownParent: $("#FormularioCrear")
});
});
</script>
The problem is modal focus, so if you review the documentation https://getbootstrap.com/docs/5.3/components/modal/#options in options there's a definition for the focus. So at the end you just need to add data-bs-focus="false" to your modal definition.
...
Related
I really don't understand how to connect these two fields or should I just create one. On my front, I have a starting date and end date I can not connect to the backend properly using django-filters Please see the below code
My filters.py
class VideoFolderFilter(FilterSet):
name = CharFilter(field_name='name', lookup_expr='icontains', widget=forms.TextInput(attrs={'class': "form-control"}))
subscription_plan = ModelChoiceFilter( label='subscription_plan', queryset=Plans.objects.all())
start_date_range = DateFromToRangeFilter(field_name='start_date_range', widget=forms.TextInput(attrs={'class': "form-control"}))
end_date_range = DateFromToRangeFilter(field_name='end_date_range', widget=forms.TextInput(attrs={'class': "form-control"}))
def get_date_range(self, start_date_range, end_date_range):
return Sample.objects.filter(sampledate__gte=start_date_range,
sampledate__lte=end_date_range)
class Meta:
model = VideoFolder
fields = '__all__'
widgets = {'start_date_range': DateInput(),}
exclude = [ 'thumbnail_link', 'link', 'name']
My views.py
#login_required
def search_videos(request):
if Subscriber.objects.filter(user=request.user).exists():
subscription = Subscriber.objects.get(user=request.user)
else:
message = "Seams like you don't have subscription with us please select one of the plans"
return redirect(reverse('main'))
video_filter = VideoFolderFilter(request.GET, queryset=VideoFolder.objects.filter(type='video').order_by('-created_date'))
videos = video_filter.qs
return render(request, 'search-videos.html', locals())
Should I change the views.py to query if yes how to date range and other fields will be included
And my search-videos.html
<div class="search-video-form-section mb-3">
<p>Use one or more filters to search below</p>
<form method="GET">
<div class="form-group mb-px-20 filter-form">
<label class="text-base">Name Contains</label>
<!-- <input type="text" class="form-control" placeholder="Keyword" /> -->
{{ video_filter.form.name }}
</div>
<div class="d-flex flex-wrap date-box">
<div class="form-group input-field">
<label class="text-base">Start Date</label>
<div class="input-group input-daterange">
{{ video_filter.form.start_date_range }}
</div>
</div>
<div class="form-group input-field">
<label class="text-base">End Date</label>
<div class="input-group input-daterange">
{{ video_filter.form.end_date_range }}
</div>
</div>
</div>
<div class="form-group filter-form">
<label class="text-base">Subscription</label>
{{ video_filter.form.subscription_plan }}
</div>
<button class="btn text-white bg-info mt-4">Search</button>
</form>
</div>
I am using Django with MySQL database. Everything is working, but the data I input will not save to the database.
This is my HTML:
<form class="space-y-8 divide-y divide-gray-200 m-2">
{% csrf_token %}
<div class="space-y-8 divide-y divide-gray-200">
<div class="pt-8">
<div>
<h3 class="text-lg leading-6 font-medium text-gray-900">
Project Information
</h3>
</div>
<div class="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
<div class="sm:col-span-3">
<label for="project-name" class="block text-sm font-medium text-gray-700">
Project Name
</label>
<div class="mt-1">
<input type="text" name="project-name" id="project-name"
class="shadow-sm focus:ring-gray-500 focus:border-gray-500 block w-full sm:text-sm border-gray-300 rounded-md">
</div>
</div>
<div class="sm:col-span-3">
<label for="project-location" class="block text-sm font-medium text-gray-700">
Project Location
</label>
<div class="mt-1">
<input type="text" name="project-location" id="project-location"
class="shadow-sm focus:ring-gray-500 focus:border-gray-500 block w-full sm:text-sm border-gray-300 rounded-md">
</div>
</div>
</div>
<div class="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
<div class="sm:col-span-3">
<label for="project-operator" class="block text-sm font-medium text-gray-700">
Operator
</label>
<div class="mt-1">
<input type="text" name="project-operator" id="project-operator"
class="shadow-sm focus:ring-gray-500 focus:border-gray-500 block w-full sm:text-sm border-gray-300 rounded-md">
</div>
</div>
<div class="sm:col-span-3">
<label for="project-start-date" class="block text-sm font-medium text-gray-700">
Start Date
</label>
<div class="mt-1">
<input type="text" name="project-start-date" id="project-start-date"
class="shadow-sm focus:ring-gray-500 focus:border-gray-500 block w-full sm:text-sm border-gray-300 rounded-md">
</div>
</div>
</div>
</div>
<div class="pt-5">
<div class="flex justify-end">
<button type="submit"
class="ml-3 inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-gray-600 hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
Save
</button>
</div>
</div>
</div>
</form>
This is my views.py
def project(request):
if request.method == 'POST':
form = ProjectForm(request.POST or None)
if form.is_valid():
form.save()
all_items = Project.objects.all
return render(request, 'project.html', {'all_items': all_items})
all_items = Project.objects.all
return render(request, 'project.html', {'all_items': all_items})
This is my forms.py:
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['project_name', 'project_location',
'operator', 'date_started']
This is my models.py
class Project(models.Model):
project_name = models.CharField(max_length=30)
project_location = models.CharField(max_length=30)
operator = models.CharField(max_length=30)
date_started = models.DateField()
I am not getting any errors, but the data I save is not saved in the database. Can anyone see what I need to fix?
In your view which directs you to html page :
def project(request):
if request.method == "POST":
form = ProjectForm(request.POST)
if form.is_valid():
form.save()
else:
print("Invalid input from user") # for debugging only, handle according to your need
form = ProjectForm()
all_items = Project.objects.all()
return render(request, 'project.html', {'form': form, 'all_items':all_items})
In your html
<form action="{% url 'url_name_for_your_project_view' %}" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" value="submit">
</form>
I am implementing search by two fields in form in Django.
I want to keep input data after search.
For example I input "C++" and chose "IT"
then I received Default values
I tried to parse request variable --- e.g. data = request.POST.copy()
but did not achieved result. What is the reason of this problem?
How can I solve this problem?
This is my code:
models.py
class Company(models.Model):
name = models.CharField(max_length=200)
about = models.TextField()
def __str__(self):
return self.name
class Vacancy(models.Model):
company_key = models.ForeignKey(Company, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
salary = models.CharField(max_length=200, default='40.000')
text = models.TextField(default="The text about vacancy")
city = models.CharField(max_length=200, default='Москва')
date_str = models.CharField(max_length=50, default='12 сентября')
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
CHOICES = [
('ALL', 'ALL'),
('IT', 'IT'),
('FINANCE', 'FINANCE'),
('OTHER', 'OTHER'),
]
department = models.CharField(
max_length=20,
choices=CHOICES,
default='ALL',
)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
urls.py
urlpatterns = [
path('', HomePageView.as_view(), name='vacancy_list'),
path('search/', SearchResultsView.as_view(), name='search_results'),
path('vacancy/<int:pk>/', views.vacancy_detail, name='vacancy_detail'),
path('accounts/login/', BBLoginView.as_view(), name='login'),
path('accounts/profile/', profile, name='profile'),
path('accounts/logout/', BBLogoutView.as_view(), name='logout'),
views.py
class HomePageView(ListView):
model = Vacancy
template_name = 'vacancy_list/vacancy_list.html'
paginate_by = 2
page_kwarg = 'vacancy'
context_object_name = 'vacancies'
def vacancy_detail(request, pk):
vacancy = get_object_or_404(Vacancy, pk=pk)
return render(request, 'vacancy_list/vacancy_detail.html', {'vacancy': vacancy})
class SearchResultsView(ListView):
model = Vacancy
template_name = 'vacancy_list/search_results.html'
paginate_by = 2
page_kwarg = 'vacancy'
context_object_name = 'vacancies'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['query'] = self.request.GET.get('q')
# added param
context['query2'] = self.request.GET.get('q2')
return context
def get_queryset(self): # new
query = self.request.GET.get('q')
query2 = self.request.GET.get('q2')
object_list = Vacancy.objects.filter(
Q(title__icontains=query) and Q(department__icontains=query2)
)
return object_list
vacancy_list.html
{% block content %}
<div class="container col-md-8" style="margin:20px;">
<div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;">
<form action="{% url 'search_results' %}" method="get">
<div class="row">
<div class="col-lg-8 col-md-6 col-xs-12">
<input name="q" type="text" placeholder="Search..." class="form-control">
</div>
<div class="col-lg-3 col-md-4 col-xs-12">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
<option>ALL</option>
<option>IT</option>
<option>Finance</option>
<option>Other</option>
</select>
</div>
<div class="col-lg-1 col-md-2 col-xs-12" style="padding-left: 0px;">
<button class="btn btn-primary">Primary</button>
</div>
</div>
</form>
</div>
{% for vacancy in vacancies %}
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-md-8">
<h1>{{vacancy.title}}</h1>
</div>
<div class="col-md-4 text-right">
<p> {{ vacancy.salary}} </p>
</div>
</div>
</div>
....
{% endfor %}
search_result.html
{% extends 'vacancy_list/base.html' %}
{% block content %}
<h1> {{request}}</h1>
<div class="container col-md-8" style="margin:20px;">
<div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;">
<form action="{% url 'search_results' %}" method="get">
<div class="row">
<div class="col-lg-8 col-md-6 col-xs-12">
<input name="q" type="text" placeholder="Search..." class="form-control">
</div>
<div class="col-lg-3 col-md-4 col-xs-12">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
<option>ALL</option>
<option>IT</option>
<option>Finance</option>
<option>Other</option>
</select>
</div>
<div class="col-lg-1 col-md-2 col-xs-12" style="padding-left: 0px;">
<button class="btn btn-primary">Primary</button>
</div>
</div>
</form>
</div>
{% for vacancy in vacancies %}
...
{% endfor %}
{% endblock %}
In your search results template, you should use {{ query }} and {{ query2 }} and a little bit of logic to populate the text and drop-down boxes.
I have used CreateView for a form, but the form is not being submitted even when it is valid. It just redirects to the same page again.I am using the form_id for from fields, and it even submitted once or twice but now it is just not working.
models.py
class Centre(models.Model):
name= models.CharField(max_length=50, blank=False, unique=True)
address = models.CharField(max_length =250)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.")
contact = models.CharField(max_length=100, blank=False)
phone = models.CharField(validators=[phone_regex], max_length=10, blank=True)
views.py
class centre(CreateView):
fields = ('name','address','contact','phone',)
model = Centre
success_url = reverse_lazy("NewApp:logindex")
def form_valid(self, form):
form.save()
return super(centre, self).form_valid(form)
template :
<form method="POST">
{% csrf_token %}
<div class="col col-md-12">
<div class="fieldWrapper" >
{{ form.name.errors }}
<div class="form-group col col-md-3">
<label for="{{form.name.id_for_label}">Centre Name</label>
<input type="text" placeholder="Centre Name" name="name" maxlength="250" id="id_name" style="box-sizing: border-box; width:500px;">
</div>
</div>
<div class="form-group col col-md-3" style="float:right; margin-top=-80px;width=200%">
<label for="{{form.address.id_for_label}" style="margin-left:200px;width:200%;white-space:nowrap;">Centre Address</label>
<input type="text" placeholder="Centre Address" name="address" maxlength="250" id="id_address" style="width:500px; margin-left:200px;">
</div>
</div>
<br> <br><br><br>
<div class="col col-md-12">
<div class="form-group col col-md-3" style="float:right; margin-top=-80px;">
<label for="{{form.contact.id_for_label}" style="margin-left:200px;width:200px;white-space:nowrap;">Contact Person</label>
<input type="text" placeholder="Contact Person" name="address" maxlength="250" id="id_contact" style="width:500px; margin-left:200px;">
</div>
{{ user_form.non_field_errors }}
<div class="fieldWrapper" >
<div class="form-group col col-md-3" >
<label for="{{form.phone.id_for_label}" style="white-space:nowrap;">Contact Number</label>
<input type="text" name="phone" maxlength="10" id="id_phone" placeholder="Contact Number" style="width:500px";>
{{ form.phone.errors }}
</div>
</div>
</div>
<br>
<br>
<div class="col col-md-12" style="padding-left:4.5% ;padding-top:2%">
<input type="submit" value="Save" class="btn btn-primary" style=" height:30px;width:80px;padding-bottom:2em;"></input>
</div>
</form>
You have the wrong name attribute for the contact field, as a result of which it is not being submitted. At the same time, you are not outputting errors for that field.
(Note, you really should use the Django form tags to output the input elements; that would have avoided this situation, as well as pre-populating the fields when the template is redisplayed after validation.)
Problem Description:
I have a django view and template which displays several paragraphs of data, which are retrieved from a Model. Below each one, is a <input type="file"> tag, for uploading images related to each row of data. When user uploads files, he may upload 1 to several files for one particular row of the model, or he may choose not to upload files for one or more models. I need to save these files with a foreign key to that particular row. I am not using django forms for this.
To explain once again, there are several file tags in my html, each below a particular set of text from different rows of a model. At POST, all files become collected into a list within request.FILES, with no clue as to from which input tag each was uploaded. I need to differentiate between files uploaded from different file tags, as these need to be saved to the model, referencing different rows by foreign key. How can I know which input tag a particular file in request.FILES was uploaded from?
My model:
class Procedure(models.Model):
procid = models.AutoField(primary_key=True, unique=True)
timestr = models.DateTimeField(default=timezone.now)
template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, blank=True, null=True)
clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
doctor = models.ForeignKey(doctor, on_delete=models.SET_NULL, blank=True, null=True)
customer = models.ForeignKey(customer, on_delete=models.CASCADE, null=False)
def __str__(self):
return f'{self.template} for {self.customer} on {self.timestr}'
class SectionHeading(models.Model):
procid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=200)
fieldtype_choice = (
('heading1', 'Heading1'),
('heading2', 'Heading2'),
)
fieldtype = models.CharField(
choices=fieldtype_choice, max_length=100, default='heading1')
template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, null=False)
def __str__(self):
return f'{self.name} [{self.procid}]'
class SectionText(models.Model):
procid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=200)
widgettype_choice = (
('textarea', 'Textarea'),
('text', 'Short Text'),
)
widgettype = models.CharField(
choices=widgettype_choice, max_length=100, default='text')
heading = models.ForeignKey(SectionHeading, on_delete=models.CASCADE, null=False)
def __str__(self):
return f'{self.name} [{self.procid}]'
class SectionImage(models.Model):
procid = models.AutoField(primary_key=True, unique=True)
pic = StdImageField(upload_to="data/media/%Y/%m/%d", blank=True, variations={
'large': (600, 400),
'thumbnail': (150, 140, True),
'medium': (300, 200),
})
procedure = models.ForeignKey(Procedure, on_delete=models.CASCADE, null=False)
def __str__(self):
return self.pic.url
My view:
if request.method == 'POST':
print(request.POST, "\n\n")
headinglist = request.POST.getlist('qn[]')
valuelist = request.POST.getlist('ans[]')
for h, v in zip(headinglist, valuelist):
print(h, v)
print(request.FILES)
filelist = request.FILES.getlist('uploaded[]')
for f in filelist:
print(f)
report_pic = SectionImage(pic = f, procedure=proc)
report_pic.save()
print(f'Saved picture to disk: {f}')
msg = "Updated successfully"
My html:
{% for qn, ans in headingparagraph %}
<div class="row mt-4">
<div class="col-md-24">
<div class="form-group">
<label for="exampleFormControlTextarea1">{{ qn.name }}</label>
<input type="hidden" id="custId" name="qn[]" value="{{ qn.procid }}">
<textarea class="form-control reporttextarea" id="" rows="3" name="ans[]">{{ ans }}</textarea>
</div>
</div>
</div>
<div class="row mb-2">
<i class="fas fa-image fa-2x mx-2"></i> Upload Images <input type="file" class="mx-2" id="{{ qn.procid }}_upload" accept="image/*" name="uploaded[]" multiple />
</div>
{% endfor %}
This gets displayed as:
<div class="row mt-4">
<div class="col-md-24">
<div class="form-group">
<label for="exampleFormControlTextarea1">Nasal mucosa</label>
<input type="hidden" id="custId" name="qn[]" value="1">
<textarea class="form-control reporttextarea" id="" rows="3" name="ans[]">Normal nasal mucosa</textarea>
</div>
</div>
</div>
<div class="row mb-2">
<i class="fas fa-image fa-2x mx-2"></i> Upload Images <input type="file" class="mx-2" id="1_upload" accept="image/*" name="uploaded[]" multiple />
</div>
<div class="row mt-4">
<div class="col-md-24">
<div class="form-group">
<label for="exampleFormControlTextarea1">Turbinates</label>
<input type="hidden" id="custId" name="qn[]" value="2">
<textarea class="form-control reporttextarea" id="" rows="3" name="ans[]">Bilateral turbinates normal</textarea>
</div>
</div>
</div>
<div class="row mb-2">
<i class="fas fa-image fa-2x mx-2"></i> Upload Images <input type="file" class="mx-2" id="2_upload" accept="image/*" name="uploaded[]" multiple />
</div>
<div class="row mt-4">
<div class="col-md-24">
<div class="form-group">
<label for="exampleFormControlTextarea1">Middle meatus</label>
<input type="hidden" id="custId" name="qn[]" value="3">
<textarea class="form-control reporttextarea" id="" rows="3" name="ans[]">Bilateral middle meatus normal</textarea>
</div>
</div>
</div>
<div class="row mb-2">
<i class="fas fa-image fa-2x mx-2"></i> Upload Images <input type="file" class="mx-2" id="3_upload" accept="image/*" name="uploaded[]" multiple />
</div>
<div class="row mt-4">
<div class="col-md-24">
<div class="form-group">
<label for="exampleFormControlTextarea1">Inferior Meatus</label>
<input type="hidden" id="custId" name="qn[]" value="4">
<textarea class="form-control reporttextarea" id="" rows="3" name="ans[]">Inferior Meatus normal</textarea>
</div>
</div>
</div>
<div class="row mb-2">
<i class="fas fa-image fa-2x mx-2"></i> Upload Images <input type="file" class="mx-2" id="4_upload" accept="image/*" name="uploaded[]" multiple />
</div>
<div class="row ">
<div class="col-sm-12">
</div>
<div class="col-sm-2">
<button type="submit" class="btn btn-primary btn-block">Save changes</button>
</div>
<div class="col-sm-12">
</div>
</div>
When I upload files for Turbinates and Inferior Meatus, but not for others, output on command line is:
<QueryDict: {'csrfmiddlewaretoken': ['0dEBGstsSSzhOgebI2FBaHWioH7bEBmx0EPnYDE4nTrrNHZYMZCSTyId0FXAJYYR'], 'qn[]': ['1', '2', '3', '4'], 'ans[]': ['Normal nasal mucosa', 'Bilateral turbinates normal', 'Bilateral middle meatus normal', 'Inferior Meatus normal'], 'uploaded[]': ['', '']}>
1 Normal nasal mucosa
2 Bilateral turbinates normal
3 Bilateral middle meatus normal
4 Inferior Meatus normal
<MultiValueDict: {'uploaded[]': [<InMemoryUploadedFile: Screenshot from 2019-01-27 11-32-34.png (image/png)>, <InMemoryUploadedFile: Screenshot from 2019-01-26 16-25-56.png (image/png)>, <InMemoryUploadedFile: Screenshot from 2019-01-26 16-25-18.png (image/png)>, <InMemoryUploadedFile: Screenshot from 2019-01-27 11-32-34.png (image/png)>]}>
Screenshot from 2019-01-27 11-32-34.png
Saved picture to disk: Screenshot from 2019-01-27 11-32-34.png
Screenshot from 2019-01-26 16-25-56.png
Saved picture to disk: Screenshot from 2019-01-26 16-25-56.png
Screenshot from 2019-01-26 16-25-18.png
Saved picture to disk: Screenshot from 2019-01-26 16-25-18.png
Screenshot from 2019-01-27 11-32-34.png
Saved picture to disk: Screenshot from 2019-01-27 11-32-34.png
All the files get into a Querydict collection. I am unable to differentiate which section it belongs to. Is there any way I can tag specific file tags so that when the form is submitted, I can iterate the list and save each file by tagging them to an individual section heading. The database part is easy. I want to know how to build the file tags/html.
First, don't name fields with []. That's a PHP/Rubyism, there's no need for it in Django.
But the way to have different names is to give the inputs those names. The name attribute of the input is what is used as the key in the FILES/POST dictionaries.