Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating data in Django ModelForm

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!

like image 296
PirosB3 Avatar asked Dec 12 '25 01:12

PirosB3


1 Answers

You should read the Django documentation on doing extra validation:

You just need to define a clean_file() method.

like image 109
Alex Gaynor Avatar answered Dec 14 '25 01:12

Alex Gaynor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!