0

I have a django form with three fields. Two of them need to be enter by the user and store within my database. DateTimeField is generated automatically. When I display the form in my main page all the fields are there, How can keep DateTimeField hidden? Here is a link with different approaches, but I did not help me.

Here is my code:

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 Code

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

<input type='submit' value='Join' class = 'btn'>
</form>
Community
  • 1
  • 1
Alexander
  • 599
  • 2
  • 14
  • 25

2 Answers2

2

Just set a value for the forms exclude attribute:

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

You don't need to show the dateCreated field in the form at all. This is an internal data and shouldn't be exposed to the user:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'body', )
catavaran
  • 44,703
  • 8
  • 98
  • 85