K
K
KarenG2015-05-19 23:57:52
Django
KarenG, 2015-05-19 23:57:52

How to automatically increment a value in a form?

Good afternoon, I shoveled all the documentation, tried many ways, but I still can’t get the desired result.
There is a form that is bound to the User model. The User model has a "term" attribute that should be incremented by 1 each time a submit is clicked.
Here is what I wrote:
models.py

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.forms import ModelForm

class User(AbstractUser):
    term = models.IntegerField(default=1)

forms.py
from django import forms
from .models import User

class UserProfile(forms.ModelForm):
    term = forms.IntegerField()
    class Meta:
        model = User
        fields = ['term']

views.py
def main(request):
  args = {}
  args.update(csrf(request))
  args['term'] = auth.get_user(request).term
  if request.method == 'POST':
      a = User.objects.get(pk = 1)
      form = UserProfile(request.POST or None, instance = a)
      if form.is_valid():
          term = auth.get_user(request).term
          term += 1
          form.save()
          return redirect ('/base/main.html')
      else:
          args['form'] = form
  return render_to_response('base/main.html', RequestContext(request, args))

When you open the page, it displays a field where you can only specify the number yourself. I understand that the problem is in the form submission itself, but there seems to be a lack of understanding... please help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-05-20
@KarenG

Why does meta.fields need term at all if it is incremented?

user = form.save(commit=False)  # Получаем обновлённую модель юзера из формы.
user.term += 1
user.save()

PS Use Class Based Views. Really, you do not feel sorry for your time?
from django.views.generic import *

class YourFormView(FormView):
    form_class = UserProfile
    template_name = 'path/to/your_template.html'

    def form_valid(self, form):  # Вызывается, если форма is_valid
        user = form.save(commit=False)
        user.term += 1
        user.save()
        return # Чего вы хотите вернуть (обычно это редирект)

    def form_invalid(self, form):
        # Что-то делаем, если форма невалидна. По-умолчанию, джанго возвращает
        # на ту же страницу и показывает ошибки в форме.

But it's even better to override the form's save method and increment term there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question