[Django]-Django adding a feedback form on every page

11๐Ÿ‘

โœ…

Iโ€™d create a context processor, to include the form in every view.

EDIT:

To get the user to the previous URL he/she was browsing, you can use just URLs.

# yourapp/context_processors.py
def feedback_form_context_processor(request):
    return {
        'feedback_form': FeedbackForm(),
        'feedback_form_url': reverse("feed_app:form_process", args=(request.path))
    }

This is how urls.py could look like:

urlpatterns = patterns('feed_app.views',
    url(r'^process-feedback-form/(?P<next_url>\d+)', 'form_process', name='form_process'),
)

And the view for the form:

def form_process(request, next_url):
    # Process form, do your stuff here
    # if its valid redirect to the url
    return redirect(next_url)

And you should structure your templates to have the correct layout. For example, having a base template:

# templates/base.html
<html>
<body>
..
{% block maincontent %}
{% endblock %}
..
{# The form!!! #}
<form action='{{feedback_form_url}}' method='POST'>
@csrftoken
{{ feedback_form.as_p }}
</form>

</body>
</html>

To create a simple view just use the correct template.

# templates/just_a_random_view.html

{% extends base.html %}

{% block maincontent %}
<h1>Content!</h1>
{% endblock %}

Finally, include it in your settings:

# settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    ...
    "yourapp.context_processors.feedback_form_context_processor"
)
๐Ÿ‘คsantiagobasulto

4๐Ÿ‘

I believe that easiest way to include form would be to use a assignment_tag:

In template library:

@register.assignment_tag
def feedback_form(format_string):
    return FeedbackForm()

In template

{% feedback_form as form %}
{# display form... %}
{{ form.as_pย }}
๐Ÿ‘คbmihelac

0๐Ÿ‘

To add on to @bmihelac, whoโ€™s answer worked really well for me. Since django 2.0 assignment_tag is deprecated in favor of simple_tag. So you can pretty much follow his answer exactly by replacing assignment_tag with simple_tag, like so:

from django import template

from .forms import FeedbackForm

register = template.Library()


@register.simple_tag
def feedback_form():
    return FeedbackForm()

And then just refer to https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/#code-layout for info about how to import it into the template!

๐Ÿ‘คnmu

Leave a comment