当我尝试使用http:// localhost:8000 / create /创建新帖子时,出现此错误。我找不到以为它们看起来相似的解决方案。我遵循一些博客教程
我不能在此处粘贴settings.py,因为帖子中有很多代码,但我认为settings.py很好,顺便说一句
我的模型。py(*我删除了一些可能不涉及的代码)
User = get_user_model()
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField()
def __str__(self):
return self.user.username
class Post(models.Model):
title = models.CharField(max_length=100)
overview = models.TextField()
detail = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
content = RichTextUploadingField(config_name='post_ckeditor')
comment_count = models.IntegerField(default=0)
view_count = models.IntegerField(default=0)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField()
categories = models.ManyToManyField(Category)
featured = models.BooleanField()
previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank = True, null = True)
next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank = True, null = True)
我的views.py
def get_author(user):
qs = Author.objects.filter(user=user)
if qs.exists():
return qs[0]
return None
pass
def post_create(request):
form = PostForm(request.POST or None, request.FILES or None)
author= get_author(request.user)
if request.method == 'POST':
if form.is_valid():
form.instance.author = author
form.save()
return redirect(reverse('post-detail', kwargs={
'id': form.instance.id
}))
context = {
'form': form
}
return render(request, 'post_create.html', context)
pass
我的表格。py
from django import forms
from .models import Post, Comment
class PostForm(forms.ModelForm):
content = forms.CharField
class Meta:
model = Post
fields = ('title', 'overview', 'content', 'thumbnail', 'categories', 'featured', 'previous_post', 'next_post')
class CommentForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea(attrs={
'class':'form-control',
'placeholder':'Type your comment',
'id':'usercomment',
'rows':4
}))
class Meta:
model = Comment
fields = ('content', )
请帮助!
答案 0 :(得分:0)
每当模型字段发生变化或添加或删除新模型时,都应进行迁移。如果不为null,则将默认对象传递给外键。
答案 1 :(得分:0)
如果您尝试将request.user
保存在作者字段中,则无需编写额外的方法即可。
if request.method == 'POST':
if form.is_valid():
post =form.save(commit=False)
post.author = request.user
post.save()
return redirect(reverse('post-detail', kwargs={'id': post.id }))