radio buttons display form

2019-09-15 06:06发布

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)

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)

The html of the template

   { % 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>

1条回答
仙女界的扛把子
2楼-- · 2019-09-15 06:38

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 
查看更多
登录 后发表回答