【问题标题】:Change DateTImeField to hidden in django在 django 中将 DateTImeField 更改为隐藏
【发布时间】:2015-05-18 02:14:07
【问题描述】:

我有一个包含三个字段的 django 表单。其中两个需要由用户输入并存储在我的数据库中。 DateTimeField 是自动生成的。当我在主页中显示表单时,所有字段都在那里,如何隐藏 DateTimeField? Here is a link with different approaches, but I did not help me.

这是我的代码:

models.py

from django.db import models
from datetime import datetime
# Create your models here.
class Post(models.Model):
    title = models.CharField(max_length = 100)
    body = models.TextField()
    dateCreated = models.DateTimeField(default=datetime.now, blank=True, )

    def __str__(self):
        return self.title

forms.py

from django import forms
from .models import Post #this is the name of the model
class PostForm(forms.ModelForm):
    class Meta:
        model = Post

models.py

class Post(models.Model):
    title = models.CharField(max_length = 100)
    body = models.TextField()
    dateCreated = models.DateTimeField(default=datetime.now, blank=True, )

    def __str__(self):
        return self.title

HTML 代码

<form method="POST" action=""> {% csrf_token %}
{{form.as_p}}

<input type='submit' value='Join' class = 'btn'>
</form>

【问题讨论】:

    标签: python html django forms


    【解决方案1】:

    Just set a value for the forms exclude attribute:

    class PostForm(forms.ModelForm):
        class Meta:
            model = Post
            exclude = ['dateCreated']
    

    【讨论】:

      【解决方案2】:

      您根本不需要在表单中显示dateCreated 字段。这是内部数据,不应向用户公开:

      class PostForm(forms.ModelForm):
          class Meta:
              model = Post
              fields = ('title', 'body', )
      

      【讨论】:

        猜你喜欢
        • 2013-10-02
        • 1970-01-01
        • 2014-07-16
        • 1970-01-01
        • 1970-01-01
        • 2021-09-05
        • 2011-10-15
        • 2021-07-06
        • 1970-01-01
        相关资源
        最近更新 更多