如何在Django Forms中自动添加实际日期?

时间:2015-08-28 00:45:58

标签: python django date time django-forms

我是Django的新手,我正在尝试为我的应用创建一个添加图书的表单。但我希望发布日期不包含在表格中。相反,我希望获得当前的系统日期,并且"添加"保存模型的表格。我怎么能这样做?

部分 views.py

def add_book(request):
if request.method == 'POST':
    form = BookForm(request.POST)
    if form.is_valid():
        new_book = form.save(commit=False)
        new_book.publication_date = django_timezone
        new_book.save()
        return HttpResponseRedirect('/thanks/')
    else:
        print form.errors
else:
    form = BookForm()
return render_to_response('add_book.html',{'form':form})

我的 forms.py

class BookForm(ModelForm):
    class Meta:
        model = Book
        exclude = ('publication_date',)

我的模特预订

class Book(models.Model):
    title = models.CharField(max_length = 100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()
    num_pages = models.IntegerField(blank = True, null = True)

    class Admin:
        list_display = ('title', 'publisher', 'publication_date')
        list_filter = ('publisher', 'publication_date')
        ordering = ('-publication_date',)
        search_fields = ('title',)
    def __str__(self):
        return self.title

我将此模板用于表单:



{% extends 'base.html' %}
  {% block title %}Add a new Book{% endblock %}
  {% block content %}
    <h3> Here you can add a new book into the local DataBase </h3>
    <form action="." method="post">{% csrf_token %}>
      <div class="fieldWrapper">
        {{ form.title.errors }}
        <label for="id_title">Book Title</label>
        {{ form.title }}
      </div>
      <div class="fieldWrapper">
        {{ form.authors.errors }}
        <label for="id_authors">Authores</label>
        {{ form.authors }}
      </div>
      <div class="fieldWrapper">
        {{ form.publisher.errors }}
        <label for="id_publisher">Publishers</label>
        {{ form.publisher }}
      </div>
      <div class="fieldWrapper">
        {{ form.num_pages.errors }}
        <label for="id_num_pages">Number of Pages</label>
        {{ form.num_pages }}
      </div>


      <p><input type="submit" value="Submit"></p>
    </form>
  {% endblock %}
&#13;
&#13;
&#13;

我暂时禁用了Django csrf因为我不需要我的目的

1 个答案:

答案 0 :(得分:0)

为此,您需要在default模型字段中将timezone.now参数作为publication_date传递。

<强> models.py

class Book(models.Model):
    title = models.CharField(max_length = 100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)

    # pass the default argument in publication_date field
    publication_date = models.DateField(default=timezone.now)

    num_pages = models.IntegerField(blank = True, null = True)

    class Admin:
        list_display = ('title', 'publisher', 'publication_date')
        list_filter = ('publisher', 'publication_date')
        ordering = ('-publication_date',)
        search_fields = ('title',)
    def __str__(self):
        return self.title

<强> views.py

完成此操作后,您可以直接在modelform上调用.save()。现在,将使用知晓的日期时间创建book对象。

def add_book(request):
    if request.method == 'POST':
        form = BookForm(request.POST)
        if form.is_valid():
            new_book = form.save() # directly save the book object
            return HttpResponseRedirect('/thanks/')
        else:
            print form.errors
    else:
        form = BookForm()
    return render_to_response('add_book.html',{'form':form})

为什么我们没有在模型字段中使用auto_now_add参数?

来自django的auto_now_add documentation:

Django的auto_now_add使用当前时间,而不是时区。因此,最好使用default参数显式指定默认值。

  

如果您希望能够修改此字段,请设置default=timezone.now   (来自django.utils.timezone.now())而不是auto_now_add=True