3

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


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!

4

1 回答 1

6

You should read the Django documentation on doing extra validation:

You just need to define a clean_file() method.

于 2010-02-05T22:00:05.323 回答