我想将 Imageform 添加到我的表单中,以允许所有用户添加照片。我已阅读此https://docs.djangoproject.com/en/dev/ref/forms/fields/#imagefield 和此https://docs.djangoproject.com/en/dev/ref/forms/api/#绑定上传的文件
但我仍然对如何实现这一目标感到困惑。如何更改我的代码以允许用户从他们自己的文件夹中添加照片?这是我的代码,我还附上了我想要创建的理想表单。
【我的理想形态】
模型.py
from django.db import models
from django.forms import ModelForm
class Sell(models.Model):
subject = models.CharField(max_length=100)
price = models.CharField(max_length=100)
condition = models.CharField(max_length=100)
photo = models.ImageField(upload_to="media")
email = models.EmailField()
body = models.CharField(max_length=200)
表格.py
from django.forms import ModelForm
from uasite1.models import Sell
class SellForm(ModelForm):
class Meta:
model = Sell
视图.py
from django.shortcuts import render_to_response,get_object_or_404
from django.http import HttpResponseRedirect
from uasite1.forms import SellForm
from uasite1.models import Sell
from django.template import RequestContext
def sell_create(request):
context = {}
if request.method == 'POST':
form = SellForm(request.POST)
if form.is_valid():
new_sell = form.save()
return HttpResponseRedirect('/sechand/%d/' % new_sell.pk)
else:
form = SellForm()
context['form'] = form
return render_to_response('sell.html',context,context_instance = RequestContext(request))
出售.html
{% extends 'base.html' %}
{% block extrahead %}
{% endblock %}
{% block content %}
<form enctype="multipart/form-data" action = "/sechand/" method = "post">
{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value="Submit" />
</form>
{% endblock%}
sell_display.html(这是显示提交信息的模板。)
{% extends 'base.html' %}
{% block content %}
<div id = 'sell'>
<h3> Product Name : [ {{ sell.subject }}]</h3>
<p>Photo{{ sell.photo }}</p>
<p>Price: [ {{ sell.price }} ]</p>
<p>Condition: [ {{ sell.condition }} ]</p>
<p>Comments: [ {{sell.body}} ]</p>
<p>Contact Email:[ {{ sell.email }} ]</p>
</div>
{% endblock %}
网址.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^sechand/$','uasite1.views.sell_create'),
url(r'^sechand/(?P<pk>\d+)/$', 'uasite1.views.sell_detail'),
url(r'^products/electronics/$', 'uasite1.views.Electronics'),
url(r'^products/$', 'uasite1.views.ProductsAll'),
url(r'^admin/', include(admin.site.urls)),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)