我想在我的django应用中保存并过滤用户的对象。输入以下代码后,图像域不会将任何图像上传到我的数据库,也不会在我的模板中返回任何图像。
模型
class Fin(models.Model):
user=models.ForeignKey(User)
title=models.CharField(max_length=250, help_text='3 bedroom flat for lease')
main_view=models.ImageField(upload_to="photos",blank=True, null=True)
side_view=models.ImageField(upload_to="photos",blank=True, null=True)
address=models.CharField(max_length=200)
city=models.CharField(max_length=200)
state=models.CharField(max_length=200)
guideline=models.TextField(max_length=1000)
def __unicode__(self):
return self.title
class FinForm(ModelForm):
class Meta:
model=Fin
fields=('title','main_view','side_view', 'address','city','state','guideline')
exclude=('user')
浏览
def fincrib(request):
extra_data_context={}
#if there's nothing in the field do nothing.
if request. method=="POST":
form =FinForm(request.POST)
if form.is_valid():
data=form.cleaned_data
newfincribs=Fin(
user= request.user,
title=data['title'],
main_view=data ['main_view'],
side_view=data['side_view'],
address=data['address'],
city=data['city'],
state=data['state'],
guideline=data['guideline'])
newfincribs.save()
extra_data_context.update({'FinForm':form})
else:
form = FinForm()
extra_data_context.update({'FinForm':form})
extra_data_context.update({'Fins':Fin.objects.filter(user=request.user)})
return render_to_response('post.html',extra_data_context,context_instance=RequestContext(request))
模板
{% block content %}
<form action="." method="POST">
{% csrf_token %}
<center> {{FinForm.as_p}} </center>
<input type="submit" value="Submit"/>
</form>
{% for Fin in Fins %}
<tr>
<a href="{% url profiles_edit_profile %}"> {{Fin.user}} </a> </p> </strong>
<p>{{Fin.title}}</p>
<p><img src="{{MEDIA_URL}}/{{Fin.main_view}}"/></p>
<p> <img src="{{MEDIA_URL}}/{{Fin.side_view}}"/></p>
<p> {{Fin.address}} </p>
<p> {{Fin.city}}</p>
<p> {{Fin.state}}</p>
<p> {{Fin.guideline}}</p>
{% endfor %}
{% endblock %}
答案 0 :(得分:2)
你在模板和视图层上遗漏了很多东西。
阅读本文:https://docs.djangoproject.com/en/1.3/topics/http/file-uploads/#basic-file-uploads
答案 1 :(得分:0)
从django官方文档中阅读binding uploaded files to a form。我认为它可以提供帮助。