1. Make a form in forms.py
class StockSearchForm(forms.ModelForm):
class Meta:
model = Stock
fields = ['category', 'item_name']
2. Import the form and add it to the view with a condition when to run the form
form = StockSearchForm(request.POST or None)
if request.method == 'POST':
queryset = Stock.objects.filter(category__icontains=form['category'].value(),
item_name__icontains=form['item_name'].value()
)
context = {
"form": form,
"header": header,
"queryset": queryset,
}
3. Add the form to the list_items.html tamplate
<form method='POST' action=''>{% csrf_token %}
{{form|crispy}}
<input type="submit" value='Search'/>
</form>
<br>
If i have in the class Stock the blank category set as False (meaning it is required) it works for both adding an item and searching the item. This is useful for adding as it is required to have a item name and category but it is not useful for searching through the items, can we make it so it works in one window as False(it is required) and True(not required) in other ?
In the forms.py file, you have a form for Data entry and also for Search. You will need to override the file with required false right in the search form.
It can be something like this:
class StockSearchForm(forms.ModelForm):
category = forms.CharField(required=False)
…
class Meta:
model = Stock
fields = [‘category’, ‘item_name’]
I hope that helps
Related Field got invalid lookup: icontains
I am trying to include a search field inside my list items page. It works for some of the module field. If i use a ForeignKey field on Stock Model in the field of category. I face a error which is ” Related Field got invalid lookup: icontains”
How can i solved my problem..
models.py
class Category(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return self.name
class Stock(models.Model):
category = models.ForeignKey(Category,on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=50, blank=True, null=True)
quantity = models.IntegerField(default=’0′, blank=True, null=True)
receive_quantity = models.IntegerField(default=’0′, blank=True, null=True)
receive_by = models.CharField(max_length=50, blank=True, null=True)
issue_quantity = models.IntegerField(default=’0′, blank=True, null=True)
issue_by = models.CharField(max_length=50, blank=True, null=True)
issue_to = models.CharField(max_length=50, blank=True, null=True)
phone_number = models.CharField(max_length=50, blank=True, null=True)
created_by = models.CharField(max_length=50, blank=True, null=True)
reorder_level = models.IntegerField(default=’0′, blank=True, null=True)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
def __str__(self):
return self.item_name
views.py
def list_items(request):
title = ‘List of Items’
form = StockSearchForm(request.POST or None)
queryset = Stock.objects.all()
dict = {‘title’: title ,’form’:form, ‘queryset’:queryset}
if request.method == ‘POST’:
queryset = Stock.objects.filter(category__icontains=form[‘category’].value(),
name__icontains=form[‘name’].value()
)
dict = {‘title’: title,’form’:form, ‘queryset’:queryset}
return render(request, ‘list_items.html’, context=dict)
Hi Delwar, I covered that in this video: https://youtu.be/mtj5bCf3B8o
Let me know. If that helps
Hello arbadjie… You have been a God sent to me with your videos on building apps with Django.. I am writing my school project and building an app using Django and i am following your tutorial to build my project.. I have a slight problem… I was able to setup the search field in my list_item page but when i try searching using the search fields, it does not show my search and it is not displaying any error… What am i missing pls..
The problem is usually on your filters() statement. Check to see if it isn’t missing something.
I still have issues with my codes… the issues are in 3 areas.
1) When i search using my search field, the complete list_items page is displayed.. It does not display the list i searched for in the search field. it displays all the table again
2)when i click on an item to update it, the page shoes templateDoesNotExit and other types of errors.
3) My delete_items icon also takes me to an error page and i have done everything according to your tutorial…
N/B: I use python 3 and Django 3.
I will also like to have your contact.. probably whatsapp cause i will be working on some personal projects using the Django framework soon and i will love to have your expertise every now and then.. If thats ok…
Thanks again
Oscar
I am getting a ValueError : Cannot use None as a query value
How to rectify it
Override the required field in the form definition in forms.py
How can you do that?
I don’t get this.
I used {{form|crispy}}, and “form”: form, in contex in the views.py, but form search still doesn’t appear on the page. What should i add on the syntax?
Check if you have the another context outside the if condition
esxcuse me, this issue was solved? because i have the same problem in computer inventory project, Regards.
in inventory project i solve rewriting code, from video 19 to video 20, i think the interpreter have a problem, because, write exacly the same code.
Thanks for contributing
Am not sure which issue you mean
My code in list_items.html error is
Invalid filter :crispy
{{form|crispy}} error in line not work
Please help us.
What is the error please?
My code in error in filer list_items
{{form|crispy}}
Line in error
Can you please explain further? I don’t understand
Hi Abdur rehman your videos are really great and helpful, recently followed and got what i needed.
I am getting an error that “TemplateSyntaxError at /list_items/” Invalid filter: ‘crispy’.
Can you help me what is the issue?
Am Happy that you solved this
Hi its sorted out, i didnt include {% load crispy_forms_tags %} therefore error was coming.. anyway thanks 🙂
Nice job
Thanks Saad, was searching for this
context = {
“title”: title,
“queryset”: queryset,
}
if request.method == ‘POST’:
queryset = Stock.objects.filter(category__icontains=form[‘category’].value(), …
item_name__icontains=form[‘item_name’].value()
)
if form[‘export_to_CSV’].value() == True:
response = HttpResponse(content_type=’text/csv’)
â–¶ Local vars
the error is value error
plzz help me
django.template.exceptions.TemplateSyntaxError: Invalid filter: ‘crispy’
erorr invaild filter crispy
It is asking to fill both the blanks that is category, Item name to search
Use in models.py, set blank=True, null=True for category and item name then use form validation to validate data while inputing
Can use None as a query value
I think due to Django version some errors are raising
Sure, that can be an issue