简体   繁体   English

Django模型CreateView不会在HTML中呈现表单字段

[英]Django model CreateView does not render form fields in HTML

I am trying to setup a class based 'CreateView' for a model in my django site, but when the create html page renders, the model fields are not rendered. 我正在尝试在django站点中为模型设置基于类的'CreateView',但是当create html页面呈现时,不会呈现model字段。 Only the submit button shows up on the web page. 网页上仅显示提交按钮。 However, when debugging, I overrided the 'form_invalid' method in the class view, and the form object had the required HTML for all fields stored in the object. 但是,在调试时,我在类视图中覆盖了“ form_invalid”方法,并且该表单对象具有该对象中存储的所有字段所需的HTML。 If I take this HTML and manually add it to the HTML of the create page in the browser I can fill out the fields and post the data to the database. 如果使用此HTML并将其手动添加到浏览器中的create page的HTML中,则可以填写字段并将数据发布到数据库中。

At this point I have not found an obvious answer as to why the form fields are not rendered so any help on this would be greatly appreciated. 在这一点上,我还没有找到关于为什么不呈现表单字段的明显答案,因此,对此将有所帮助。

environment used: python 3.7.3, django 2.2.3 使用的环境:python 3.7.3,django 2.2.3


Solution: 解:

This issue was fixed by changing the form name in the view context data. 通过更改视图上下文数据中的表单名称,已解决此问题。

In views.py: 在views.py中:


def get_context_data(self, *args, **kwargs):
        context = super(CreateAlertView, self).get_context_data(**kwargs)
        context["alert_form"]=context["form"]
        return context

Or... In the HTML template change 'alert_form' to 'form' to match the default context. 或者...在HTML模板中,将“ alert_form”更改为“ form”以匹配默认上下文。


models.py: models.py:

class Alert(models.Model):
    RAIN = 'Rain'
    SNOW = 'Snow'
    COLD = 'Cold'
    HEAT = 'Heat'
    WEATHER_CHOICES = [
        (RAIN, 'Rain'),
        (SNOW, 'Snow'),
        (COLD, 'Cold'),
        (HEAT, 'Heat'),
    ]

    DAILY = 'Daily'
    WEEKLY = 'Weekly'
    INTERVAL_CHOICES = [
        (DAILY, 'Daily'),
        (WEEKLY, 'Weekly'),
    ]

    weather_type = models.CharField(max_length=15, choices=WEATHER_CHOICES, default=RAIN)
    interval = models.CharField(max_length=10, choices=INTERVAL_CHOICES, default=DAILY)
    search_length = models.IntegerField(default=1)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    active = models.BooleanField(default=False)

views.py: views.py:

class CreateAlertView(LoginRequiredMixin, CreateView):
    template_name = 'users/alert_form.html'
    #model = Alert
    form_class = AlertModelForm
    success_url = 'users/profile/'

    def form_valid(self, form):

        print('validation')
        form.instance.user = self.request.user
        return super().form_valid(form)

    def form_invalid(self, form):
        print(form) # check form HTML here
        return super().form_invalid(form)

forms.py: forms.py:

class AlertModelForm(ModelForm):

    class Meta:
        model = Alert
        exclude = ['user']

urls.py: urls.py:

urlpatterns = [
    path('alert/create/', CreateAlertView.as_view(), name='alert'),
]

html template: html模板:

<h1>create an alert</h1>
<form method="post">
    {% csrf_token %}
    {{ alert_form.as_p }}
    {{ alert_form.non_field_errors }}
    {{ field.errors }}
    <button type="submit">Save changes</button>
</form>

Create page as rendered: 创建呈现的页面:

创建呈现的页面

Create page with manually modified HTML: 使用手动修改的HTML创建页面: 使用手动修改的HTML创建页面

The context name for the form set by the CreateView (FormMixin) is "form", your template is referencing "alert_form" 由CreateView(FormMixin)设置的表单的上下文名称为“ form”,您的模板引用了“ alert_form”

Here is a helpful website for seeing all options available in the class based views 是一个有用的网站,用于查看基于类的视图中的所有可用选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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