简体   繁体   中英

From views, how do I pass both context and registration form to my registration template?

I'm fairly new to Django and I'm trying to pass both the context and my registration form. I know how to pass either the context, or the form, but not both. Check the last line of the code, that's what I'm trying to figure out.

I've tried:
return render(request, 'users/register.html', context, {'form': form})
and it doesn't work. There's something wrong with the syntax.

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm

def register(request):
    context = {
        'title': "Register",
        'page_title': "Golf App - Register",
        'login_title': "Login"
    }
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account Created for {username}!')
            return redirect('golf-home')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})

I'm trying to get it so that I can use both the context and form in the template.

只需将表单放在上下文中

context['form'] = UserRegisterForm()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM