Fabian
Fabian

Reputation: 95

Show file link in template

In my Django project I have a folder called bills. I save every bill, which I create in my django project, in this folder. The filename is something like this: HK_Smith_2014.pdf Is it possible, to browse in this folder, search for Smith (in the background) and display a link of this file in my template. It should be possible, to click on this link, and the file is opened.

Upvotes: 2

Views: 535

Answers (1)

MBrizzle
MBrizzle

Reputation: 1813

If you are saving the file as a FileField in your model, you should be able to access it in your template like this:

<a href="{{ my_bill.url }}">{{ my_bill.name }}</a>

For the search function, however, you need to do a little more work. You'd have to make a form that takes the input of the specific bills, and then use that information to search through your model for the particular bill. One way to do this would be as follows:

class SearchForm(forms.Form):
    search_term = forms.CharField()

def search(request):
    form = SearchForm(request.POST)
    if form.is_valid():
        term = form.cleaned_data['search_term'].lower()
        for obj in Bill.objects.all():
            if term in obj.name.lower():
                 return HttpResponseRedirect(reverse('search:results', args=(obj.id,)))
    else:
        form = SearchForm()

    return render(request, 'search/search.html', {'form':form})

Of course, you'd have to have a results view that takes the bill_id as an argument, and a search.html template to match. There are plenty of ways you could expand on this as well (such as returning an error if you can't find an instance of the search term in any of your objects). But this is a skeleton of a solution.

Upvotes: 1

Related Questions