单选按钮显示形式 [英] radio buttons display form

查看:65
本文介绍了单选按钮显示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单中有3个单选按钮,当我单击每个按钮时,会出现一个表单,并且我的回测参数更改。问题是,当我单击保存按钮时,什么也不会保存。在添加单选按钮的检查之前,保存按钮一直在工作。单击单选按钮可更改参数策略。当我检查单选按钮但不知道如何解决时,该错误与保存功能有关。

I have in my form 3 radio buttons, when i click on each one a form appears and a parameter of my backtesting change. The problem is that when i click on save buttons nothing is saved. Before I added the check of radio buttons the save buttons was working. The click on radio buttons change the strategy of parameters. The error is with the save function when i check the radio buttons but i don't know how to resolve it.

Models.py

class Parameters(models.Model):

MARKET= ((1,'Nasdaq'),(2, 'Nyse'),(3,'Amex'),)  


SECTOR_CHOICES = ((1,'Utilities'),(2, 'Basic Materials'),(3,'Healthcare'), (4,'Services'),(5,'Financial'),)




user = models.ForeignKey(User)
title = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to the chosen parameters')
type = models.CharField('forecast type', choices=FORECAST_TYPES, max_length=20, default="backtest")
strategy = models.CharField('Strategy', choices=STRATEGY_CHOICES, max_length=20,default="Long")

#input characteristics
price_1_min = models.FloatField('1. Price, min', default=0.1, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
price_1_max = models.FloatField('1. Price, max', default=20000, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
stocks_num_2_min     = models.IntegerField('2. Number of selected stock, min', default=3, validators=[MinValueValidator(0), MaxValueValidator(100)])
stocks_num_2_max     = models.IntegerField('2. Number of selected stock, max', default=7, validators=[MinValueValidator(1),])
    holding_period = models.IntegerField('3. Holding Period', default=1, validators=[MinValueValidator(1),])


    volume = models.IntegerField('4. Volume', default=0, validators=[MinValueValidator(0),])
    market = models.CharField('Market', max_length=30, null=True)
    sector = models.CharField('Sector', max_length=30, null=True)

将参数保存在表中的html:

The html where the parameters are saved in a table:

 {% extends 'base.html' %}
 {% block content %}

   <div> {% if user.is_authenticated %}
            {% if user.profile.is_active %}
               &nbsp; Saved from "Backtesting"
                <ul>
                    {% for param in user.parameters_set.all %}
                        {% if param.type == "backtest" %}

                           <table style="width:100%">
                                    <tr>
                                         <th> Saved File </th>
                                         <th> Created at </th>              
                                     <tr> 

                                     <td> <a href='{{param.get_backtest_url}}'>{{param.title}}  </a> </td>
                                     <td> {{param.created_at}} </td>
                                     <td> {{param.strategy}} </td>

                              </tr>
                             </table>

                        {% endif %}
                    {% endfor %}
                </ul>
                            {% else %}
                <p>
                You are logged in but your account has expired. You can reactivate your account by buying one of <a href="{% url 'pricing' %}">our services</a>. You are welcome however to keep using our free services!
                </p>
            {% endif %}
{% else %}
                            <p>
If you "login" you can save your parameters for future use. Please <a href="{% url 'auth_login' %}">login</a>, or <a href="{% url 'registration_register' %}">register</a> and get <strong><span class = "greenText">1 Month free trial</span></strong>.
                            </p>
{% endif %}
    </div>      

{% endblock %}

View.py

def backtest(request, pk=None):

if pk is not None:
    param = get_object_or_404(Parameters, pk=pk, user=request.user)
    form = BacktestForm(request.POST or None, instance=param)
else:
    form = BacktestForm(request.POST or None)

    if request.method == 'POST':
    if form.is_valid():
        if 'save' in request.POST:
                            obj = form.save(commit= False)
                            obj.user = request.user
                            if ('toggle-tab1').checked  in request.POST:
             obj.strategy="Long"
                            elif ('toggle-tab2').checked  in request.POST: 
                             obj.strategy="Short" 
                            else : 
                             obj.strategy="Long and Short "



                obj.type = "backtest"

                obj.save()

                messages.info(request, 'Saved!')
            return redirect(obj.get_backtest_url())

                    else:
                            obj = ForecastQueue.create(request.user, 'backtest', json.dumps(request.POST))
            obj.save()
                            return redirect(obj.get_url())

            else:
        messages.info(request, 'Please check entered data')
        data = {
            'active_page': 'backtest',
            'form': form,}

else:
            data = {'active_page': 'backtest',
        'form': form,
    }
return render(request, 'backtest.html', data)

模板的html

   { % extends 'base.html' %}
   {% block title %}Backtesting{% endblock %}
   {% block content %}
<div class="page-header">
    <h1>Backtesting{% if form.instance.pk %}: {{form.instance.title}} {% endif %} <a data-toggle="popover" data-content="
    <img src='{{STATIC_URL}}img/tutorial/documentation/img20.png'class='img-responsive img-rounded'/>
        "><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span></a></h1>
    </div>
    <div class="row">
    <div class='col-md-9'> 
              <div id="tabs">

               <input type="radio" name="tabs" id="toggle-tab1"  checked="checked" />
               <label for="toggle-tab1">Long</label>

               <input type="radio" name="tabs" id="toggle-tab2"    />
               <label for="toggle-tab2">Short</label>

               <input type="radio" name="tabs" id="toggle-tab3"   />
               <label for="toggle-tab3">Long and Short</label>
               <div id="tab1" class="tab"  >
        <form action="{% url "backtest" %}" method='POST' role='form' id='form'>
            {% csrf_token %}


            {% include 'tags/parameters_form.html' %}
            <br />
            {% include 'tags/parameters_backtest_form.html' %}
            <br/>


                            {% if user.is_authenticated %}
                            <input type='submit' id='run' value='Run' class='btn btn-default'>

                {% if user.profile.is_active %}
                    Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
                {% else %}
                    <p>
                    Expired account! you need to reactivate in order to save parameters.
                    </p>
                {% endif %}
            {% else %}
                                     Please <a href="{% url 'auth_login' %}">login</a> in order to Run backtesting!
                 </br>
                 Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).   

                              {% endif %}                        


                    </form>


推荐答案

在表单标签中添加所有3个单选字段,如下所示,

Add all 3 radio field in form tag like below and add value of each radio button different value.

<form action="{% url "backtest" %}" method='POST' role='form' id='form'>
            {% csrf_token %}
      <input type="radio" name="tabs" value="first" id="toggle-tab1"  checked="checked" />
               <label for="toggle-tab1">Long</label>

               <input type="radio" name="tabs" value="second" id="toggle-tab2"    />
               <label for="toggle-tab2">Short</label>

               <input type="radio" name="tabs" value="third"  id="toggle-tab3"   />
               <label for="toggle-tab3">Long and Short</label>

....

提交此表格时,您将获得选项卡中的值。因此请遵循以下代码。

When you submit this form you will get "tabs" in request.POST with value, So follow below code in view.

 if form.is_valid():
    if 'save' in request.POST:
                            obj = form.save(commit= False)
                            obj.user = request.user
                            tab_value = request.POST.get('tabs')
                            if tab_value == 'first':
             obj.strategy="Long"
                            elif tab_value == 'second': 
                             obj.strategy="Short" 
                            else : 
                             obj.strategy="Long and Short 

这篇关于单选按钮显示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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