Shefali
Shefali

Reputation: 251

Accessing model attributes in the template in django

this is a snippet of the views.py of my django app.i have used modelform to create a form. the models.py has a class user which has an attibute username. i want to redirect the registration page to a view 'redirect' but also i want to pass the name of the user which is obtained after we hit the submit button on the form and the data gets stored in the instance 'new_form'.

def registration(request):
    if request.method=='POST':
        form=userForm(request.POST)
        if form.is_valid():
            name=form.cleaned_data['username']
            new_form=form.save()

            return HttpResponseRedirect(reverse('redirect'))
    else:
        form=userForm()
    return render(request,'student/registration.html',{'form':form})

my redirect.html looks something like this.

<h1>You have signed up.</h1>
<p>hello {{field.name}}</p>

but the problem is that name is not being displayed after hello which is obvious because i haven't passed anything with reverse('redirect'). So how do i do that? And is there any problem with my redirect.html also?

Upvotes: 1

Views: 1631

Answers (2)

Astik Anand
Astik Anand

Reputation: 13057

Make a context dictionary and send.

def registration(request):
    context ={}
    if request.method=='POST':
        form=userForm(request.POST)
        if form.is_valid():
            name=form.cleaned_data['username']
            context['name']=name
            new_form=form.save()

            return render(request,'student/registration.html',context)
    else:
        form=userForm()
        context['form']=form
    return render(request,'student/registration.html',context)

Now html

<h1>You have signed up.</h1>
<p>hello {{name}}</p>

Upvotes: 1

kartikmaji
kartikmaji

Reputation: 976

Instead of return HttpResponseRedirect(reverse('redirect')).

Use return render(request, 'redirect.html', {'name': name}).

And edit your redirect.html to

<h1>You have signed up.</h1>
<p>hello {{name}}</p>

Hope this helps.

Upvotes: 2

Related Questions