Django -在同一个url中有两个视图

3vpjnl9f  于 2023-02-06  发布在  Go
关注(0)|答案(2)|浏览(128)

我在django做了一个网站,我想在主页上显示我最近的博客文章列表,在下面几个街区我想做一个简单的联系表单,博客和联系表单分开工作都很好,但是我想把它们放在同一个页面上(显然是在同一个网址上)。
网址views.py:

from .forms import NameForm

def get_name(request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    else:
        form = NameForm()
    return render(request, 'personal/index.html', {'form': form})

如果您想查看forms.py,请:

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

我的主页www.example.com中的url模式urls.py是:

urlpatterns = [
    url(r'^$', ListView.as_view(
                                queryset=Post.objects.all().order_by("-date")[:2],
                                template_name="personal/index.html")),
    url(r'^$', views.get_name, name='contact'),
]

使用这个url模式,博客文章列表会完美地显示出来,但是联系表单不会显示出来,但是使用下面的url模式,联系表单会显示出来,但是博客文章不会显示出来。

urlpatterns = [
    url(r'^$', views.get_name, name='contact'),
    url(r'^$', ListView.as_view(
                                queryset=Post.objects.all().order_by("-date")[:2],
                                template_name="personal/index.html")),
]

我想让这两个内容显示在同一页。请帮助我。如果你需要任何更多的信息,然后一定告诉。

zxlwwiss

zxlwwiss1#

同一个URL不能有多个视图。每个URL只能有一个视图。
在这种情况下,最简单的解决方法是更新get_name视图,使其包含模板上下文中的帖子。

def get_name(request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    else:
        form = NameForm()
    post_list = Post.objects.all().order_by("-date")[:2]
    return render(request, 'personal/index.html', {'form': form, 'post_list': post_list})

然后删除使用ListView的url模式,以便get_name处理请求。

dhxwm5r4

dhxwm5r42#

虽然你不能直接这么做,但是你可以考虑在www.example.com中使用你的函数views.py来处理请求,当它从一个模型中得到一个post请求时,它只为相应的模型初始化表单。要实现这一点,你需要为你的按钮指定一个名称。见下面的代码-

def SignUpLogin(request):
    message = ""
    Login_message = ""
    print(request.POST)
    if request.method == 'POST':
        if request.POST.get('UserForgotPassword') == 'Sign Up':
            form_SignUP_Login = LoginForm()
            print("POST request received")
            print(request.POST)
            form_SignUP=SignUpForm(request.POST)
            print(form_SignUP)
            if form_SignUP.is_valid():
                if request.POST["Password"] != request.POST["Confirm_Password"]:
                    message = "* Passwords do not match"
                    #raise forms.ValidationError(('Passwords do not match'), code="PasswordNotMatched")
                else:
                    try:
                        user = User.objects.get(username=request.POST["Username"])
                        context= {'form': form_SignUP, 'error':'* Username already taken. Please try different username.'}
                        return render(request, 'User/SignUp.html', context)
                    except User.DoesNotExist:
                        user = User.objects.create_user(request.POST["Username"], request.POST["Email"], request.POST["Password"])
                        user.first_name = request.POST["First_Name"]
                        user.last_name = request.POST["Last_Name"]
                        user.save()
                        form_SignUP = SignUpModel(Username = request.POST["Username"], First_Name = request.POST["First_Name"], Last_Name = request.POST["Last_Name"], Email = request.POST["Email"],  Company_Name = request.POST["Company_Name"], Address = request.POST["Address"], Password = make_password(request.POST["Password"]), Confirm_Password = make_password(request.POST["Confirm_Password"]), Phone_Number = request.POST["Phone_Number"])
                        form_SignUP.save()

                        #queryset = SignUpModel.objects.get(Username = request.POST["Username"])
                        #queryset.Password = "pwd_removed"
                        #queryset.Confirm_Password = "pwd_removed"
                        #queryset.save()
                        #send_email_to_host(request.POST["First_Name"], request.POST["Family_Name"], request.POST["Number_Of_Adults"], request.POST["Number_Of_Kids"], request.POST["Email"])
                        return redirect(HomePage)

        elif request.POST.get('UserLogin') == 'Login':
            form_SignUP = SignUpForm()
            form_SignUP_Login=LoginForm(request.POST)
            if form_SignUP_Login.is_valid():
                user = authenticate(username=request.POST["Username"], password=request.POST["Password"])
                if user is not None:
                    print("User authenticated")
                    return redirect(HomePage)
                else:
                    print("User not authenticated")
                    form_SignUP_Login = LoginForm()
                    Login_message = "Username and password combination is not correct"

        elif request.POST.get('UserForgotPassword') == 'Forgot Password':
            form_SignUP = SignUpForm()
            form_SignUP_Login = LoginForm()

    else:
        form_SignUP = SignUpForm()
        form_SignUP_Login = LoginForm()

    return render(request, 'User/SignUp.html', {'form' : form_SignUP, "error":message,'form_login' : form_SignUP_Login, "error_login":Login_message})

相关问题