views:

321

answers:

2

And i have a simple modelform for Package

from models import Package
from django import forms

class PackageForm(forms.ModelForm):
class Meta:
    model= Package
    fields= ['name', 'version', 'url', 'description', 'arch', 'dependancies', 'conflicts', 'file']

How can i ask the modelform to check, within validation, if the file extension (class is FileField) is .sh for example?

is there a way to put this in modelform? of can i only manage it in a view?

Thanks

Edit: Also, forgot to ask, the model has a Foreignkey to the auth User model... which is going to contain the current user.. how can modelform manage that?

Thanks again

+2  A: 

You should read the django documentatino on doing exttra validation: http://docs.djangoproject.com/en/1.1/ref/forms/validation/#ref-forms-validation You just need to define a clean_file() method.

Alex Gaynor
That's great! :D i'll be using that :D but in the case of a fileField, is 'value' a File object? if so how can i evaluate it's extension?
PirosB3
value.name should be the name, I think.
Alex Gaynor
A: 

Thanks for the answer! i'm getting hold of this.. although i encounter a problem

Package contains a foreignkey to django.contrib.auth.models User model, When the form is processed how can i tell the modelform to pass the current user object to the model instance? i thought of this...

views.py

def add(request):
if request.method == 'POST':
    the_model= PackageForm(request.user, request.POST, request.FILES)
    if the_model.is_valid():
        the_model.save()

i overwrited the init in modelform:

from models import Package
from django import forms

class PackageForm(forms.ModelForm):
def __init__(self,user,*args,**kwargs):
        super (PackageForm,self ).__init__(*args,**kwargs) # populates the post
        self.fields['maintainer_name'].queryset = user # adds the user object passed by add in views.py
class Meta:
    model= Package
    fields= ['name', 'version', 'url', 'description', 'arch', 'dependancies', 'conflicts', 'file']

manteiner_name is the ForeignKey(User) object... it gives me a keyerror :( that's not good... Any solutions?

Thanks!

PirosB3