开发者

Auto populate DateTimeField not working in django forms

I am getting below error when I use auto_now_add in my Model Form.

TypeError: __init__() got an unexpected keyword argument 'auto_now_add'

Here is my model field

modified = models.DateTimeField(blank = True)

Declaration in form. I have seen in one of the posts DateTimeField Not Working to add initial = datetime.datetime.now for auto populating

import datetime

modified = forms.DateTimeField(initial = datetime.datetime.now) - When I use this no error is coming but datetime was not auto populating.

I have used the same in self.fields['modified'] - Still no use

Any of the above statements were not working. Some one help me on this.


I am pasting all my model class and Model 开发者_如何学运维Form here Model Class

class Users(models.Model):
  name = models.CharField(max_length = 100)
  role = models.ForeignKey(RolesConfig, db_column = 'role')
  level = models.ForeignKey(LevelConfig, db_column = 'level')
  team_name = models.ForeignKey(TeamNamesConfig, db_column = 'team_name')
  location = models.ForeignKey(LocationConfig, db_column = 'location')
  modified = models.DateTimeField(blank = True)
  class Meta:
     db_table = u'users'
     def __str__(self):
            return "%s" % (self.ldap)
     def __unicode__(self):
         return u'%s' % (self.ldap)

I have modified the field in phpmyadmin

Auto populate DateTimeField not working in django forms

This is my ModelForm

class TargetForm(forms.ModelForm):
    modified = forms DateTimeField(initial = datetime.datetime.now)
    def __init__(self, *args, **kwargs):
       super(MMPodTargetForm, self).__init__(*args, **kwargs)    
       self.fields['modified'] = forms.DateTimeField(initial = datetime.datetime.now)
    class Meta:
       model = models.Users

I need to get current date and time autopopulated in the form, when the form loads. Tell me whats wrong in my code.


I think the error is because you're adding the auto_now_add extra argument to your form instead of to your mode. Try changing your model to the following to see if that fixes the problem (untested):

class Users(models.Model):
  name = models.CharField(max_length = 100)
  role = models.ForeignKey(RolesConfig, db_column = 'role')
  level = models.ForeignKey(LevelConfig, db_column = 'level')
  team_name = models.ForeignKey(TeamNamesConfig, db_column = 'team_name')
  location = models.ForeignKey(LocationConfig, db_column = 'location')
  modified = models.DateTimeField(auto_now = True)
  class Meta:
     db_table = u'users'
     def __str__(self):
            return "%s" % (self.ldap)
     def __unicode__(self):
     return u'%s' % (self.ldap)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜