A
A
Andrey Salnikov2017-08-16 13:17:00
Django
Andrey Salnikov, 2017-08-16 13:17:00

How to load a separate image into the model?

Good afternoon.
There is this form:

class Layout(forms.Form):
    img = forms.ImageField()
    comment = forms.CharField(required=False, widget=forms.Textarea)

It is displayed on the page and it can be filled. After filling the data AJAX'om sent to the server. Through new FormData.
On the server, the file is written to disk like this:
with open(os.path.join(settings.MEDIA_ROOT, 'mockup', request.FILES['img'].name), 'wb+') as file:
    for chunk in request.FILES['img'].chunks():
        file.write(chunk)

It seems to me that there should be a more elegant way, but I simply did not find another.
After that, the file name and full path to it are written to session.
After some time, you need to write this data to the database, to the model, which has a field:
mockup = models.ImageField('Макет', blank=True, null=True)

Here's what I do (I read it on some forum):
d_f = File(open(c._mockup['img']['url']))
new_order.mockup.save(c._mockup['img']['name'], d_f, save=True)

But nothing works. Question:
How to do it right?
UPD:
The bug has been fixed. I forgot to add open flags to the open
function Then, if possible, answer another question - how to make loading more elegant.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question