Alexander
Alexander

Reputation: 727

Change DateTImeField to hidden in django

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>

Upvotes: 0

Views: 1137

Answers (2)

user764357
user764357

Reputation:

Just set a value for the forms exclude attribute:

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

Upvotes: 2

catavaran
catavaran

Reputation: 45565

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', )

Upvotes: 1

Related Questions