How do I add a placeholder on a CharField in Django?

Look at the widgets documentation. Basically it would look like: q = forms.CharField(label=”search”, widget=forms.TextInput(attrs={‘placeholder’: ‘Search’})) More writing, yes, but the separation allows for better abstraction of more complicated cases. You can also declare a widgets attribute containing a <field name> => <widget instance> mapping directly on the Meta of your ModelForm sub-class.

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

Putting a django login form on every page

Ok, I eventually found a way of doing this, although I’m sure there are better ways. I created a new middleware class called LoginFormMiddleware. In the process_request method, handle the form more or less the way the auth login view does: class LoginFormMiddleware(object): def process_request(self, request): # if the top login form has been posted … Read more

How does Django Know the Order to Render Form Fields?

New to Django 1.9 is Form.field_order and Form.order_fields(). # forms.Form example class SignupForm(forms.Form): password = … email = … username = … field_order = [‘username’, ’email’, ‘password’] # forms.ModelForm example class UserAccount(forms.ModelForm): custom_field = models.CharField(max_length=254) def Meta: model = User fields = (‘username’, ’email’) field_order = [‘username’, ‘custom_field’, ‘password’]

Create Custom Error Messages with Model Forms

New in Django 1.6: ModelForm accepts several new Meta options. Fields included in the localized_fields list will be localized (by setting localize on the form field). The labels, help_texts and error_messages options may be used to customize the default fields, see Overriding the default fields for details. From that: class AuthorForm(ModelForm): class Meta: model = … Read more

How to update an object from edit form in Django?

Why don’t you just use ModelForm? # forms.py # … class MyForm(forms.ModelForm): class Meta: model = MyModel # views.py # … def my_view(request, id): instance = get_object_or_404(MyModel, id=id) form = MyForm(request.POST or None, instance=instance) if form.is_valid(): form.save() return redirect(‘next_view’) return render(request, ‘my_template.html’, {‘form’: form}) See https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#the-save-method for more details.