djangodjango-templatesdjango-widget-tweaks

Django: how to get username in template using django-tweaks


I have rendered a html form with widget_tweaks and i want the default value of the field to be the current username.

  #template
  {% if user.is_authenticated %}
  <form method="post">
  {% render_field form.title value="{{ request.user }}" readonly="True" %}
  </form>
  {% else %}
  <h 1>Login First</h 1>
  {% endif %}

but this render the exact text "{{ request.user }}" rather than printing the username. If I use the

tag and use the {{ request.user }}, prints the current username.

This is how my views.py looks:

views.py

class CreatePostView(CreateView):
template_name = 'posts/new_post.html'
redirect_field_name = 'posts/post_detail.html'
form_class = PostForm
model = Post
def get_absolute_url(self):
    return reverse('posts:post_detail', args = [self.id])

Solution

  • In django templatetags, you do not need double accolades {{ }}. Try the following:

    <!-- Your template -->
    [...]
    {% render_field form.title value=request.user readonly="True" %}
    [...]
    

    I just removed the double accolades.