Django form showing up in template as form variable name

Question:

I have created a custom user model in Django and am trying to create a login form. Instead of the form showing up in the Django template, login_form, the name of the variable, shows up.

forms.py

class ProfileLogin(forms.ModelForm):
    password = forms.CharField(label="Password", widget=forms.PasswordInput)

    class Meta:
        model = Profile
        fields = ("username", "password")

    def clean(self):
        username = self.cleaned_data.get('username', None)
        password = self.cleaned_data.get('password', None)
        if not authenticate(username=username, password=password):
            raise forms.ValidationError("Invalid username and/or password.")
        return None

views.py

def login_views(request):
    context = {}
    user = request.user
    if user.is_authenticated:
        return redirect('index')

    if request.POST:
        login_form = ProfileLogin(request.POST)
        if login_form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)

            if user:
                login(request, user)
                return redirect('index')

    else:
        login_form = ProfileLogin()

    context['login_form'] = ['login_form']
    return render(request, "capstone/login.html", context)

html

<form method="post">
        {% csrf_token %}
        {% for field in login_form %}
        <h5>{{ field.label_tag }}
            {{ field }}
            {% if field.help_text %}
                <span>{{ field.help_text }}</span>
            {% endif %}

                {% for error in field.errors %}
                    <p>{{ error }}</p>
                {% endfor %}
            {% if login_form.non_field_errors %} 
                <div>{{ login_form.non_field_errors }}</div>
            {% endif %}
        </h5>
    {% endfor %}
        <button type="submit">Login</button>
      </form>

I tried changing

{% for field in login_form %}
        <h5>{{ field.label_tag }}
            {{ field }}

to {{ login_form }}, but the same thing happens. The name login_form shows up on the webpage instead of the actual form.

Asked By: user19590524

||

Answers:

You need to modify your view to add the form to the context, you currently passing in a single string in a list.

context['login_form'] = ['login_form']

Needs to be:

context['login_form'] = login_form
Answered By: ac2001
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.