Lars
Lars

Reputation: 1270

How to set default values in Forms

I am Building a BlogApp and i am stuck on a Problem.

What i am trying to do :-

I am trying to set the Default Value in forms.py for a Form.

views.py

def new_topic(request,user_id):
    profiles = get_object_or_404(Profile,user_id=user_id)

    if request.method != 'POST':
        form = TopicForm()
    else:

        form = TopicForm(data=request.POST)
        new_topic = form.save(commit=False)
        new_topic.owner = profile
        new_topic.save()
        return redirect('mains:topics',user_id=user_id)

    #Display a blank or invalid form.
    context = {'form':form}
    return render(request, 'mains/new_topic.html', context)

forms.py

class TopicForm(forms.ModelForm):

    class Meta:
        model = Topic
        fields = ['topic_no','topic_title']

What have i tried :-

I also did by using initial , BUT this didn't work for me.

form = DairyForm(request.POST,request.FILES,initial={'topic_title': 'Hello World'})

The Problem

Default value is not showing when i open form in browser.

I don't know what to do

Any help would be appreciated.

Thank You in Advance

Upvotes: 0

Views: 220

Answers (2)

SaGaR
SaGaR

Reputation: 542

You have to use instance=TopicInstance If you want any specific instance to be default. Or you want any other initial you should pass it like this

def new_topic(request,user_id):
    profiles = get_object_or_404(Profile,user_id=user_id)

    if request.method != 'POST':
        form = TopicForm(initial={'topic_title': 'Hello World'})#When displaying it for first time
    else:

        form = TopicForm(data=request.POST)
        new_topic = form.save(commit=False)
        new_topic.owner = profile
        new_topic.save()
        return redirect('mains:topics',user_id=user_id)

    #Display a blank or invalid form.
    context = {'form':form}
    return render(request, 'mains/new_topic.html', context)

Upvotes: 1

ruddra
ruddra

Reputation: 51968

You need to pass initial in the GET method, like this:

if request.method == 'GET':
    form = TopicForm(initial={'topic_title': 'Hello World'})
else:

More information can be found in documentation.

Upvotes: 1

Related Questions