简体   繁体   中英

How can I handle multiple views in one url?

I am working on Homepage that have until now two Views for one URL how can i handle it? i w'll make a Article and Form to get user information in the same page.

urls.py

from django.urls import path
from . import views

app_name = "LandingPage"

urlpatterns = [
    path('', views.form_page, name='form_page'),

]

views.py

from django.shortcuts import render, redirect
from django.utils import timezone
from multiurl import ContinueResolving
from .models import Article
from .forms import UserForm


# Article
def form_page(request):
    posts = Article.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'LandingPage/form_page.html', {'posts': posts})

# Add User
def user(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('LandingPage:form_page')
    else:
        form = UserForm()
    return render(request, 'LandingPage/user.html', {'form': form})

In the urls.py you added is only one view (but you wrote of two). You can combine the two view functions into one and make the same with the templates.

from django.shortcuts import render, redirect
from django.utils import timezone
from multiurl import ContinueResolving
from .models import Article
from .forms import UserForm


def form_page(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('LandingPage:form_page')
    else:
        form = UserForm()
    posts = Article.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'LandingPage/user.html', {'form': form, 'posts': posts})

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