【问题标题】:How to test checked radio button from views.py?如何从views.py测试选中的单选按钮?
【发布时间】:2016-04-15 17:06:20
【问题描述】:

我有一个 django 项目,其中我的主页包含单选按钮,这使我有机会转到另一个应用程序或显示消息。我认为我对检查按钮的测试没有正确编写。 日志/views.py

from django.shortcuts import render
from django.contrib.auth.decorators import login_required,user_passes_test
from aps import views
from django.http import HttpResponse

@login_required()
def home(request):
    if request.user.is_superuser:
        return render(request,"home.html") 
        if ('choix1').checked  in request.POST:
            return HttpResponse("hedha lmail")
        elif 'choix2'  in request.POST:
            return HttpResponse("hedha ltemps")
        elif 'choix3'  in request.POST:
            return views.index(request)
        else :
            return HttpResponse("You have not chosenn ay choice")
    else:
        return views.index(request)

home.html

{% extends 'base.html' %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="jumbotron">
            <h1>Hello</h1>
            <p>You are on your account</p>

        </div>
        <div class="jumbotron">
            
<FORM>
<p>you have the opprtunity to : </P>
<INPUT type= "radio" name="choix1" id="choix1" value="mail"> change mail sender
<INPUT type= "radio" name="choix2" id="choix2" value="temps"> change frequency of getting temperqture sensor's value
<INPUT type= "radio" name="choix3" id="choix3" value="graph"> show graph  <br>
<INPUT type= "submit" value="ok"> 
</FORM>
        </div>
    </div>
</div>

{% endblock %}

【问题讨论】:

    标签: python html django


    【解决方案1】:

    首先,删除

    return render(request,"home.html") 
    

    因为您的应用没有到达if 检查。

    另外,将 POST 方法添加到您的 html 表单中:

    <form method="POST">
    

    查看是否选择了收音机:

    if 'choix1' in request.POST:
        ...
    

    【讨论】:

    • 我把它改成了禁止访问(CSRF 令牌丢失或不正确。):/log/ 和 home .html 我无法删除它,因为超级用户应该首先访问主页
    • MIDDLEWARE_CLASSES 中的settings.py 文件中删除django.middleware.csrf.CsrfViewMiddleware
    • 谢谢,但即使我删除了它也不起作用。
    【解决方案2】:
    @login_required()
    def home(request):
        if request.user.is_superuser:
            return render(request,"home.html")           #this line I am talking about
            if ('choix1').checked  in request.POST:
                return HttpResponse("hedha lmail")
            elif 'choix2'  in request.POST:
                return HttpResponse("hedha ltemps")
            elif 'choix3'  in request.POST:
                return views.index(request)
            else :
                return HttpResponse("You have not chosenn ay choice")
        else:
            return views.index(request)
    

    在上述方法的第 4 行中,您将在检查任何条件之前返回您的方法。

    【讨论】:

    • 超级用户必须在 home.html 中选择一个按钮,选中的按钮将使他有机会访问另一个应用程序或显示消息
    猜你喜欢
    • 2017-09-05
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多