Overlapping two ImageField in a Django form - python

I’m trying to edit a user’s profile in django but when editing the banner image and the profile pictura overlap. I mean, I put a different image on each one, but when I save the form, I get the same image.
When a profile is created both are set by default as it comes in models.py.
views.py
#login_required
def EditProfile(request):
user = request.user.id
profile = Profile.objects.get(user__id=user)
user_basic_info = User.objects.get(id=user)
if request.method == 'POST':
form = EditProfileForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
user_basic_info.first_name = form.cleaned_data.get('first_name')
user_basic_info.last_name = form.cleaned_data.get('last_name')
profile.picture = form.cleaned_data.get('picture')
profile.banner = form.cleaned_data.get('banner')
profile.location = form.cleaned_data.get('location')
profile.url = form.cleaned_data.get('url')
profile.birthday = form.cleaned_data.get('birthday')
profile.bio = form.cleaned_data.get('bio')
profile.save()
user_basic_info.save()
return redirect('users:profile', username=request.user.username)
else:
form = EditProfileForm(instance=profile)
context = {
'form':form,
}
return render(request, 'users/edit.html', context)
forms.py
class EditProfileForm(forms.ModelForm):
first_name=forms.CharField(
widget=forms.TextInput(attrs={
'class': 'shadow-sm focus:ring-indigo-500 dark:bg-dark-third dark:text-dark-txt focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md',
})
)
last_name=forms.CharField(
widget=forms.TextInput(attrs={
'class': 'shadow-sm focus:ring-indigo-500 dark:bg-dark-third dark:text-dark-txt focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md',
})
)
picture = forms.ImageField(label='Profile Picture', required=False, widget=forms.FileInput)
banner = forms.ImageField(label='Banner Picture', required=False, widget=forms.FileInput)
location = forms.CharField(widget=forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md'}), max_length=25, required=False)
url = forms.URLField(label='Website URL', widget=forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md'}), max_length=60, required=False)
bio = forms.CharField(widget=forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md'}), max_length=260, required=False)
birthday = forms.DateField(widget= forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md'}), required=False)
class Meta:
model = Profile
fields = ('first_name','last_name','picture','banner','location','url','bio','birthday')
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
picture = models.ImageField(default='users/user_default_profile.png', upload_to=user_directory_path_profile)
banner = models.ImageField(default='users/user_default_bg.jpg', upload_to=user_directory_path_banner)
verified = models.CharField(max_length=10, choices=VERIFICATION_OPTIONS, default='unverified')
followers=models.ManyToManyField(User, blank=True, related_name="followers")
date_created = models.DateField(auto_now_add=True)
location=models.CharField(max_length=50, null=True, blank=True)
url=models.CharField(max_length=80, null=True, blank=True)
birthday=models.DateField(null=True, blank=True)
bio = models.TextField(max_length=150, null=True, blank=True)
def __str__(self):
return self.user.username
edit.html
<form class="form-horizontal dark:text-dark-txt" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="mt-1 sm:mt-0 sm:col-span-2">
<img class="h-28 w-full bg-cover" src="{{user.profile.banner.url}}" alt="{{profile.user.username}} Banner Picture">
<div class="max-w-lg flex justify-center px-6 pt-5 pb-6 border-2 dark:border-dark-third border-gray-300 border-dashed rounded-md">
{{form.banner}}
<div class="space-y-1 text-center">
<div class="flex text-sm text-gray-600">
</div>
</div>
</div>
<!--Profile Picture-->
<div class="mt-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:items-center sm:border-t dark:border-dark-third border-gray-200 sm:pt-5">
<label for="photo" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Photo
</label>
<div class="mt-1 sm:mt-0 sm:col-span-2">
<div class="flex items-center">
<span class="mr-4 h-18 w-18 rounded-full overflow-hidden dark:bg-dark-third bg-gray-100">
<img src="{{user.profile.picture.url}}" alt="">
</span>
{{form.picture}}
</div>
</div>
</div>
<div class="mt-4">
<label for="first name" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
First Name
</label>
{{form.first_name}}
</div>
<label for="last name" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Last Name
</label>
{{form.last_name}}
<label for="bio" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Bio
</label>
{{form.bio}}
<label for="city" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Location: City, Country
</label>
{{form.location}}
<label for="birthday" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Date of Birth: yyyy-mm-dd
</label>
{{form.birthday}}
<label for="url" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Website URL
</label>
{{form.url}}
</div>
<div class="control-group">
<div class="controls">
<a href="{% url 'users:profile' username=user.username %}" class="mt-4 inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded dark:text-dark-txt text-indigo-700 dark:bg-dark-second bg-indigo-100 dark:hover:bg-dark-third hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-dark-third focus:ring-indigo-500">
Return to Profile </a>
<button type="submit" class="mt-4 inline-flex float-right items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded dark:text-dark-txt text-indigo-700 dark:bg-dark-third bg-indigo-100 dark:hover:bg-dark-third hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-dark-third focus:ring-indigo-500">
Update</button>
</div>
</div>
</div>
</form>

Related

Django Autocomplete Light not working with Bootstrap 5 Modal

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.
...

Django filters date range filter is not working

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>

Can't get form data from site to save in database Django MySQL

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>

Keep data in the form after submit

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.

Django: Search stopped working in 1.10

I've been working on an application I originally started in Django 1.7, then ported it over to 1.10, where it stopped working. It will work if I select a District to search by, but only by the District. What I'm hoping is that if all the search terms are left blank, it will return all objects in that pool. It would be great if anyone had some ideas on where this is going wrong, as it doesn't give me errors, just tells me there are no results.
Model:
class PlantingSite(models.Model):
id_planting_site = models.IntegerField(null=True, blank=True)
empty = models.BooleanField(default=False)
address = models.CharField(max_length=256, null=True, blank=True)
street = models.CharField(max_length=256, null=True, blank=True)
coord_lat = models.CharField(max_length=256, null=True, blank=True)
coord_long = models.CharField(max_length=256, null=True, blank=True)
zipcode = models.CharField(max_length=256, null=True, blank=True)
neighborhood = models.ForeignKey(Neighborhood, null=True)
district = models.ForeignKey(District, null=True)
property_address = models.CharField(max_length=256, null=True, blank=True)
property_street = models.CharField(max_length=256, null=True, blank=True)
property_zipcode = models.CharField(max_length=256, null=True, blank=True)
property_owner = models.ForeignKey(Contact, related_name='planting_sites_owned_by_contact', null=True)
contact = models.ForeignKey(Contact, related_name='planting_sites_cared_for_by_contact', null=True)
notes = models.TextField(null=True, blank=True)
basin_type = models.ForeignKey(BasinType, related_name='planting_sites_with_basin_type', null=True)
overhead_utility = models.ManyToManyField(OverheadUtility, related_name='planting_sites_with_overhead_utility', blank=True)
hardscape_damage = models.ManyToManyField(HardscapeDamage, related_name='planting_sites_with_hardscape_damage', blank=True)
aspect = models.ForeignKey(Aspect, null=True)
sequence = models.IntegerField(null=True, blank=True)
side = models.CharField(max_length=256, null=True, blank=True)
size = models.CharField(max_length=256, null=True, blank=True)
created_by = models.ForeignKey(User, related_name='planting_sites_created', null=True)
created_at = models.DateTimeField(default=timezone.now)
last_edited = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return unicode(self.id_planting_site)
class Meta:
ordering = ['-created_at']
My View:
def uf_search(request):
if request.POST:
search_sent = True
# SEARCH PLANTING SITES
if request.POST.get('search_type_id') == "1":
planting_site_search = True
if request.POST.get('address_range'):
if request.POST.get('address_start') and request.POST.get('address_end'):
address_start = request.POST.get('address_start')
address_end = request.POST.get('address_end')
r_address = Q(address__range=[address_start, address_end])
else:
r_address = Q(address__isnull=False) | Q(address__isnull=True)
elif request.POST.get('address_exact'):
if request.POST.get('address'):
address = request.POST.get('address')
r_address = Q(address__icontains=address)
else:
r_address = Q(address__isnull=False) | Q(address__isnull=True)
planting_site_fields = {
'street': request.POST.get('street'),
'zipcode': request.POST.get('zipcode'),
}
r_objects = Q()
if request.POST.get('neighborhood_id'):
r_neighborhood = Q(neighborhood__id_neighborhood=request.POST.get('neighborhood_id'))
else:
r_neighborhood = Q(neighborhood__id_neighborhood__isnull=False) | Q(neighborhood__id_neighborhood__isnull=True)
if request.POST.get('district_id'):
r_district = Q(district__id_district=request.POST.get('district_id'))
else:
r_district = Q(district__id_district=False) | Q(district__id_district=True)
for field, value in planting_site_fields.iteritems():
if value:
r_objects = Q(**{field+'__icontains': value})
if request.POST.get('empty_planting_sites'):
search_results = PlantingSite.objects.values('id', 'id_planting_site', 'address', 'street', 'zipcode', 'neighborhood__name', 'district__name', 'empty').filter(r_address, r_objects, r_neighborhood, r_district, empty=True)
else:
search_results = PlantingSite.objects.values('id', 'id_planting_site', 'address', 'street', 'zipcode', 'neighborhood__name', 'district__name', 'empty').filter(r_address, r_objects, r_neighborhood, r_district)
request.session['search_results'] = list(search_results)
neighborhood_list = Neighborhood.objects.all()
district_list = District.objects.all()
species_list = Species.objects.all()
condition_list = TreeCondition.objects.all()
args = {'search_sent': search_sent, 'planting_site_search': planting_site_search, 'search_results': search_results, 'neighborhood_list': neighborhood_list,
'district_list': district_list, 'species_list': species_list, 'condition_list': condition_list}
args.update(csrf(request))
return render(request, 'uf_search.html', args)
Template:
<form action="/forest/search/" method="post">
{% csrf_token %}
<input type="hidden" name="search_type_id" id="search_type_id" value="1">
<p>
<div class="row">
<div class="col-sm-4">
Address:
</div>
<div class="col-sm-4">
Exact: <input type="checkbox" name="address_exact" id="address_exact" />
</div>
<div class="col-sm-4">
Range: <input type="checkbox" name="address_range" id="address_range" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Range:
</div>
<div class="col-sm-8">
<input type="text" id="address_start" name="address_start" /> to <input type="text" id="address_end" name="address_end" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Exact:
</div>
<div class="col-sm-8">
<input type="text" id="address" name="address" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Street:
</div>
<div class="col-sm-8">
<input type="text" id="street" name="street" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Zipcode:
</div>
<div class="col-sm-8">
<input type="text" id="zipcode" name="zipcode" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Neighborhood:
</div>
<div class="col-sm-8">
<select name="neighborhood_id" id="neighborhood_id">
<option value="">Select:</option>
{% for neighborhood in neighborhood_list %}
<option value="{{neighborhood.id_neighborhood}}">{{neighborhood.name}}</option>
{% endfor %}
</select>
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
District:
</div>
<div class="col-sm-8">
<select name="district_id" id="district_id">
<option value="">Select:</option>
{% for district in district_list %}
<option value="{{district.id_district}}">{{district.name}}</option>
{% endfor %}
</select>
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
</div>
<div class="col-sm-8">
<input type="checkbox" name="empty_planting_sites" id="empty_planting_sites">
Show Empty Planting Sites Only
</div>
</div>
</p>
<input type="submit" name="submit" id="submit" value="Search" />
</form>
Any ideas? Is it something that was dropped in the newest version?

Categories

Resources