Django在自定义模板中上载图像
forms.pyDjango在自定义模板中上载图像,django,Django,forms.py from django import forms from .models import VideoPost class PostForm(forms.ModelForm): class Meta: model = VideoPost fields = ('category', 'title', 'slug', 'content', 'video', 'image',) models.py class VideoPost(model
from django import forms
from .models import VideoPost
class PostForm(forms.ModelForm):
class Meta:
model = VideoPost
fields = ('category', 'title', 'slug', 'content', 'video', 'image',)
models.py
class VideoPost(models.Model):
category = models.ForeignKey('Category', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique = True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
video = models.CharField(max_length=100, blank=True)
content = RichTextUploadingField()
image = models.ImageField(upload_to='images', null=True, blank=True)
date_posted = models.DateTimeField(default=timezone.now)
def _get_unique_slug(self, *args, **kwargs):
self.slug = slugify(self.title)
super(VideoPost, self).save(*args, **kwargs)
def __unicode__(self):
return self.title
views.py
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return render(request, 'stories/post_detail.html')
else:
form = PostForm()
return render(request, 'stories/post_new.html', {'form': form})
设置.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
LOGIN_REDIRECT_URL = 'home'
MEDIA_URL = 'static/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
这不是django内置的管理页面,我想制作一个自定义的帖子模板。
所有其他表单输入工作正常,除图像外,所有数据都正确地存储在db中。
数据库中的图像字段始终为空,无论我在其中放置了什么图像,甚至在我的静态/媒体/图像路径中,它也是空的。
非常感谢您的帮助。请确保在HTML表单中正确设置了属性enctype=“multipart/form data”。否则request.FILES将为空。Oh。。。。我懂了。。。我已经为此挣扎了好几个小时,而这一行正好解决了这个问题。谢谢!!!没问题,试着遵循django的惯例。