Home > Mobile >  How do I display my form in a Django template?
How do I display my form in a Django template?

Time:09-10

I am trying to display my stat update form in my Django template, however it isn't displaying. My stats below show up correctly, just not the form.

{{ stats.user }} | {{ stats.weight }} | {{ stats.date }}

Template:

{% block content %}
<div >
    <div >
        <div >
            <h1>My Health</h1>
        </div>
    </div>
</div>
<div >
    <div >
        <form method="post" style="margin-top: 1.3em;">
            {{ update_form }}
            {% csrf_token %}
            <button type="submit" >Submit</button>
        </form>
    </div>
    <div >
        <div >
            <p > {{ stats.user }} | {{ stats.weight }} | {{ stats.date }} </p>
        </div>
    </div>
</div>
{% endblock content %}

forms.py:

class StatUpdateForm(forms.Form):
    class Meta:
        model = Stats
        fields = ('user', 'weight', 'date')

models.py:


class Stats(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField(auto_now=True)
    weight = models.DecimalField(max_digits=5, decimal_places=2)

    class Meta:
        db_table = 'health_stats'
        ordering = ['-date']

    def __str__(self):
        return f"You currently weigh {self.weight}, {self.user}"

views.py:

from django.shortcuts import render
from .models import Stats
from .forms import StatUpdateForm
from django.views import generic, View
from django.shortcuts import get_object_or_404
# from django.contrib.auth import authenticate
# from django.core.exceptions import ValidationError
# from .forms import RegistrationForm, LoginForm


def home(request):
    return render(request, 'home.html')


class MyHealth(View):
    
    def get(self, request, *args, **kwargs):

        stats = Stats
             
        context = {
            'stats': stats,
            "update_form": StatUpdateForm(),
            'user': stats.user,
            'weight': stats.weight,
            'date': stats.date,
        }
        return render(request, 'MyHealth.html', context)

I've tried redefining the form in my views.py, but I'm unsure why it isn't pulling through, as the other parts of the context are.

Any help would be appreciated!

CodePudding user response:

I assume the form fields are rendering and the fields just aren't loaded with the correct values.
do this: StatUpdateForm(instance=stats) to make it an edit form

CodePudding user response:

In the form, since you are using a model, you must extend from forms.ModelForm instead forms.Form, try to change that line in the forms.py

class StatUpdateForm(forms.ModelForm):  # extends from forms.ModelForm
    class Meta:
        model = Stats
        fields = ('user', 'weight', 'date')
  • Related