我创建了一个django ModelForm,它没有显示在我的html模板中,我正在尝试确定为什么代码没有呈现我的表单?

kb5ga3dv  于 2023-02-06  发布在  Go
关注(0)|答案(1)|浏览(130)

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 %}

只有我的提交按钮在发布,但是表单从来没有出现在我面前。我已经完全按照django的文档做了,但是仍然没有得到任何好的结果。

xurqigkl

xurqigkl1#

它应该是form_subscriber而不是subscriber_form,因此:

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

此外,我建议您只在视图中使用SubscriberForm(request.POST),而不要为GET请求使用None,因为它已经在else条件下处理了,因此:
views.py:

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

相关问题