我試圖上傳圖片,但我一直在谷歌搜索,但我找不到解決方案。 問題是,它不上傳圖像,並在數據庫字段中保存爲空。 任何人都可以幫助我找到解決問題的辦法。 我使用django 1.10和Linux。無法在django上使用MEDIA_ROOT上傳圖像
注:英語不是我的母語;請原諒我的一部分的任何錯誤
注意,如果我可以從Django管理
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/imagenes/')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
Models.py
from django.db import models
from apps.almacen.categoria.models import Categoria
# Create your models here.
class Articulo(models.Model):
idarticulo = models.AutoField(primary_key=True)
codigo= models.CharField(max_length=50)
nombre= models.CharField(max_length=100)
stock= models.IntegerField()
descripcion=models.CharField(max_length=512)
imagen=models.FileField(upload_to = 'articulos/',null=True,blank=True)
estado=models.CharField(max_length=20)
idcategoria= models.ForeignKey(Categoria,db_column='idcategoria',null=True,blank=True,on_delete=models.CASCADE)
def __str__(self):
return '{}'.format(self.nombre)
forms.py內上傳的圖片
from django import forms
from apps.almacen.articulo.models import Articulo
class ArticuloForm(forms.ModelForm):
class Meta:
model = Articulo
fields = [
'idarticulo',
'nombre',
'codigo',
'descripcion',
'idcategoria',
'stock',
'imagen',
]
labels = {
'idarticulo':'Articulo',
'nombre':'Nombre',
'codigo':'Codigo',
'descripcion':'Descripción',
'idcategoria':'Categoria',
'stock':'Stock',
'imagen':'Imagen',
}
widgets = {
'nombre': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Digite el nombre'}),
'codigo': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Digite el código'}),
'idcategoria': forms.Select(attrs={'class':'form-control'}),
'stock': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Digite el stock'}),
'descripcion': forms.TextInput(attrs={'class':'form-control','placeholder':'Digite la Descripción'}),
'imagen': forms.FileInput(attrs={'class':'form-control'}),
}
Views.py
class ArticuloCreate(CreateView):
model= Articulo
form_class= ArticuloForm
template_name='almacen/articulo/articulo_form.html'
success_url= reverse_lazy('almacen_art:articulo_listar')
def post(self, request, *args, **kwargs):
self.object = self.get_object
form = self.form_class(request.POST)
if form.is_valid():
articulos = form.save(commit=False)
articulos.save()
return HttpResponseRedirect(self.get_success_url())
else:
return self.render_to_response(self.get_context_data(form=form))
articulo.html
<form method="post" enctype='multipart/form-data'>
{% csrf_token %}
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label for="image">Imagen</label>
{{form.imagen}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<button class="btn btn-primary" type="submit">Guardar</button>
<button class="btn btn-danger" type="reset">Cancelar</button>
</div>
</div>
</div>
</form>
{% endblock %}
你可以幫我解決這個問題呢?
你看到了什麼錯誤? – Fallen
此問題有被關閉的危險。您需要提供一個最小示例並可能包含錯誤消息。 – cwallenpoole
@Falle問題是它沒有上傳圖像,並在數據庫中保存爲空 – Xavier