Django REST and FILEFIELD field

40 views
Skip to first unread message

manu.polline

unread,
Feb 26, 2010, 1:35:11 PM2/26/10
to django-rest
Hi everyone,
my name is Manuel. I'm tryng to upload a file directly in a filefield
of Django model exposed by django-rest-interface.
It'is possible?
this is my model :

class File(models.Model):
file = models.FileField(upload_to='files',
help_text=_("file itself"))
page = models.ForeignKey(page)

and my urls.py :
json_File_resource = Collection(
queryset = File.objects.all(),
authentication = HttpBasicAuthentication(),
permitted_methods = ('GET', 'POST', 'PUT', 'DELETE'),
receiver = JSONReceiver(),
responder = JSONResponder()
)

urlpatterns = patterns('',
....
....
url(r'^json/CampaignFile/(.*?)/?$',json_File_resource),
...
)

The GET works and the PUT to other field too but not the POST or the
PUT on filefield Field.
How i can pass the local file to the remote Service in the JSON
string?
For example, what is the correct cUrl command to POST a File?

Please Help Me!!!

Manuel

drozzy

unread,
Feb 26, 2010, 3:58:49 PM2/26/10
to django-rest
I would think you can just use usual django POST method for uploading
files:
http://docs.djangoproject.com/en/dev/topics/http/file-uploads/

You can expose a url (doesn't have to be rest-based) who's view will
handle the uploaded file.

manu.polline

unread,
Feb 26, 2010, 6:45:52 PM2/26/10
to django-rest
Thanks for the answer!

Can you explain with a little example for my model?
Please...it's the last things and my project is ready.
Please

Manuel

drozzy

unread,
Feb 26, 2010, 6:56:33 PM2/26/10
to django-rest
Well, hello again,

I think you maybe have to explain more, in order for me to understand
what exactly you are trying to accomplish. Sorry - I am a bit slow ;-(

If you don't fancy talking here you can always head over to live
Django chat where folks will help you out: irc://irc.freenode.net/django
Also check out django faq on more resources:
http://code.djangoproject.com/wiki/IrcFAQ

I don't think this is related to rest-framework, but django in
general. If I am mistaken - please correct me.

manu.polline

unread,
Feb 26, 2010, 7:16:59 PM2/26/10
to django-rest
Hi Again,
i'm trying to populate a django model with a Java Http Client, or by a
cURL command.
The model is this:

class File(models.Model):
file = models.FileField(upload_to='files',
help_text=_("file itself"))
page = models.ForeignKey(page)

I want to upload a local file from my pc to the server where Django
run directly in my model.
I've done this things with many other model but this one is the only
that have a filefield field .
I think that the django-rest it's my solution but all all my trying
fail :( .
If you'll help me you'll become my hero
thanks

Manuel

drozzy

unread,
Feb 26, 2010, 7:33:09 PM2/26/10
to django-rest
I think you are confused as to what django-rest is for.
I don't think you are using django-rest at all. It looks like you have
a simple django model.

In that case you need to see what kind of "view" the django provides.
You probably have a view that accepts a file:

def upload_file(request):
//do stuff with request.FILES and request.POST

In that case all you need to do from Java-http client side is send a
"post" request with the form with enctype="multipart/form-data".
Then on the django side you can access it from the view.
Again I refer you to django docs for that:
http://docs.djangoproject.com/en/dev/topics/http/file-uploads/


I am not sure which part you are using - the django side (which saves
the file) or the java-client side of the webservice, which tries to
send the file.
It is not clear to me what exactly you are trying to accomplish.
Perhaps describing what kind of components you have in your system
(i.e. client, service, database) and how they interact might help me
in understand in what exactly you are trying to accomplish.

Remember, that in order to ask a question - one must know greater part
of the answer. So ask away.

manu.polline

unread,
Feb 26, 2010, 7:58:00 PM2/26/10
to django-rest
My side is the Java Client side.
All i want is manage remotely the Django side without using the django
site.
The java client side db is postgresql and the django side db is
sqlite.
In my client i'm using the apache commons component.
The django application is an already existing application and i think
that exposing all model with django-rest is the solution of all my
problems.
And it is, because i can manage all models ( db tables data) but not
in this filefield case :(.
In my view.py the only thing tha refer to the file is

def grab_file(request, file):
print "grab_file", file
file = File.objects.get(file=file).file
mime = guess_mime(file.name)
print mime
return HttpResponse(file.read(), mimetype=mime[0] )

And in my form there isn't nothing that refer to file model

Manuel

drozzy

unread,
Feb 26, 2010, 8:13:22 PM2/26/10
to django-rest
The problem is that your view accepts (request, file), but it must
only accept request parameter. Request parameter holds the file within
itself, inside a special variable called FILES. This in turn ties into
the form with which you submitted files - and the input field used

Did you read the django doc on handling files?
http://docs.djangoproject.com/en/dev/topics/http/file-uploads/

I am not sure how you would set this up from the Java side - that is
for creating this kind of POST request. I suggest you inspect the
"request" object, by doing something like:
print( dir(request) )
inside the django view.
And see if the has the "FILES" variable in it.

Let me know what you come up with. I'll try to dig around here.

manu.polline

unread,
Feb 26, 2010, 8:27:23 PM2/26/10
to django-rest
The project i'm talking about is here :

http://proximitymarketing.googlecode.com/files/openproximity2-devel-20100212114948.tar.gz

and the model is CampaignFile. I hope this help you to understand!

Manuel

On 27 Feb, 02:13, drozzy <dro...@gmail.com> wrote:
> The problem is that your view accepts (request, file), but it must
> only accept request parameter. Request parameter holds the file within
> itself, inside a special variable called FILES. This in turn ties into
> the form with which you submitted files - and the input field used
>

> Did you read the django doc on handling files?http://docs.djangoproject.com/en/dev/topics/http/file-uploads/

drozzy

unread,
Feb 26, 2010, 8:50:06 PM2/26/10
to django-rest
Hm...
So you are using this url?
file/grab/(?P<file>.+)

Are you issuing a get request then?
Because all I can see is a view called "grab_file" that Returns a file
object, not saves it.

I am still not clear as to what you are trying to do.

On Feb 26, 9:27 pm, "manu.polline" <manuel.coli...@gmail.com> wrote:
> The project i'm talking about is  here :
>

> http://proximitymarketing.googlecode.com/files/openproximity2-devel-2...

manu.polline

unread,
Feb 26, 2010, 8:59:10 PM2/26/10
to django-rest
No, i'm not using this url.
I want to upload a file, with one campaign value and one chance value
( model CampaignFile).
I have a campaign with id=1 and i want post a file test.txt , chance=1
and campaign=1 from my java client .
---In my forms.py i define ----

class FileForm(forms.ModelForm):
class Meta:
model = CampaignFile

----in my views.py----

def upload_file(request, file=None):
print "configure_file", file

errors = []
messages = []
form = None
if request.method == "POST":
form=FileForm(request.POST, request.FILES)
if form.is_valid():
cd=form.cleaned_data
add_file(
cd['campaign'],
cd['chance'],
cd[request.FILES['file']],
)
return HttpResponseRedirect('/')

---and ---

def add_file(campaign, chance, file):

search=CampaignFile.objects.filter(file=file)


if search.count()==0:
rec = CampaignFile(request.POST, request.FILES)
rec.campaign = campaign
rec.chance = chance
rec.file = request.FILES['file']
rec.save()
print rec

---and in my urls.py---

url(r'^json/prova/', views.upload_file),

It's the right way? Where i'm wrong? it doesn't work :(

drozzy

unread,
Feb 26, 2010, 9:25:05 PM2/26/10
to django-rest
well when you say "CampaignFile.objects.filter(file=file)", the file
is None at this point, as your upload_file only receives the request
as an argument.
You should get your filename some other way.
If however you do not find it - you create a new CampaignFile object.
By passing request.POST you already populate all your fields, so you
do not need to assign chance and campaign, to which you do not have
access in your "add_file" function.

so just doing:

rec=CampaignFile(request.POST, request. FILES)
rec.save()

should do it.

I hope I am not confusing you.

manu.polline

unread,
Feb 26, 2010, 9:51:32 PM2/26/10
to django-rest
Like so?

def upload_file(request):


if request.method == "POST":
form=FileForm(request.POST, request.FILES)
if form.is_valid():

rec = CampaignFile(request.POST, request.FILES)
rec.save()
return HttpResponseRedirect('/')

I my debug I alwais get

Request information
FILES No Files Data

:(

manu.polline

unread,
Feb 26, 2010, 10:53:09 PM2/26/10
to django-rest
it work!!!!

but i get this error

int() argument must be a string or a number, not 'QueryDict'

what does it means!!

You are really an hero!

drozzy

unread,
Feb 27, 2010, 9:25:35 AM2/27/10
to django-rest
My friend, you'll have to let me see the complete stack-trace.
Just copy the full error message and paste it here.

manu.polline

unread,
Feb 27, 2010, 10:31:02 AM2/27/10
to django-rest
Hi

this is my error.
You are really gentle
thanks
don't look at the url name . I've to change it :)

TypeError at /json/prova/

int() argument must be a string or a number, not 'QueryDict'

Request Method: POST
Request URL: http://192.168.1.170/json/prova/
Exception Type: TypeError
Exception Value:

int() argument must be a string or a number, not 'QueryDict'

Exception Location: /opt/openproximity2/libs/django/db/models/fields/
__init__.py in get_db_prep_value, line 361
Python Executable: /usr/bin/python
Python Version: 2.6.2
Python Path: ['/opt/openproximity2/django-web', '/opt/openproximity2/
libs', '/opt/openproximity2/libs/django/template/loaders/eggs.py', '/
opt/openproximity2/libs/django/template/loaders/eggs.pyc', '/opt/
openproximity2/libs/django/template/loaders/.svn/text-base/eggs.py.svn-
base', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/
lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/
python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/
python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/
gst-0.10', '/var/lib/python-support/python2.6', '/usr/lib/python2.6/
dist-packages/gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/
usr/local/lib/python2.6/dist-packages']
Server time: sab, 27 Feb 2010 16:29:39 +0100

drozzy

unread,
Feb 27, 2010, 11:47:02 AM2/27/10
to django-rest
Hm...
What does your urls.py entry for this url look like?

> ...
>
> read more »

manu.polline

unread,
Feb 27, 2010, 12:06:49 PM2/27/10
to django-rest
This is in my urls.py

url(r'^json/prova/', views.upload_file),

> ...
>
> leggi tutto

drozzy

unread,
Feb 27, 2010, 3:46:25 PM2/27/10
to django-rest
Hm... I can 't seem to see what the problem is. Let me know if you
find something new.
Make sure you types are correct, especially in models, forms and urls.

> ...
>
> read more »

manu.polline

unread,
Feb 28, 2010, 1:39:33 PM2/28/10
to django-rest
Hi,
this is my model

class CampaignFile(models.Model):
chance = models.DecimalField(null=True, blank=True, default=1.0,
decimal_places=2, max_digits=3,
help_text=_("if < 1 then a random number generator will check if the
user is lucky enough to get this file"))
file = models.FileField(upload_to='campaign',
help_text=_("campaign file itself"))

campaign = models.ForeignKey(MarketingCampaign)

def __unicode__(self):
return "%s: %.2f" % (self.file, self.chance)


this is my form

class FileForm(forms.ModelForm):
class Meta:
model = CampaignFile

this is my view

def upload_file(request, file=None):
print "configure_FILE", file

errors = []
messages = []
form = None
if request.method == "POST":
form=FileForm(request.POST, request.FILES)
if form.is_valid():

rec = CampaignFile(request.POST, request.FILES)
rec.save()
return HttpResponseRedirect('/')

return render_to_response('op/upload_file.html', {'form':
form})
#messages.append("file uploaded")

this is my html body

<form action="." enctype="multipart/form-data"
method="POST">
<table>
<tr>
<td>{% trans "campaign" %}</td>
<td><input type="text" name="campaign" value="{{ campaign }}" ></
td>
</tr>
<tr>
<td>{% trans "chance" %}</td>
<td><input type="text" name="chance" value="{{ chance }}" ></td>
</tr>
<tr>
<td>{% trans "file" %}</td>
<td><input type="file" name="file" value="{{ file }}" ></td>
</tr>
{% if messages %}
{% for message in messages %}
<tr><td>{{ message }}</td></tr>
{% endfor %}
{% endif %}
<tr>
<td><input type="submit" value="{% trans "Upload" %}"></td>
</tr>
</table>
</form>

Manuel

> ...
>
> leggi tutto

drozzy

unread,
Mar 1, 2010, 7:32:33 AM3/1/10
to django-rest
Hey,
Well i can't seem to find any errors here.
Your error has something to do probably with how you are casting to
integer - so you have something like "int(q)" somewhere - where q is
not a string.
Or you are formatting something with %d and passing it a query string,
something like: "%d" % q

That is my best guess.

> ...
>
> read more »

Reply all
Reply to author
Forward
0 new messages