The main thing i need to do is extend a model DetailView
page with a specific custom python function. That function need to be called from DetailView
page and return some data, depending on the parameter entered by user into custom form on DetailView
. That data, responded by custom function, i need to display on the same DetailView
page, without database record, when user enter a form field value and press 'submit'. I think to implement that function by custom tag, which is located in /app/templatetags/func.py
#/app/templatetags/func.py
from django import template
register = template.Library()
def get_data(current_version, previous_version, some_data):
return current_version+' works!'
and call it in template, something like that:
<!--templates/detail/article_detail.html-->
{% load func %}
...
{% get_data article_object.value %}
<form action="" method="get">
{{ form }}
<input type="submit" value="Compare">
</form>
...
it works then i trying to specify an argument here in template.
But i cannot understand how to take it from the form. Here is views.py
:
class ArticleDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView):
model = Article
context_object_name = 'article_object'
template_name = 'detail/article_detail.html'
login_url = 'login'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = GetChangelog()
return context
forms.py
class GetChangelog(forms.Form):
diff_version = forms.CharField(label='difference',max_length=10)
Looks like it's impossible to pass a parameter through the url, because of that. Imagine that my article detail view page has an url:
http://blog.com/articles/4 ; when i put some data to the form and press submit
, it becomes http://blog.com/articles/4?diff_ver=4, but i find myself on the same page, while in the urls i have pointed that record:
#urls.py
...
path('articles/<int:pk>?diff_ver=<str:diff_ver>', ArticleDetailView.as_view(), name='article_changelog')
According to my idea when url have changed to http://blog.com/articles/4?diff_ver=4, it must to redirect me into another view with some additional data from my custom function from func.py
, which will recieve diff_ver as an argument. Or may be some another approaches are acceptable here?
UPDATE it can be done easily by context, thank to @dirkgroten:
class ArticleDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView):
model = Article
context_object_name = 'article_object'
template_name = 'detail/article_detail.html'
login_url = 'login'
def get_context_data(self, **kwargs):
context['parameter'] = self.request.GET.get('diff_version')
context = super().get_context_data(**kwargs)
context['form'] = GetChangelog()
return context
and in template:
<!--templates/detail/article_detail.html-->
{% load func %}
...
{% get_data parameter %}
<form action="" method="get">
{{ form }}
{{ parameter }}
<input type="submit" value="Compare">
</form>
...