我试图在模型上上传图像,然后在模板上显示。
Forms.py:
False
Models.py:
x = "a" if a else ("b" if b else ("c" if c else None))
views.py
class ClanakForma(forms.ModelForm):
class Meta:
model = Clanak
fields = '__all__'
urls.py:
class Clanak(models.Model):
naslov = models.CharField(null=False, blank=True, max_length=120)
datumObjave = models.DateField(null=False, blank=False)
autor = models.ForeignKey(Autor, on_delete=models.CASCADE, null=True)
videofile= models.FileField(upload_to='images/', null=True, verbose_name="")
def __str__(self):
return str(self.naslov) + ', ' + str(self.datumObjave) + ', ' + str(self.autor) + ', ' + str(self.videofile)
justadded.html:
def dodajClanak(request):
if request.method == 'GET':
forma = ClanakForma()
elif request.method == 'POST':
forma = ClanakForma(request.POST)
if forma.is_valid():
data = Clanak()
data.naslov = forma.cleaned_data['naslov']
data.datumObjave = forma.cleaned_data['datumObjave']
data.autor = forma.cleaned_data['autor']
data.videofile = forma.cleaned_data['videofile']
#data.email = forma.cleaned_data['email']
data.save()
return redirect('readAllNew')
return render(request, 'justadded.html', {'forma':forma})
def readAllNew(request):
data = list(Clanak.objects.all())
return render(request, 'readAllNew.html', {'data':data})
readAllNew.html
urlpatterns = [
path('dodajClanak/',views.dodajClanak, name='dodajClanak'),
path('readAllNew/',views.readAllNew, name='readAllNew'),
] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
我的问题是,当我转到http://127.0.0.1:8000/dodajClanak/并尝试上传出现错误的图像时:
用英语说:“您没有选择任何图像”。
当我进入链接http://127.0.0.1:8000/readAllNew/时,我看不到任何图像:
我可以通过管理站点上传它,但仍然看不到。
答案 0 :(得分:2)
将表单更改为
<form action="{% url 'dodajClanak' %}" method="post" enctype=multipart/form-data>
并从中查看
forma = ClanakForma(request.POST)
if forma.is_valid():
data = Clanak()
data.naslov = forma.cleaned_data['naslov']
data.datumObjave = forma.cleaned_data['datumObjave']
data.autor = forma.cleaned_data['autor']
data.videofile = forma.cleaned_data['videofile']
#data.email = forma.cleaned_data['email']
data.save()
return redirect('readAllNew')
到
forma = ClanakForma(request.POST,request.FILES)
if forma.is_valid():
forma.save()
return redirect('readAllNew')
在使用ModelForm
时,无需写所有这些行
答案 1 :(得分:1)
扩展@Exprator答案
尝试显示图片
<td><img src='{{media_url}}{{ i.videofile.url }}'></td>
希望有帮助