How to limit file types on file uploads for ModelForms with FileFields?

Create a validation method like: def validate_file_extension(value): if not value.name.endswith(‘.pdf’): raise ValidationError(u’Error message’) and include it on the FileField validators like this: actual_file = models.FileField(upload_to=’uploaded_files’, validators=[validate_file_extension]) Also, instead of manually setting which extensions your model allows, you should create a list on your setting.py and iterate over it. Edit To filter for multiple files: def … Read more

ModelForm with OneToOneField in Django

You have to create second form for PrinterAddress and handle both forms in you view: if all((profile_form.is_valid(), address_form.is_valid())): profile = profile_form.save() address = address_form.save(commit=False) address.printer_profile = profile address.save() Of course in the template you need to show both forms under one <form> tag 🙂 <form action=”” method=”post”> {% csrf_token %} {{ profile_form }} {{ address_form … Read more

Django Forms: pass parameter to form

You should define the __init__ method of your form, like that: class StylesForm(forms.Form): def __init__(self,*args,**kwargs): self.site_id = kwargs.pop(‘site_id’) super(StylesForm,self).__init__(*args,**kwargs) of course you cannot access self.site_id until the object has been created, so the line: height = forms.CharField(widget=forms.TextInput(attrs={‘size’:site_id})) makes no sense. You have to add the attribute to the widget after the form has been created. … Read more

Django’s forms.Form vs forms.ModelForm

Forms created from forms.Form are manually configured by you. You’re better off using these for forms that do not directly interact with models. For example a contact form, or a newsletter subscription form, where you might not necessarily be interacting with the database. Where as a form created from forms.ModelForm will be automatically created and … Read more

resize image on save

I recommend using StdImageField from django-stdimage, it should handle all the dirty work for you. It’s easy to use, you just specify the dimensions of the resized image in the field definition: class MyModel(models.Model): image = StdImageField(upload_to=’path/to/img’, size=(640, 480)) Check out the docs — it can do thumbnails also.