我正在制作出售二手自行车的网络应用,我无法弄清楚如何让用户上传多张图片。目前只能上传一张图片。谢谢!
这是我的model.py:
class UsedBike(models.Model):
manufacturer = models.CharField("Proizvođač",
max_length = 20, choices = manufacturers,) #proizvodjac
model = models.CharField("Model:", max_length = 20) #model
engine_size = models.IntegerField("Kubikaža:", default = 0) #kubikaza
km = models.IntegerField("Kilometraža:", default = 0) #kilometraza
year = models.IntegerField("Godina proizvodnje:", default = 0) #godina proizvodnje
bike_type = models.CharField("Vrsta motora:", max_length = 20, choices = bike_types) #tip motora
location = models.CharField("Lokacija:", max_length = 20) #lokacija
comment = models.TextField("Komentar:") #opis
views = models.IntegerField("Broj pregleda:", default = 0) #broj pregleda
likes = models.IntegerField(default = 0) #broj lajkova
slug = models.SlugField(unique = True) #slug
hp = models.IntegerField("Snaga", default = 0) #snaga
condition = models.CharField("Stanje:", max_length = 15, choices = condition_of_bike) #stanje
price = models.IntegerField("Cena:", default = 0) #cena
registered = models.CharField("Registrovan:", max_length = 15, choices = yes_no) #registrovan
img = models.ImageField("Slike:", upload_to = 'img', blank = True, null = True)
pub_date = models.DateTimeField(editable = False, default = timezone.now())
expire_date = models.DateTimeField(editable = False, default = timezone.now()+datetime.timedelta(days = 30))
author = models.ForeignKey(User)
forms.py:
class BikeForm(forms.ModelForm):
helper = FormHelper()
helper.layout = Layout(
Div(
Div('manufacturer', 'model', 'engine_size', 'km', 'year', 'bike_type', 'location',
css_class = 'col-md-6'),
Div(AppendedText('hp', 'ks'), 'condition', AppendedText('price', '€'), 'registered', 'comment', Field('img', multiple = 'multiple'),
ButtonHolder(Submit('submit', 'Dodaj', css_class = 'btn btn-primary')), css_class = 'col-md-6'),
css_class = 'row-fluid'),
)
class Meta:
model = UsedBike
widgets = {
'comment': forms.Textarea(attrs={'rows': 6, 'cols': 1}),
}
exclude = ('views', 'likes', 'slug', 'author')
views.py:
def add_bike(request):
if request.method == 'POST':
form = BikeForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit = False)
form.author = request.user
form.save()
if 'img' in request.FILES:
form.img = request.FILES['img']
form.save()
return index(request)
else:
print form.errors
else:
form = BikeForm()
return render(request, 'shop/add_bike.html', { 'form': form })
我在模板中的表单:
<form class = 'form' enctype = 'multipart/form-data' role = 'form' id = 'bike_form' method = 'post' action = '/shop/add_bike/' >
<h2>Postavi oglas</h2>
{% csrf_token %}
{% crispy form %}
</form>
答案 0 :(得分:0)
看看django-photologues&#39;源代码。它可以选择在zip文件https://github.com/jdriscoll/django-photologue
中上传任意数量的图像