您好我正在建立自己的博客,我一直在尝试将照片添加到我的博文中。目前,我可以将照片上传到媒体/文档文件夹,但是我在将这些照片分配到帖子时遇到了问题。
这就是我的models.py看起来像
class Document(models.Model):
post = models.ForeignKey('blog.Post', related_name='documents', null = True)
description = models.CharField(max_length=255, blank=True)
document = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.text
forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('description', 'document')
views.py
@login_required
def model_form_upload(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.post = post
form.save()
return redirect('/')
else:
form = DocumentForm()
return render(request, 'blog/model_form_upload.html', { 'form': form })
在post_detail.html
中{% for document in post.documents.all %}
<div style="padding: 10px;">
<p> {{ document.description }} </p>
<img src=""/>
</div>
{% endfor %}
...
{% if user.is_authenticated %}
<a class="btn btn-default" href="{% url 'model_form_upload' pk=post.pk %}">Add photo</a>
{% endif %}
目前,我正在尝试打印出描述,然后处理网址会更容易。照片正在上传,它们只是没有连接到帖子。当我删除null = True
时,我无法在命令行上传递makemigrations。任何人都可以帮我解决这里的错误吗?
编辑:如果有帮助,则注释类具有相同的代码行,但仍然可以正常工作:
models.py
class Comment(models.Model):
post = models.ForeignKey('blog.Post', related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('author', 'text')
答案 0 :(得分:0)
您的DocumentForm
没有post
属性,因此它不知道如何保存它。
添加到DocumentForm
除post
以外的所有字段:
class DocumentForm(ModelForm):
class Meta:
model = Document
exclude = ['post']
然后,在视图中,执行以下操作:
@login_required
def model_form_upload(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
document = form.save(commit=False)
document.post = post
document.save()
return redirect('/')
else:
form = DocumentForm()
return render(request, 'blog/model_form_upload.html', { 'form': form })