将DateTImeField更改为隐藏在django中

时间:2015-03-16 02:32:19

标签: python html django forms

我有一个带三个字段的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>

2 个答案:

答案 0 :(得分:2)

Just set a value for the forms exclude attribute

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

答案 1 :(得分:1)

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

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