Milano
Milano

Reputation: 18705

Saving file in Django doesn't work

I've created a form which should gets text,modelchoice and file. Everything works correctly instead of file saving. It doesn't returns any error but does not save any file.

So this is my form:

class PurchaseForm(forms.Form):
    text = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 18, 'cols': 90}))
    language = forms.ModelChoiceField(queryset=Language.objects.all())
    file = forms.FileField(required=False)

This is a model called job:

class Job(models.Model):
    customer = models.ForeignKey(User,null=False,related_name='customer')
    freelancer = models.ForeignKey(User,null=True,related_name='freelancer')
    description = models.TextField(null=True)
    price = models.FloatField(null=True)
    language = models.ForeignKey(Language,null=False)
    file = models.FileField(upload_to='files')

And this is the view:

def purchase(request):
    if request.method == 'POST':
        print dict(request.POST.iterlists())
        form = forms.PurchaseForm(request.POST)
        if form.is_valid():
            job = Job()
            print form.cleaned_data
            job.customer = request.user
            job.language = form.cleaned_data['language']
            # job.description = form.cleaned_data['description']
            if 'file' in form.cleaned_data.keys():
                print 'OKOK'
                job.file = form.cleaned_data['file']
                # print job.file.path # If I uncomment this, it raises error Exception Value:   The 'file' attribute has no file associated with it.
            job.save()

            return render(request, 'purchases/complete.html')
    else:
        purchase_form = forms.PurchaseForm()
        return render(request, 'jobs/purchase.html', {'purchase_form': purchase_form})

In this view there are two prints. The first prints this (I can see the file there):

{u'text': [u'\u010dr\u010dr\u010dr\u010d'], u'csrfmiddlewaretoken': [u'os8p9oRWR
d8mMTmSsGPd55Y7bWy6pMWl'], u'language': [u'3'], u'file': [u'export.csv']}

And the second prints this:

{'text': u'\u010dr\u010dr\u010dr\u010d', 'file': None, 'language': <Language: HG
: Hungar - Intermediate - 0.02 eur/sign>}

It act's like I didn't upload (send) any file through the form.

Do you have any idea why is that so?

EDIT: If I leave the print job.file.path line uncommented, it raises this error: Exception Value:

The 'file' attribute has no file associated with it.

Upvotes: 0

Views: 1460

Answers (1)

Ivan Semochkin
Ivan Semochkin

Reputation: 8897

I think you need update form like this:

def purchase(request):
    if request.method == 'POST':
        print dict(request.POST.iterlists())
        form = forms.PurchaseForm(request.POST request.FILES or None)

UPD for comment:
for saving try too add this in url:

from django.conf.urls.static import static
urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

and check media settings:

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

this is for admin, add method for model, which use image field:

def admin_image(self):
    return "<img src='%'/>" % self.your_image_field.url
    admin_image.allow_tags = True

and register list_display=('admin_image',) in admin.py

Upvotes: 1

Related Questions