简体   繁体   中英

I have created a django ModelForm that is not showing up in my html template, I am trying to determine why that code is not rendering my form?

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.

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)
        ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM