Problems with Image Link


I created a model called worker that has a field called signature where I'm uploading the signature digital in an image:

class Trabajador(models.Model):
    usuario = models.OneToOneField(User)
    dni = models.CharField(max_length=8,primary_key=True)
    apellido_paterno = models.CharField(max_length=50)
    apellido_materno = models.CharField(max_length=50)
    nombres = models.CharField(max_length=100)    
    firma = models.ImageField(upload_to='firmas')
    estado = models.BooleanField(default=True)

    def nombre_completo(self):
        return self.apellido_paterno+' '+self.apellido_materno+' '+self.nombres    

    def __str__(self):
        return smart_str(self.apellido_paterno)+' '+smart_str(self.apellido_materno)+' '+smart_str(self.nombres)

I have a form named TrabajadorForm where I use the model created previously:

class TrabajadorForm(forms.ModelForm):

    class Meta:
        model = Trabajador
        fields =['dni','apellido_paterno','apellido_materno','nombres','usuario','firma']

    def __init__(self, *args, **kwargs):
        super(TrabajadorForm, self).__init__(*args, **kwargs)
        for field in iter(self.fields):
                'class': 'form-control'

I have a view to be able to modify the worker:

class ModificarTrabajador(UpdateView):
    model = Trabajador
    template_name = 'modificar_trabajador.html'
    form_class = TrabajadorForm
    success_url = reverse_lazy('administracion:maestro_trabajadores') 

And the template called modify_worker:

{% extends "base_administracion.html" %}
{% block cuerpo %}

<div class="row">
    <div class="col-lg-12">
        <h1 class="page-header">Modificar Trabajador</h1>
<div class="row">
    <div class="col-lg-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                Por favor ingrese todos los campos necesarios.
            <div class="panel-body">
                <form role="form" action="{% url 'administracion:modificar_trabajador' %}" method="post" enctype="multipart/form-data">
                    {% csrf_token %}
                    <div class="form-group">
                        {{ form.as_p }}                         
                    <div class='form-group'>
                        <input type="submit" class="btn btn-primary" name="submit" value="Modificar Trabajador">
                        <button type="reset" class="btn btn-primary" onclick="location.href='{% url 'administracion:maestro_trabajadores' %}'">
<div id="popup"></div>
{% endblock cuerpo %}

Until then everything works very well but when I click on the signature link I get an error because the link points to:



and not to the correct location of the file, I would like to see if something can be done to solve this problem. Greetings.

asked by inkarri 10.05.2016 в 17:29

1 answer


In the file, define the following variables:

MEDIA_ROOT = os.path.join(BASE_DIR, 'images')
MEDIA_URL = '/images/'

Then in app / modify the signature model:

firma = models.FileField(upload_to=imageName_Generator)

imageName_Generator is the name of the following function (also defined within the arvhico):

def imageName_Generator(instance, filename):
    import random, string, datetime

    # separas la extencion del archivo y la guardas en ext
    ext = filename.split('.')[-1]
    # guardas en now la fecha y la hora cuando se guardo el archivo (se genero al usuario)
    now =
    # personalmente me gusta agregar un string aleatorio para generar nombre aun mas unicos 
    # a los archivos,en esta ocacion estamos generando un string aleatorio de letras y 
    # digitos con una longitur de 5 caracteres
    rdm = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(5)])

    # finalmente juntamos todo en una sola variable
    finalname = "%s-%s-%s_%s.%s" % (str(now.year), str(now.month), str(, str(rdm), str(ext))
    # y regresamos la ruta donde la guardaremos junto con el nombre y extencion
    return os.path.join('firmas/', finalname)

The variable instance that receives the imageName_generator function is all the form information, in case you want to add, for example, the name of the user to the name of the image.

Many things you already have contemplated, but even so I leave to cover everything you need to work with images in django.

answered by 11.10.2016 в 22:44