M
M
MalekBV2019-09-10 21:57:16
Django
MalekBV, 2019-09-10 21:57:16

Django redirect with filter?

Got into a stupor. If you write /tag/id_tag ​​on the site, then you are redirected to a template where it says "All results with the tag
#tagname"
urls.py

path('tag/<int:id>', views.tag_detail, name = "tag_detail_url")

Models.py
class Anime(models.Model):
#code
tags = models.ManyToManyField('Tag', related_name='animes', blank = True)

class Tag(models.model):
name = models.CharField("Тэг", max_length = 30)

def get_absolute_url(self):
    return reverse('animeapp:tag_detail_url', kwargs = {'id': self.id})

Views.py
def tag_detail(request, id):
    tag = Tag.objects.get(id = id)
    return render(request, 'animeapp/tag_detail.html', {'tag': tag})

SAMPLE:
<form action="{% url 'animeapp:index' %}" class="form-filter">

          <p class="filter-p"><small class="filter-p">Жанры</small></p>
          <select name="filter_tags" class="home-p" id="filter_tags">
            {% for a in anime %}
              {% for tag in a.tags.all %}
                <option value="{{tag.name}}" class="home-p">{{tag.name}}</option>
              {% endfor %}
            {% endfor %}
          </select>

          <button class="btn btn-primary btn-tag mt-4" type="submit">Найти</button>
        </form>

It is necessary that when you click on the button, tags are shown, but already with a filter. As I understand it, you need to redirect to the url /tag/tag_id with a suitable tag. Please explain in detail, I'm dumb. Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
szelga, 2019-09-11
@szelga

firstly, in select, you option valueshould {{tag.name}}substitute tag.id.
secondly, the form attribute actionpoints to the URL to which its content should be sent after submit.
thirdly, it will send the content of the form not in the form you intended. Forms have a GET method by default, so it will redirect to a URL like http://сайт/урл/?filter_tags=значение.
if you do not want to touch tag_detail, then you will have to intercept the button click through JavaScript, and manually redirect to the desired URL.
or make a new View that will only accept request, parse values ​​fromrequest.GETand then issue or not issue a result (error handling will be required, in case the input is not an integer, or the tag with the required id is not found). then at the form in actionit will be necessary to expose it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question