Django Set Default Form Values

Django set default form values

You can use Form.initial, which is explained here.

You have two options either populate the value when calling form constructor:

form = JournalForm(initial={'tank': 123})

or set the value in the form definition:

tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

Django - How Do I Set A Default Value In A Form To Be The Current User?

You should disable the field, not just add a readonly attribute to the widget, since a "hacker" can forge a malicious HTTP request that sets the author to another user:

class PostForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['author'].disabled = True

class Meta:
model = Post
fields = ('title', 'author', 'category', 'site', 'body')
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'author': forms.Select(attrs={'class': 'form-control'}),
'category': forms.Select(choices=choice_list,attrs={'class': 'form-control'}),
'site': forms.Select(choices=site_choice_list,attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control'})
}

We can then use this form in a view with:

from django.contrib.auth.mixins import LoginRequiredMixin

class AddPostView(LoginRequiredMixin, CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'

def get_initial(self):
return {'author': self.request.user}

The LoginRequiredMixin mixin [Django-doc] guarantees that only users that have logged in can see (and interact with) the view.

set a default value in user form django

I think I understand what you were asking. If you are going to use a ModelForm you should look here into how the class meta: works for ModelForm This should get you started with having an additional field in the form. If you are adding some extra data to the User model you will need to extend the user model with AbstractUserand add the 'additional_field'.

from django import forms
from django.contrib.auth.models import User

class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput, min_length=6)
confirm_password = forms.CharField(widget=forms.PasswordInput(), min_length=6)
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.EmailField(max_length=254)
additional_field = forms.CharField(max_length=100)

def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['additional_field'].disabled = True
self.fields['additional_field'].initial = 'SOME INITIAL VALUE'

Set initial value in django model form

You can override __init__ to also get your fields, and set their initial like so:

class CreateOrderForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

self.fields['my_field'].initial = 'my_initial'

Django don't display default value in form field

One way would be removing the defaults you have set in your models.

Then setting required attribute to False in forms.py.

   widgets = {
'form_item': forms.TextInput(attrs={'class': 'form-control', 'required': False})
}

and in your forms, when cleaning do something like

def clean_<field_name>(self):
value = self.cleaned_data[<field_name>]
if not value:
return 'OEM'
...whatever other cleaning you want
return value

If Django does interpet the empty string as valid(skips the if block), then just do

if value == '':
...run logic

Unable to set default form values in Django

So I finally found my mistake. Reading the Django documentation tells me the following:

This is why initial values are only displayed for unbound forms. For bound forms, the HTML output will use the bound data.

This part of the documentation explains the meaning of bound and unbound forms, giving form = NameForm(request.POST) as an example of a bound form.

Therefore, to solve the posted problem, I changed my views.py code as such:

def my_view(request, template_name="path/to/template"):
form = MyForm(request.POST or None, initial={
'field_one': field_one_default,
'field_two': field_two_default,
})

...

Django: Set a dropdown form field to a value from the current detail view's Model

Found the answer after posting. For anyone else looking for the answer.

When creating a new form instance (in my case within the get_context_data of my detail view class) use the initial parameter:

context['change_stage_form'] = ChangeStageForm(initial={
'assessment_stage': self.object.assessment_stage
})

Django Forms Docs: https://docs.djangoproject.com/en/dev/ref/forms/api/#initial-form-values

Thank you to: https://stackoverflow.com/a/813474/16395136

How to make a select field using Django model forms (using set values)?

Here you can use ModelChoiceField provided by django forms. Define a Country model containing all the countries, and use that as a QuerySet here. It will be also be dynamic that can be changed later.

from django import forms
from .models import Trip, Country

class TripForm(forms.ModelForm):
class Meta:
model = Trip
fields = ['name', 'country', 'start_date', 'end_date']


country = forms.ModelChoiceField(
queryset=Country.objects.all(),
to_field_name='name',
required=True,
widget=forms.Select(attrs={'class': 'form-control'})
)

Django sets a default value to model input

In your view you are passing a reference to your Field model as the argument instance. Doing this places the representation of the model fields into your form fields when it is rendered. If what you are wanting is just a blank form when you load the page then just remove the instance argument and create your form in your else statment, like form = FieldForm(). The instance argument is only needed for a form if you are trying to pre-populate data into the form, for example if you made a view where you wanted to update information on an already created object you would pass an instance of your model to the instance argument.



Related Topics



Leave a reply



Submit