简体   繁体   中英

Django: How do I call a model function in views that accesses form data and stores the result in the database?

I am a beginner in Django. I am developing an app in Django. I need to store the result of a form in the database, and call a function in views, and then store the result of that function in my database again. In models.py, this is my model class with the calculate function:

class f1New(models.Model):
    v1 = models.CharField(max_length=5)
    u1 = models.CharField(max_length=5)
    a1 = models.CharField(max_length=5)
    t1 = models.CharField(max_length=5)
    def calculate(v1,u1,a1,t1):
        v1 = u1 + a1

In views.py,

def f1(request):
    context = RequestContext(request)
    if request.method == 'POST':
        form = f1Form(request.POST)
        if form.is_valid():
            form.save(commit=True)
            f1.calculate(form[v1],form[u1],form[a1],form[t1])
            return question_list(request)
        else:
            print form.errors
    else:
        print ("Not Post")
    return render_to_response('question_list.html', {'form': form}, context)

I do not know if this is correct, and don't know how to check it. Any help would be highly appreciated. :)

I have absolutely no idea what you are asking here. As Rajesh comments, if v1 is always calculated from the other elements, why are you accepting it in the form at all?

It's possible that you are after this:

class F1Model(models.Model):
    ...
    def calculate(self):
        self.v1 = self.u1 + self.a1

class F1Form(forms.ModelForm):
    class Meta:
        exclude = ('v1',)

def f1(request):
    if request.method == 'POST':
        form = F1Form(request.POST)
        if form.is_valid():
            f1instance = form.save(commit=False)
            f1instance.calculate()
            f1instance.save()
            return redirect('question_list')
    else:
        form = F1Form()
    return render(request, 'question_list.html', {'form': form})

but it's impossible to tell for sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM