Answer the question
In order to leave comments, you need to log in
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")
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})
def tag_detail(request, id):
tag = Tag.objects.get(id = id)
return render(request, 'animeapp/tag_detail.html', {'tag': tag})
<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>
Answer the question
In order to leave comments, you need to log in
firstly, in select, you option value
should {{tag.name}}
substitute tag.id
.
secondly, the form attribute action
points 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.GET
and 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 action
it will be necessary to expose it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question