Django-在相同的网址中有两个视图 [英] Django - Having two views in same url

查看:85
本文介绍了Django-在相同的网址中有两个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在django中创建一个网站,我想在我的主页中显示我最近的博客文章的列表以及下面一些要填写的联系表格。博客和联系表分别工作正常。但是我想将它们包括在同一页面中(显然在同一URL中)。

I am making a website in django and in my homepage I want to show the list of my recent blog post and a few blocks below I want to make a simple contact form. The blog and the contact form separately are working fine. But I want to include them in the same page(obviously in the same url).

views.py是:

The views.py is:

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,则:

If you want to look at the forms.py then :

from django import forms

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

我主页的urls.py中的urlpattern为:

The urlpattern in urls.py of my homepage is:

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'),
]

使用此urlpatter列表的博客文章完美显示,但没有显示联系表单。但是,随着下面的urlpattern联系人表单出现,但博客帖子没有出现。

With this urlpatter the list of blog post shows up perfectly but the contact form doesn't show up. But with the below urlpattern contact form shows up but blog posts doesn't show up.

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")),
]

我想使这两个内容都显示在同一页面中。请帮我。如果需要更多信息,请告知。

I want to make both of these contents show up in the same page. Please help me. If you need any more information then do tell.

推荐答案

虽然不能直接执行此操作,但可以在视图中考虑函数。 py以某种方式处理请求,即当它从一个模型收到发布请求时,仅初始化相应模型的表单。为此,您需要为按钮分配一个名称。参见下面的代码-

While you cannot do that directly, you could consider your function in views.py to handle the request in a way that when it gets a post request from one model then it initialises the form for the respective model only. For this to happen you will need to assign a name to your button. See below code -

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})

这篇关于Django-在相同的网址中有两个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆