Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

python - Django Pass Input to URL

I want to make a search field in django. I have a database with books and want, that the user can write e.g. "3" in a field and than the URL should look like this: www.url.com/search/3 3 is the id

How can I do that?

btw. I already have this: www.url.com/book/3 but I want, that the user writes it in a input field :)

question from:https://stackoverflow.com/questions/65829875/django-pass-input-to-url

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a simple Search out of a ListView:

# see search results based on user query

class SearchQuestionView(ListView):
    model = Question
    template_name = 'learn/search_results.html'
    context_object_name = 'questions'

    def get_queryset(self):
        query = self.request.GET.get('q', '')
        topic = self.request.GET.get('topic', '')
        object_list = Question.objects.filter(
                Q(question_text__icontains=query))
        if topic:
            object_list = object_list.filter(topic__name__icontains=topic)
        return object_list

You can add additional filters in the same way you added the topic filter.

Then, your form to search this could look like this:

<form action="{% url 'search-results' %}" method="GET">   
     <input name="q" type="text" placeholder="Question Text" aria-label="Search">
     <input name="topic" type="text" placeholder="Topic" aria-label="Search">
     <button type="submit">Search</button>
</form>

This is a cool way to get introduced to the incredibly powerful __ for Django querysets (https://docs.djangoproject.com/en/3.1/ref/models/querysets/).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...