Home > database >  I have created a django ModelForm that is not showing up in my html template, I am trying to determi
I have created a django ModelForm that is not showing up in my html template, I am trying to determi

Time:01-30

models.py

from django.db import models


# Create your models here.
class Subscriber(models.Model):
    """A subscriber Model"""
    email = models.CharField(max_length=255, blank=False, null=False, help_text="Subscriber Email Address", unique=True)
    full_name = models.CharField(max_length=100, blank=False, null=False, help_text="First and Last Name")

    class Meta:
        verbose_name = "Subscriber"
        verbose_name_plural = "Subscribers"

forms.py

from django.forms import ModelForm
from .models import Subscriber


class SubscriberForm(ModelForm):
    class Meta:
        model = Subscriber
        fields = ["email", "full_name"]

views.py

from django.shortcuts import render
from .forms import SubscriberForm
from django.http import HttpResponseRedirect
from django.contrib import messages


# Create your views here.

def subscriber(request):
    if request.method == "POST":
        subscriber_form = SubscriberForm(request.POST or None)
        if subscriber_form.is_valid():
            subscriber_form.save()
            messages.success(request, "")
            return HttpResponseRedirect("/")
    else:
        subscriber_form = SubscriberForm()
    context = {
        "form_subscriber": subscriber_form
    }
    return render(request, "subscriber/subscriber_form.html", context)

subscriber_form.html

{% block content %}
    <div>
        <form method="POST">
            {% csrf_token %}
            {{ subscriber_form.as_ul }}
            <input type="submit" value="Submit">
        </form>
    </div>
{% endblock %}

Only my submit button is publishing, however the form is never showing up for me. I have followed the django docs exactly and still am not getting any good results.

CodePudding user response:

It should be form_subscriber not subscriber_form so:

{% block content %}
    <div>
        <form method="POST">
            {% csrf_token %}
            {{ form_subscriber.as_ul }}
            <input type="submit" value="Submit">
        </form>
    </div>
{% endblock %}

Additionally, I'd recommend you to only use SubscriberForm(request.POST) in views without using None for GET request as it is already being handled in else condition so:

views.py:

def subscriber(request):
    if request.method == "POST":
        subscriber_form = SubscriberForm(request.POST)
        ...
  • Related