我有一个这样的模型:
from django.db import models
from django.contrib.auth.models import User
class Task(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField(default)
completed = models.BooleanField(default=False)
description = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
def summary(self):
return self.description[:50]
def pub_date_pretty(self):
return self.pub_date.strftime('%b %e %Y')
def __str__(self):
return self.title
我有一个这样的forms.py,因为我不希望用户能够确定哪个用户正在保存数据,我希望pub_date
成为现在的时间:
from django import forms
from .models import Task
from django.utils import timezone
class Taskform(forms.ModelForm):
class Meta:
model = Task
fields = ['title', 'description', 'completed']
我的观点是这样的:
@login_required
def create(request):
form = Taskform(request.POST or None)
task = Task()
task.pub_date = timezone.datetime.now()
task.user = request.user
if form.is_valid():
form.save()
return redirect('')
return render(request, 'home/create.html', {'form': form})
我想将时间和用户传递给表单,因为它验证但我不确定如何?
答案 0 :(得分:1)
您可以使用带有form.save()
参数的commit=True
来获取任务实例并进行更新:
if form.is_valid():
task = form.save(commit=False)
task.pub_date = timezone.datetime.now()
task.user = request.user
task.save()
return redirect('')
检查详细信息here。