Data validation in Django ModelForm

And I have a simple model for the 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 modelform to check, as part of the check, if the file extension (the class is FileField) is .sh, for example?

Is there any way to put this in modelform? can i only control it in view?

thank

Edit: Also, I forgot to ask, the model has a Foreignkey for auth User model ... which is going to contain the current user. How can this drive the model?

Thanks again


Thanks for the answer! I understand that this is ... although I ran into a problem

The package contains a foreign key for django.contrib.auth.models user model. When the form is processed, how can I pass modelform to pass the current user object to the model instance? I thought about it ...

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 init 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 - ForeignKey ()... :( ... ?

!

+3
1
+6

Source: https://habr.com/ru/post/1731619/


All Articles