Django formsets: make first required?

Found a better solution: class RequiredFormSet(BaseFormSet): def __init__(self, *args, **kwargs): super(RequiredFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False Then create your formset like this: MyFormSet = formset_factory(MyForm, formset=RequiredFormSet) I really don’t know why this wasn’t an option to begin with… but, whatever. It only took a few hours of my life to figure … Read more

Change Django ModelChoiceField to show users’ full names rather than usernames

You can setup a custom ModelChoiceField that will return whatever label you’d like. Place something like this within a fields.py or wherever applicable. class UserModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.get_full_name() Then when creating your form, simply use that field UserModelChoiceField(queryset=User.objects.filter(is_staff=False), required = False) More info can be found here

Can I have a Django form without Model

Yes. This is very much possible. You can read up on Form objects. It would be the same way you would treat a ModelForm, except that you are not bound by the model, and you have to explicitly declare all the form attributes. def form_handle(request): form = MyForm() if request.method==’POST’: form = MyForm(request.POST) if form.is_valid(): … Read more

Django form with choices but also with freetext option?

I would recommend a custom Widget approach, HTML5 allows you to have a free text input with a dropdown list which would work as a pick-one-or-write-other type of field, this is how I made it: fields.py from django import forms class ListTextWidget(forms.TextInput): def __init__(self, data_list, name, *args, **kwargs): super(ListTextWidget, self).__init__(*args, **kwargs) self._name = name self._list … Read more

How do I add a Foreign Key Field to a ModelForm in Django?

In regards to displaying a foreign key field in a form you can use the forms.ModelChoiceField and pass it a queryset. so, forms.py: class DocumentForm(forms.ModelForm): class Meta: model = Document def __init__(self, *args, **kwargs): user = kwargs.pop(‘user’,”) super(DocumentForm, self).__init__(*args, **kwargs) self.fields[‘user_defined_code’]=forms.ModelChoiceField(queryset=UserDefinedCode.objects.filter(owner=user)) views.py: def someview(request): if request.method==’post’: form=DocumentForm(request.POST, user=request.user) if form.is_valid(): selected_user_defined_code = form.cleaned_data.get(‘user_defined_code’) #do stuff … Read more