【问题标题】:Django request.Get passing variables to next pageDjango request.Get 将变量传递到下一页
【发布时间】:2012-05-16 04:29:50
【问题描述】:

我有一个关于请求的基本问题。进入 Django。我在下面给出了我的表单声明

现在,我需要将 v.position 传递到下一页。如果我的 v.position 已填充,如何验证 request.get

例如:- 下面的代码是否正确?

volpostion = request.GET['志愿者职位'].strip()

如果 volposition 执行所需的功能。

我读到了那个请求。Get 得到一个表单字段的字典。。这里的表单字段是指标签名称?

Forms.py

<tr>
        <th colspan=4 align="left"><label for="id_Volposition">Volunteer Position:</label></th>
        <th colspan=.5 align="left"><a href="/signups/new/{{ v.position }}" class="username" <u>{{ v.volposition }}</u></a></th>
<tr> <td colspan="2" height="2" style="display:none">&nbsp;</td> </tr>
</tr>

<tr>
        <th colspan=4 align="left"><label for="id_roledesc">Role Description:</label></th>
        <th colspan=.5 align="left">{{ v.roledesc }}</th>
<tr> <td colspan="2" height="2" style="display:none">&nbsp;</td> </tr>
</tr>

更多信息:

urls.py

urlpatterns = patterns('',
   (r'^new/$',                           sfp.view),
   (r'^volunteer/$',     volunteer_page),
   (r'^vollist/$', volunteer_list),
   (r'^volcont/$', volunteer_contact)

views.py

sfp = SimpleFormProcessing(
    form_class=VolunteerSignupForm,
    form_2_model=volunteersignupform_2_model,
    form2_class=VolunteerForm,
    form_template='signups/create_contact_form.dmpl',
    email_template='signups/response_email.dmpl',
    email_html_template='signups/response_email_html.dmpl',
    email_subject='Vibha Volunteer Signup',
    email_sender='volunteer@vibha.org',
    redirect_url='/signups/thanks/',
    do_captcha=True)

SimpleFormProcessing.py

from django.shortcuts import render_to_response
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.http import HttpResponseRedirect
from formwrappers import form_with_captcha, form_with_ipaddress
import pdb


class SimpleFormProcessing:

    def __init__(self, form_class, form_2_model, form2_class, form_template,
            email_template, email_subject, email_sender, redirect_url,
            do_captcha=False, record_ip_addr=False, email_html_template=None):
        self.form_class = form_class
        self.form_2_model = form_2_model
        self.form_template = form_template
        self.email_template = email_template
        self.email_html_template = email_html_template
        self.email_subject = email_subject
        self.email_sender = email_sender
        self.redirect_url = redirect_url
        self.do_captcha = do_captcha
        self.record_ip_addr = record_ip_addr

    def view(self, request, initial={}):
        pdb.set_trace()
        Form = self.form_class
        if self.do_captcha:
            Form = form_with_captcha(Form, request)
        if self.record_ip_addr:
            Form = form_with_ipaddress(Form, request)
        if request.method == 'POST':
            # Try processing the form
            if self.do_captcha and not accepts_cookies(request):
                return our_flatpage('Please enable cookies and try again.')
            else:
                form = Form(request.POST)
                if form.is_valid():
                    # The form is correct, process it
                    model = self.form_2_model(form)
                    if self.email_template:
                        text_content = render_to_string(self.email_template, {'model': model})
                        recipients = model.emailRecipients()
                        try:
                            bcc_recipients = model.emailBCCRecipients()
                        except:
                            bcc_recipients = None
                        msg = EmailMultiAlternatives(self.email_subject, text_content, self.email_sender,
                                recipients, bcc_recipients)

                        if self.email_html_template:
                            html_content = render_to_string(self.email_html_template, {'model': model})
                            msg.attach_alternative(html_content, "text/html")

                        msg.send()

                    return HttpResponseRedirect(self.redirect_url)
                else:
                    # Show the form with errors
                    return render_to_response(self.form_template, {'form': form})
        else:
            # Show the empty form

            form = Form(initial=initial)
            if self.do_captcha:
                accepts_cookies(request)

volunteer_list.dmpl

{% extends "base.dmpl" %}
{% block title %}User Registration{% endblock %}
{% block head %}User Registration{% endblock %}
{% block contentBox %}
<h2>Volunteer Opportunities</h2>
<p>Vibha is currently looking for volunteers interested in helping the organization in the following areas:</p>
<div class="relation">
<ul>
{% for k in teamrel %}
        <li align="left"><a href="#{{ k }} "> <b> {{ k}} </b> </a> </li>
{% endfor %}
</ul>
</div>

<p>If you are interested in any of these opportunities please contact us by clicking on the position you are interested and filling out the form.</p>
<p>&nbsp;</p>

<table>

{% for v in vollist %}
{% ifchanged  v.teamrelation %}
<tr>
<th colspan=7 align="left"><h3><a name="{{ v.teamrelation }}"> {{v.teamrelation}} </a> </h3></th>
</tr>
{% endifchanged %}


<tr>
        <th colspan=4 align="left"><label for="id_Volposition">Volunteer Position:</label></th>
        <th colspan=.5 align="left"><a href="/signups/new/{{ v.position }}" class="username" <u>{{ v.volposition }}</u></a></th>
<tr> <td colspan="2" height="2" style="display:none">&nbsp;</td> </tr>
</tr>

<tr>
        <th colspan=4 align="left"><label for="id_roledesc">Role Description:</label></th>
        <th colspan=.5 align="left">{{ v.roledesc }}</th>
<tr> <td colspan="2" height="2" style="display:none">&nbsp;</td> </tr>
</tr>
<tr>
        <th colspan=4 align="left"><label for="id_timereqt">Time Requirements:</label></th>
        <th colspan=.5 align="left">{{ v.noofhours }} hours per month</th>
<tr> <td colspan="2" height="2" style="display:none">&nbsp;</td> </tr>
</tr>
<tr>
        <th colspan=4 align="left"><label for="id_qualreqt">Qualification and Requirements:</label></th>
        <th colspan=.5 align="left">{{ v.Qualreqt }}</th>
<tr> <td colspan="2" height="2" style="display:none">&nbsp;</td> </tr>
</tr>
<tr>
        <th colspan=4 align="left"><label for="id_duration">Duration of the Role:</label></th>
        <th colspan=20 align="left">  {{ v.Duration}} {{ v.Durationyrmon}}</th>
<tr> <td colspan="10" height="20" style="display:none">&nbsp;</td> </tr>
</tr>
{% endfor %}

</table>

{% endblock %}

【问题讨论】:

  • 您的forms.py 包含html?我在您的问题上既没有看到表单也没有看到 django 表单。还有什么是“v”。我们应该知道吗?
  • 对不起,我没有使用表单。它是一个 html 页面。志愿者职位将被传递。如果视图中填充了志愿者职位,我需要知道如何访问该职位。
  • 首先阅读文档:docs.djangoproject.com/en/dev/topics/forms 并发布更多代码,您的视图是什么样的?

标签: django django-forms django-views


【解决方案1】:

您的问题很难解读,但据我所知,这里有一些提示:

  1. request.GET 和 request.POST 字典的键(取决于使用的方法)将是字段的 HTML name 属性,而不是它们的标签。您没有发布任何包含任何字段的代码,但总的来说,如果您有类似的内容:

    <input type="hidden" name="volposition" value="0">
    

    然后,您会找到以下值:

    request.POST['volposition']
    
  2. 当您不确定该键是否存在时,请始终在字典中使用.get() 方法。如果密钥不存在,您拥有的代码将引发IndexError 异常。例如:

    volposition = request.GET.get('volposition')
    
  3. 实际上应始终通过POST 方法发送表单。 罕见 例外是搜索表单之类的东西,其中将提交的值作为查询字符串更有意义(这些通常通过GET 方法发送)。经验法则是,如果您出于只读目的请求资源,请使用GET。例如,搜索 Google,不会更改任何内容,您只是请求搜索结果列表,因此使用了 GET。但是,如果您正在进行任何类型的修改(创建、编辑,甚至只是更新会话数据...任何实际影响某种更改 的内容),那么您可以使用POST。您也不应该将两者混为一谈。例如,不要将POST 发送到带有查询字符串的 URL。

说了这么多。您应该能够使用以下内容覆盖您的基地:

{% if request.REQUEST.volposition %}
<input type="hidden" name="volposition" value="{{ request.REQUEST.volposition }}">
{% endif %}

request.REQUEST 包含通过 URL 传递的参数,无论是 GET 还是 POST。当您知道将发送什么方法数据时,请始终使用request.GET 或request.POST,但在这种情况下,您只需要该值并且它可能来自任一方法,@987654341 @ 是可以接受的。

如果键确实 存在,那么隐藏的输入将以其值呈现。无论数据如何发送,volposition 现在都会传递。

【讨论】:

  • 作为一般说明,赞成/接受您得到的答案被认为是一种很好的形式 - 这样问题就会被认为已得到回答,并且用户会因他们的工作而获得赞誉。
猜你喜欢
  • 2013-09-14
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
  • 2016-02-19
  • 1970-01-01
相关资源
最近更新 更多