我的观点: ''' 从django.shortcuts导入渲染 从django.http导入HttpResponse 来自.models import Post 从.forms导入createPostForm
def showPosts(request):
if request.method == "POST":
crf = createPostForm(request.POST)
crf.author = request.user
crf.save()
else:
crf = createPostForm()
context = {
'post' : Post.objects.all(),
'crf' : crf
}
return render(request, 'Content/FeedsPage.html', context)
'''
我的模特: '''
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
# image = models.ImageField(blank=True, null=True, upload_to='post_images/')
# video = models.FileField(blank=True, null=True, upload_to='post_videos/')
title = models.CharField(max_length=100)
description = models.CharField(blank=True, max_length=1000)
date_posted = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
'''
我的模板:
'''
<form enctype="multipart/form-data" novalidate method="post">
{%csrf_token%}
<div class="fieldWrapper">
{{crf.title.errors}}
{{crf.title}}
</div>
<div class="fieldWrapper">
{{crf.description.errors}}
{{crf.description}}
</div>
<button class="primaryButton" type="submit">submit</button>
</form>
''' 我的表格:
'''
from django import forms
from .models import Post
class createPostForm(forms.ModelForm):
title = forms.CharField(
widget = forms.TextInput(attrs={
'placeholder': 'Give a sweet title',
'autocomplete' :'off'
})
)
description = forms.CharField(widget=forms.TextInput(attrs={
'placeholder': 'Please elaborate a little',
'autocomplete' :'off'
}))
class Meta:
model = Post
fields = '__all__'
'''
我删除了is_valid()函数以查看发生了什么并相应地显示了它 “无法创建帖子,因为数据未通过验证”
请有人帮助
答案 0 :(得分:0)
此save()方法接受可选的commit关键字参数,该参数接受True或False。如果使用commit = False调用save(),它将返回一个尚未保存到数据库的对象。在实际保存之前,对于某些后期处理而言,这很不错!因此,您的方法应如下所示。
def showPosts(request):
if request.method == "POST":
crf = createPostForm(request.POST)
if crf.is_valid():
form = crf.save(commit=False)
form.author = request.user
form.save()
else:
crf = createPostForm()
context = {
'post' : Post.objects.all(),
'crf' : crf
}
return render(request, 'Content/FeedsPage.html', context)