无法保存复选框数据

时间:2017-05-31 20:35:25

标签: django django-rest-framework

我真的很累,直到现在我还没有找到任何解决办法。我试图创建一个表来查看用户保存的所有数据。问题是models.py中的所有输入都被保存,不包括带复选框的参数。我不知道是什么问题。 models.py中的所有这些参数都保存在数据库中。

这是我的Models.py:

class Parameters(models.Model):

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

#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),])
limit_3                 = models.FloatField('3. Last price to upper straight, %', default=20, validators=[MinValueValidator(-200),])
learning_days_4_min         = models.IntegerField('4. Number of Learning days, min', default=1, validators=[MinValueValidator(1),MaxValueValidator(30)])
learning_days_4_max         = models.IntegerField('4. Number of Learning days, max', default=10, validators=[MinValueValidator(1),MaxValueValidator(30)])
evaluation_days_5           = models.IntegerField('5. Number of Evaluation days', default=10, validators=[MinValueValidator(1),MaxValueValidator(10)])
delay_days_6                = models.IntegerField('6. Number of “no quarterly reports” days (N)', default=10, validators=[MinValueValidator(0),MaxValueValidator(20)])
minimum_gain_7              = models.FloatField('7. Minimum gains for winners', default=0, validators=[MinValueValidator(0),MaxValueValidator(100)])
minimum_loss_8              = models.FloatField('8. Minimum losses for losers', default=0, validators=[MinValueValidator(-100),MaxValueValidator(0)])
total_gain_min_9            = models.FloatField('9. Minimum total gain', default=0, validators=[MinValueValidator(0),MaxValueValidator(100)])
winning_stock_percentage_min_10     = models.FloatField('10. Minimum percentage of winning stocks', default=60, validators=[MinValueValidator(0),MaxValueValidator(100)])


#input characteristics
period_start        = models.DateField('period, start', default=datetime.date(2013, 9, 25)) 
period_end      = models.DateField('end', default=datetime.datetime.today().date() - datetime.timedelta(days=16))
inital_capital      = models.IntegerField('Total initial capital, USD', default=100000, validators=[MinValueValidator(10000),])
fraction_to_invest  = models.FloatField('Percentage of the available capital to (re)invest', default=50, validators=[MinValueValidator(10), MaxValueValidator(90)])
minimum_cash        = models.IntegerField('Minimum cash to invest, %', default=5, validators=[MinValueValidator(1), MaxValueValidator(50)])
trades_fees         = models.FloatField('Trade fees, USD', default=8, validators=[MinValueValidator(0),])
stop_loss       = models.FloatField('Stop-Loss, %', default=-2, validators=[MinValueValidator(-50), MaxValueValidator(-1)])
target_gain     = models.FloatField('Target gain, %', default=5, validators=[MinValueValidator(1),])

created_at  = models.DateTimeField(u'created', auto_now_add=True)
updated_at  = models.DateTimeField(u'updated', auto_now=True)

这是forms.py:保存

后,所有带有multiplechoice字段的输入都为空
class BacktestForm(forms.ModelForm):

period_start = forms.DateField(initial=datetime.datetime.today().date() - datetime.timedelta(days=365+16), widget=forms.widgets.DateInput(format="%Y/%m/%d"), input_formats=["%Y/%m/%d"])
period_end  = forms.DateField(initial=datetime.datetime.today().date() - datetime.timedelta(days=16), widget=forms.widgets.DateInput(format="%Y/%m/%d"), input_formats=["%Y/%m/%d"])

    market = forms.MultipleChoiceField(required=False,widget=CheckboxSelectMultiple, choices=MARKET_CHOICES)
    sector = forms.MultipleChoiceField(required=False,widget=CheckboxSelectMultiple, choices= MEDIA_CHOICES)
class Meta:
    model = Parameters
    exclude = [
        'user',
        'type',
        'created_at', 
        'updated_at', 
        ]
    widgets={
        'title': forms.TextInput(attrs={'placeholder':'for ex. highLimitLowPrice'}),
        }

在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
            obj.type = "backtest"

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

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

1 个答案:

答案 0 :(得分:0)

在models.py

class Parameters(models.Model):
    ...
    MARKET = (
    (1,'First'),
    (2,'Second')
    )
    SECTOR= (
    (1,'First'),
    (2,'Second')
    )
    market = models.CharField('Market', max_length=30, null=True)
    sector= models.CharField('Sector', max_length=30, null=True)

    def display_sector_label(self)
        sectors= [(str(dict(self.SECTOR)[value])) for value in self.sector]
        return ", ".join(sectors)

    def display_market_label(self)
        markets = [(str(dict(self.MARKET)[value])) for value in self.market]
        return ", ".join(markets)

在forms.py

class BacktestForm(forms.ModelForm):
    market = forms.MultipleChoiceField(
        label='Market',
        choices=Parameters.MARKET,
        widget=forms.CheckboxSelectMultiple
    )
    sector = forms.MultipleChoiceField(
        label='Sector',
        choices=Parameters.SECTOR,
        widget=forms.CheckboxSelectMultiple
    )