我是Django的新手。我想创建一个简单的上传应用程序,其中用户将输入图像,价格和电子邮件ID的描述。并且想要显示描述文本和电子邮件以及图像。但是文本没有与图像一起出现。 See the final image after uploading
以下是我的代码:
Models.py
# -*- coding: utf-8 -*-
from django.db import models
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
description = models.CharField(max_length=255, blank=True)
price = models.IntegerField(default=0)
emailId = models.CharField(max_length=255, blank=True)
**forms.py**
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
)
description = forms.CharField(max_length=255)
price = forms.IntegerField()
emailId = forms.CharField(max_length=255)
**views.py**
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.shortcuts import render_to_response
from myapp.models import Document
from myapp.forms import DocumentForm
def list(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
return HttpResponseRedirect(reverse('list'))
else:
form = DocumentForm() # A empty, unbound form
documents = Document.objects.all()
return render(request,'myapp/list.html',{'documents': documents, 'form': form} )
def index(request):
return render_to_response('myapp/index1.html')
**list.html**
{% load staticfiles %}
{% load static %}
<html>
<head>
<meta charset="utf-8">
<title>Recent Uploads</title>
</head>
<body>
<form action="{% url "list" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<div id="wrapper">
<section>
{% if documents %}
<ul id="gallery">
{% for document in documents %}
<li>
<a href="{{ document.docfile.url }}">
<img src="{{ document.docfile.url }}" alt=""></a>
<p>
<font color="black">
<p>Description : {{ document.description }}</p>
<p>Price :{{ document.price }}</p>
<p>Contact/Email-ID : {{ document.emailId }}</p>
</font>
</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
</section>
</div>
</body>
</html>
答案 0 :(得分:0)
您的表单不会将数据保存到数据库中。您需要继承forms.ModelForm
而不是forms.Form
。对于后者,您可能需要编写自己的自定义保存方法。 ModelForms
隐含地为你做这件事。
forms.py,
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = "__all__"
views.py,
def list(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
doc = form.save(commit=False)
doc.docfile = request.FILES['docfile']
doc.save()
return HttpResponseRedirect(reverse('list'))
else:
form = DocumentForm()
documents = Document.objects.all()
return render(request,'myapp/list.html',{'documents': documents, 'form': form} )