djongo icon indicating copy to clipboard operation
djongo copied to clipboard

FileField inside ArrayModelField isn't being saved via Django admin

Open renzladia opened this issue 8 years ago • 12 comments

I have a FileField in my abstract model being used for my ArrayModelField. The field is being rendered properly in Django admin. However, submitting the form does not save the value provided for the FileField.

Django==1.11.7 djongo==1.2.23 MongoDB v3.6.3

Python script

class Document(models.Model):
    name = models.CharField(_('Name'), max_length=50)
    image = models.FileField(
        _('Document image'),
        null=True,
        blank=True,
        default=None
    )

    class Meta:
        abstract = True


class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = (
            'name', 'image'
        )


class Client(models.Model):
    name = NullCharField(_('Name'), max_length=250)
    documents = models.ArrayModelField(model_container=Document, model_form_class=DocumentForm)


There's no error when saving the entry on the Django admin. It's just that the file isn't being saved. I tried saving it via Django shell, and it worked. Viewing it on Django admin shows the file that I saved via shell. I think the file just isn't being included in the object for the ArrayModelField when saving via Django admin.

renzladia avatar Mar 24 '18 06:03 renzladia

me too

dieudv avatar Aug 27 '18 03:08 dieudv

I have same issue, anyone know the best way to do this thing? model

class Photo(models.Model):
    data = models.ImageField(upload_to='items/')
    feature = models.ListField(default=[])

    class Meta:
        abstract = True


class Item(models.Model):
    main_color = models.CharField(max_length=20)
    type = models.EmbeddedModelField(
        model_container=Type,
    )
    photos = models.ArrayModelField(
        model_container=Photo,
    )

views

photos = []
for p in request.FILES.getlist('photo'):
    photo = Photo()
    photo.data = p
    photos.append(photo)
item = Item()
item.photos = photos
item.save()

trananhkma avatar Nov 29 '18 07:11 trananhkma

Same problem here!

`class Preguntas(models.Model): TIPO = ( ('ISC', 'isc'), ('NPS', 'nps'), ('FEEDBACK', 'feedback'), ) pregunta = RichTextField(max_length=2000) tipo = models.CharField(max_length=2000, choices=TIPO) imagen_url = models.CharField(max_length=256, verbose_name="Imagen", null=True, blank=True) imagen_url_temp = models.ImageField(verbose_name="Imagen", validators=[validate_image]) # imagen_url_temp = models.ImageField(verbose_name="Imagen")

def image_tag(self):
    return mark_safe('<img src="%s" width="150" height="150" />' % (self.imagen_url_temp.url))
image_tag.short_description = 'Imagen'

class Meta:
    abstract = True
    
def __str__(self):
    return self.name

class preguntaRate(models.Model): _id = models.CharField(primary_key=True,max_length=256, verbose_name="_Id") beneficio = models.ForeignKey(beneficio, on_delete=models.CASCADE, verbose_name="Beneficio") preguntas = models.ArrayModelField(model_container=Preguntas, blank=True,null=False) created_at = models.DateField(auto_now_add=True)

# def image_tag(self):
#     return mark_safe('<img src="%s" width="150" height="150" />' % (self.imagen_url_temp.url))
# image_tag.short_description = 'Imagen'

class Meta:
    db_table = 'preguntas_rate'
    verbose_name = 'PreguntasRate'
    verbose_name_plural = 'PreguntasRate'

def save(self, *args, **kwargs):
    if not self.pk :
        self._id = generate_ObjetId()
    arryName = self.imagen_url_temp.name.split('.')
    strCount = len(arryName) -1
    extencion = arryName[strCount]
    if self.imagen_url_temp:
        if 'preguntasrate/' not in self.imagen_url_temp.name:
            strGuid = generate_UUID()
            self.imagen_url= settings.URL + settings.MEDIA_URL + 'preguntasrate/' + strGuid + '.' + extencion
            self.imagen_url_temp.name = 'preguntasrate/' + strGuid + '.' + extencion
    super(preguntaRate, self).save(*args, **kwargs)

def __str__(self):
    return '%s' % (self.beneficio)`

pabloliberona avatar Sep 26 '19 18:09 pabloliberona

@nesdis any comments on this issue??

eldano1995 avatar Mar 31 '20 22:03 eldano1995

def document_path_name_poc(instance, filename):
    dir_name = instance.user.username 
    return 'Certification Upload/%s/%s' % (dir_name,filename)
 
class ClinicDetails(models.Model):
    clinic = models.ForeignKey(HospitalMaster, on_delete=models.CASCADE, verbose_name=_("Clinical Name"))
    clinic_address = models.TextField(verbose_name=_("Clinical Address"))
    affiliation = models.CharField(max_length=100, verbose_name=_("Affiliation"))
    document_path = models.FileField(upload_to=document_path_name_poc, blank=True, null=True, verbose_name=_("Document Path"))
    
    class Meta:
	abstract = True

class ClinicDetailsForm(forms.ModelForm):
    clinic = forms.ModelChoiceField(label=_("Clinical Name"),
	queryset=HospitalMaster.objects.all(),
	widget=autocomplete.ModelSelect2(url='case_history:hospital-autocomplete' ,attrs={'class':'form-control', 'data-placeholder': 'Select Hospital Name', 'data-minimum-input-length': 2})
    )
    clinic_address = forms.CharField(label=_("Clinical Address"), max_length=250, widget=forms.Textarea(attrs={'class':'form-control', 'placeholder':_('Clinical Address')})) 
    affiliation = forms.CharField(label=_("Affiliation"), max_length=250, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':_('Affiliation')})) 
    document_path = forms.FileField(label=_("Document Upload"), widget=forms.FileInput(attrs={'class':'form-control'})) 

    class Meta:
	model = ClinicDetails
	fields = ['clinic','clinic_address','affiliation','document_path']

class PractDetailsArray(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("User"))
    pract_regis_body = models.CharField(max_length=100, verbose_name=_("Registration Body"))
    state =  models.ForeignKey(State, blank=True, null=True, on_delete=models.CASCADE, verbose_name=_("State"))
    tnc = models.BooleanField(default=False, verbose_name=_("Terms And Conditions"))
    pract_reg_no =  models.CharField(max_length=50, verbose_name=_("Registration Number"))
    document_name = models.CharField(max_length=100, verbose_name=_("Document Name"))
    clinical_setting = models.ArrayField(
	model_container=ClinicDetails,
	model_form_class=ClinicDetailsForm,
    )
     
    def __str__(self):
	return self.user.first_name+' '+self.user.last_name
   
    class Meta:
	verbose_name = "Pract Details Array"
	verbose_name_plural = "Pract Details Array"
	db_table = 'PractDetailsArray'

I am also facing same problem here. Please any suggestions..!

ghost avatar Jun 30 '20 09:06 ghost

@nesdis any comments on this issue??

manish2507 avatar Jul 02 '20 13:07 manish2507

Same Problem Here also...

class Attachment(models.Model): title = models.CharField(max_length=10, null=True, blank=True) file = models.FileField( 'Document', upload_to='uplodes/docs', null=True, blank=True)

class Meta:
    abstract = True

def __str__(self):
    return self.title

class Asset(models.Model): _id = models.ObjectIdField() category_id = models.ForeignKey( Category, on_delete=models.CASCADE, blank=True, null=True) category = models.CharField(max_length=200, null=True, blank=True) assetname = models.CharField(max_length=200, null=True, blank=True) material_code = models.CharField(max_length=200, null=True, blank=True) serialnumber = models.CharField(max_length=100, null=True, blank=True) warranty_up_to = models.CharField(max_length=100, null=True, blank=True) photos = models.FileField(blank=True, null=True, upload_to="uplodes/images") attachment = models.ArrayField( model_container=Attachment, null=True, blank=True)

objects = models.DjongoManager()

class Meta:
    db_table = 'asset'

#this is views... def updatethefiles(request): if request.method == "POST": title = request.POST.get('title') length = request.POST.get('length') assetname = request.POST.get('assetname') assetobj = Asset.objects.filter(assetname=assetname) files = [Attachment(title=title, file=request.FILES.get('file'))]

    for file_num in range(0, int(length)):
        for obj in assetobj:
            obj.attachment = files
            obj.save()
            print(title, '---------')
            print(assetname, '---------')
            print("savesavesavesavesave")

return JsonResponse({'status': 'save'})

#"How can we slove this please any suggestions".............................!!

mayurn-code avatar Apr 18 '21 07:04 mayurn-code

Hey Bro For this, I created a custom screen in Django admin.

On Sun, Apr 18, 2021 at 1:23 PM Mayur Nawghare @.***> wrote:

I have a FileField in my abstract model being used for my ArrayModelField. The field is being rendered properly in Django admin. However, submitting the form does not save the value provided for the FileField.

Django==1.11.7 djongo==1.2.23 MongoDB v3.6.3 Python script

class Document(models.Model): name = models.CharField(_('Name'), max_length=50) image = models.FileField( _('Document image'), null=True, blank=True, default=None )

class Meta:
    abstract = True

class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ( 'name', 'image' )

class Client(models.Model): name = NullCharField(_('Name'), max_length=250) documents = models.ArrayModelField(model_container=Document, model_form_class=DocumentForm)

There's no error when saving the entry on the Django admin. It's just that the file isn't being saved. I tried saving it via Django shell, and it worked. Viewing it on Django admin shows the file that I saved via shell. I think the file just isn't being included in the object for the ArrayModelField when saving via Django admin.

Sir How did you slove this problem plz help me...

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/nesdis/djongo/issues/85#issuecomment-821950415, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJQHWOUAH2HLPJCWVMSICJLTJKFYVANCNFSM4EXGQG7A .

ghost avatar Apr 18 '21 07:04 ghost

Same Problem Here also...

class Attachment(models.Model): title = models.CharField(max_length=10, null=True, blank=True) file = models.FileField( 'Document', upload_to='uplodes/docs', null=True, blank=True)

class Meta:
    abstract = True

def __str__(self):
    return self.title

class Asset(models.Model): _id = models.ObjectIdField() category_id = models.ForeignKey( Category, on_delete=models.CASCADE, blank=True, null=True) category = models.CharField(max_length=200, null=True, blank=True) assetname = models.CharField(max_length=200, null=True, blank=True) material_code = models.CharField(max_length=200, null=True, blank=True) serialnumber = models.CharField(max_length=100, null=True, blank=True) warranty_up_to = models.CharField(max_length=100, null=True, blank=True) photos = models.FileField(blank=True, null=True, upload_to="uplodes/images") attachment = models.ArrayField( model_container=Attachment, null=True, blank=True)

objects = models.DjongoManager()

class Meta:
    db_table = 'asset'

#this is views... def updatethefiles(request): if request.method == "POST": title = request.POST.get('title') length = request.POST.get('length') assetname = request.POST.get('assetname') assetobj = Asset.objects.filter(assetname=assetname) files = [Attachment(title=title, file=request.FILES.get('file'))]

    for file_num in range(0, int(length)):
        for obj in assetobj:
            obj.attachment = files
            obj.save()
            print(title, '---------')
            print(assetname, '---------')
            print("savesavesavesavesave")

return JsonResponse({'status': 'save'})

#"How can we slove this please any suggestions".............................!!

To slove this refer this:--- https://stackoverflow.com/questions/25513370/save-file-from-modelforms-filefield

mayurn-code avatar Apr 18 '21 09:04 mayurn-code

can you send me what is the error?

On Sun, Apr 18, 2021 at 2:30 PM Mayur Nawghare @.***> wrote:

Same Problem Here also...

class Attachment(models.Model): title = models.CharField(max_length=10, null=True, blank=True) file = models.FileField( 'Document', upload_to='uplodes/docs', null=True, blank=True)

class Meta: abstract = True

def str(self): return self.title

class Asset(models.Model): _id = models.ObjectIdField() category_id = models.ForeignKey( Category, on_delete=models.CASCADE, blank=True, null=True) category = models.CharField(max_length=200, null=True, blank=True) assetname = models.CharField(max_length=200, null=True, blank=True) material_code = models.CharField(max_length=200, null=True, blank=True) serialnumber = models.CharField(max_length=100, null=True, blank=True) warranty_up_to = models.CharField(max_length=100, null=True, blank=True) photos = models.FileField(blank=True, null=True, upload_to="uplodes/images") attachment = models.ArrayField( model_container=Attachment, null=True, blank=True)

objects = models.DjongoManager()

class Meta: db_table = 'asset'

#this is views... def updatethefiles(request): if request.method == "POST": title = request.POST.get('title') length = request.POST.get('length') assetname = request.POST.get('assetname') assetobj = Asset.objects.filter(assetname=assetname) files = [Attachment(title=title, file=request.FILES.get('file'))]

for file_num in range(0, int(length)):
    for obj in assetobj:
        obj.attachment = files
        obj.save()
        print(title, '---------')
        print(assetname, '---------')
        print("savesavesavesavesave")

return JsonResponse({'status': 'save'})

#"How can we slove this please any suggestions".............................!!

To slove this refer this:--- https://stackoverflow.com/questions/25513370/save-file-from-modelforms-filefield

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/nesdis/djongo/issues/85#issuecomment-821958132, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJQHWOT5ULKCXJK44DOZMX3TJKNSFANCNFSM4EXGQG7A .

ghost avatar Apr 18 '21 09:04 ghost

can you send me what is the error? … On Sun, Apr 18, 2021 at 2:30 PM Mayur Nawghare @.***> wrote: Same Problem Here also... class Attachment(models.Model): title = models.CharField(max_length=10, null=True, blank=True) file = models.FileField( 'Document', upload_to='uplodes/docs', null=True, blank=True) class Meta: abstract = True def str(self): return self.title class Asset(models.Model): _id = models.ObjectIdField() category_id = models.ForeignKey( Category, on_delete=models.CASCADE, blank=True, null=True) category = models.CharField(max_length=200, null=True, blank=True) assetname = models.CharField(max_length=200, null=True, blank=True) material_code = models.CharField(max_length=200, null=True, blank=True) serialnumber = models.CharField(max_length=100, null=True, blank=True) warranty_up_to = models.CharField(max_length=100, null=True, blank=True) photos = models.FileField(blank=True, null=True, upload_to="uplodes/images") attachment = models.ArrayField( model_container=Attachment, null=True, blank=True) objects = models.DjongoManager() class Meta: db_table = 'asset' #this is views... def updatethefiles(request): if request.method == "POST": title = request.POST.get('title') length = request.POST.get('length') assetname = request.POST.get('assetname') assetobj = Asset.objects.filter(assetname=assetname) files = [Attachment(title=title, file=request.FILES.get('file'))] for file_num in range(0, int(length)): for obj in assetobj: obj.attachment = files obj.save() print(title, '---------') print(assetname, '---------') print("savesavesavesavesave") return JsonResponse({'status': 'save'}) #"How can we slove this please any suggestions".............................!! To slove this refer this:--- https://stackoverflow.com/questions/25513370/save-file-from-modelforms-filefield — You are receiving this because you commented. Reply to this email directly, view it on GitHub <#85 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJQHWOT5ULKCXJK44DOZMX3TJKNSFANCNFSM4EXGQG7A .

Yes file not being saved in uploads to dir... There is no error

mayurn-code avatar Apr 18 '21 09:04 mayurn-code

class RepertorisationDocument(models.Model): manual_report = models.FileField(upload_to='Repertorisation_Upload/', blank=True, null=True,verbose_name=_("Repertorisation Document"))

class Meta:
    abstract = True

class CaseRepertorisation(models.Model): id = models.ObjectIdField() case = models.ForeignKey(CaseHistory, on_delete=models.CASCADE, verbose_name=("Case History")) computerized_manual_reports = models.ArrayField( model_container = RepertorisationDocument, null = True ) def str(self): return str(self.case.case_title)

class Meta:
    verbose_name = "Repertorisation "
    verbose_name_plural = "Repertorisation "
    db_table = 'repertorisations'

def repertorisation(request, case_id=None): if request.method == 'POST': user_json = {} if case_id: if CaseRepertorisation.objects.filter(case_id=case_id).exists(): case_repert_record = CaseRepertorisation.objects.get(case_id=case_id) else: case_repert_record = CaseRepertorisation( case_id = case_id, computerized_manual_reports = None, )

        report_data = request.FILES.get('report_upload', None)
        if report_data:
            if case_repert_record.computerized_manual_reports:

case_repert_record.computerized_manual_reports.extend([RepertorisationDocument(manual_report = report_data)]) else: case_repert_record.computerized_manual_reports = ([RepertorisationDocument(manual_report = report_data)])

case_repert_record.computerized_manual_report =

report_data case_repert_record.save() user_json['success_msg'] = _("Report has been saved successfully.") return JsonResponse(user_json)

This my piece of code maybe it will help you.

On Sun, Apr 18, 2021 at 3:01 PM Mayur Nawghare @.***> wrote:

can you send me what is the error? … <#m_-5574444218109011781_> On Sun, Apr 18, 2021 at 2:30 PM Mayur Nawghare @.***> wrote: Same Problem Here also... class Attachment(models.Model): title = models.CharField(max_length=10, null=True, blank=True) file = models.FileField( 'Document', upload_to='uplodes/docs', null=True, blank=True) class Meta: abstract = True def str(self): return self.title class Asset(models.Model): _id = models.ObjectIdField() category_id = models.ForeignKey( Category, on_delete=models.CASCADE, blank=True, null=True) category = models.CharField(max_length=200, null=True, blank=True) assetname = models.CharField(max_length=200, null=True, blank=True) material_code = models.CharField(max_length=200, null=True, blank=True) serialnumber = models.CharField(max_length=100, null=True, blank=True) warranty_up_to = models.CharField(max_length=100, null=True, blank=True) photos = models.FileField(blank=True, null=True, upload_to="uplodes/images") attachment = models.ArrayField( model_container=Attachment, null=True, blank=True) objects = models.DjongoManager() class Meta: db_table = 'asset' #this is views... def updatethefiles(request): if request.method == "POST": title = request.POST.get('title') length = request.POST.get('length') assetname = request.POST.get('assetname') assetobj = Asset.objects.filter(assetname=assetname) files = [Attachment(title=title, file=request.FILES.get('file'))] for file_num in range(0, int(length)): for obj in assetobj: obj.attachment = files obj.save() print(title, '---------') print(assetname, '---------') print("savesavesavesavesave") return JsonResponse({'status': 'save'}) #"How can we slove this please any suggestions".............................!! To slove this refer this:--- https://stackoverflow.com/questions/25513370/save-file-from-modelforms-filefield — You are receiving this because you commented. Reply to this email directly, view it on GitHub <#85 (comment) https://github.com/nesdis/djongo/issues/85#issuecomment-821958132>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJQHWOT5ULKCXJK44DOZMX3TJKNSFANCNFSM4EXGQG7A .

Yes file not being saved in uploads to dir...

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/nesdis/djongo/issues/85#issuecomment-821961766, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJQHWOQZUBM6FYCJ3OPG7YTTJKRHFANCNFSM4EXGQG7A .

ghost avatar Apr 18 '21 12:04 ghost