faro
faro

Reputation: 89

django issues between forms and models

i am a beginner with Django. I want to ask how can i access a variable in forms.py to print out for the user. I know that models.py create the database for the user. The variable that i want to print it is a checkbox multiple choice field. I need to print the value of the multiplechoice in a table.The image is here This is the Form.py:

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

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

This is my view.py for the button save:

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

Upvotes: 0

Views: 79

Answers (1)

IVI
IVI

Reputation: 2116

Please post the full forms class. I don't see how your model and form is connected. I think you might need a modelform instead of a form if you want to access the model.

So the way to connect them would be like this

forms.py

from .models import Parameter
class ParameterForm(forms.ModelForm):
    market = forms.MultipleChoiceField(required=False,widget=CheckboxSelectMultiple, choices=MARKET_CHOICES)
    sector = forms.MultipleChoiceField(required=False,widget=CheckboxSelectMultiple, choices= MEDIA_CHOICES)

        class Meta:
            model = Parameters

Upvotes: 1

Related Questions