Reputation: 1479
I am following a Django tutorial where the blog
app and users
app are separate. Upon registering as a user I would like the user to be redirected to a view in the blog
app. Here is the users
app views.py
:
def register(request):
if request.method == 'POST': # if form was submitted w data
form = UserCreationForm(request.POST) #instantiate form w post data
if form.is_valid():
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}')
return redirect('blog-home') #not working
else:
form = UserCreationForm()
return render(request, 'users/register.html', {'form':form})
and here is the blog
app's views.py
:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Post
# Create your views here.
def home(request):
posts = Post.objects.all()
return render(request, 'blog/home.html', {'posts':posts})
and the url pattern tied to said view:
path('', views.home, name = 'blog-home'),
When a user submits the form, I get the following error: Reverse for 'home' not found. 'home' is not a valid view function or pattern name.
I am not sure why this is, I believe I copied the code word for word and the example in the video is working.
Upvotes: 0
Views: 47
Reputation: 7330
In your app's urls.py mention app_name so that you can redirect to any app's views.
blog/urls.py
app_name = 'blog'
urlpatterns =[...
]
Now you can redirect to the blog app home view like this
return redirect ('blog:blog_home')
#return redirect ('app_name:url_name')
Upvotes: 2
Reputation: 2029
If you want to redirect to url named 'blog-home' you need to reverse('blog-home').
Your url isn't called 'home' but 'blog-home'. Your error mention that you tried to reverse for 'home'.
It should work if you change your view:
def register(request):
if request.method == 'POST': # if form was submitted w data
form = UserCreationForm(request.POST) #instantiate form w post data
if form.is_valid():
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}')
return redirect(reverse('blog-home'))
else:
form = UserCreationForm()
return render(request, 'users/register.html', {'form':form})
Upvotes: 0